diff --git a/tasks/agentescape-25-skeleton-19fca94f/environment/puzzle/worker.py b/tasks/agentescape-25-skeleton-19fca94f/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-25-skeleton-19fca94f/environment/puzzle/worker.py @@ -0,0 +1,73 @@ +"""Stateless Python tool worker. Never receives a scenario or reference values.""" + +import json +import os +import signal +import subprocess +import sys +import tempfile +import threading + +from fastapi import FastAPI +from pydantic import BaseModel, ConfigDict + +app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) +lock = threading.Lock() + + +class Execution(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + code: str + + +@app.get("/health") +def health(): + return {"ok": True} + + +@app.post("/execute") +def execute(request: Execution): + if len(request.code.encode()) > 65536: + return {"stdout": "Error: code exceeds 64 KiB limit"} + with lock, tempfile.TemporaryDirectory(prefix="escape-code-") as directory: + os.chown(directory, 65534, 65534) + with tempfile.TemporaryFile() as output: + process = subprocess.Popen( + [sys.executable, "-I", "/app/child.py"], + stdin=subprocess.PIPE, + stdout=output, + stderr=subprocess.DEVNULL, + cwd=directory, + user=65534, + group=65534, + extra_groups=[], + start_new_session=True, + env={"PATH": "/usr/local/bin:/usr/bin:/bin"}, + ) + try: + process.communicate( + json.dumps({"code": request.code}).encode(), timeout=5 + ) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + return {"stdout": "Error: Python execution timed out"} + finally: + # Also remove children still in the process group after normal exit. + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + output.seek(0) + value = output.read(65537) + if len(value) > 65536 or process.returncode != 0: + return { + "stdout": "Error: Python execution exceeded a resource limit or failed" + } + try: + result = json.loads(value) + if not isinstance(result.get("stdout"), str): + raise ValueError("Invalid worker response") + return result + except (ValueError, AttributeError): + return {"stdout": "Error: Python execution returned invalid output"} diff --git a/tasks/agentescape-25-skeleton-19fca94f/instruction.md b/tasks/agentescape-25-skeleton-19fca94f/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-25-skeleton-19fca94f/instruction.md @@ -0,0 +1,18 @@ +# Escape the room + +Discover the victory string and submit it with `escape submit-answer`. +Start with `escape observe`. This returns the room, available information, visible entities, and victory node ID. + +Use these commands (JSON responses): + +```sh +escape investigate NODE_ID +escape tool-call NODE_ID --arguments-json '{"parameter": "value"}' +escape use-item NODE_ID --arguments-json '{"parameter": "value"}' +escape submit-answer 'exact victory string' +escape state +``` + +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. + +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. diff --git a/tasks/agentescape-25-skeleton-19fca94f/solution/oracle.py b/tasks/agentescape-25-skeleton-19fca94f/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-25-skeleton-19fca94f/solution/oracle.py @@ -0,0 +1,133 @@ +"""Reference solver: use trusted inputs, but obtain the answer through public actions.""" + +import json +import urllib.request +from pathlib import Path + + +def http_action(base_url, payload): + request = urllib.request.Request( + base_url + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(request, timeout=30) as response: + return json.load(response) + + +def solve(scenario, act, observe): + nodes = {node["id"]: node for node in scenario["nodes"]} + visible = {entity["id"] for entity in observe["available_entities"]} + solved = set() + seen_outputs = {} + action_count = 0 + + def call(payload): + nonlocal action_count + action_count += 1 + response = act(payload) + visible.update(entity["id"] for entity in response.get("newly_revealed", [])) + if ( + response.get("episode", {}).get("termination_reason") + == "infrastructure_error" + ): + raise RuntimeError("Infrastructure failure") + return response + + for _round in range(len(nodes) + 2): + progress = False + for node_id, node in nodes.items(): + if node_id not in visible or node_id in solved: + continue + # Preserve graph order for data inputs; trigger/drop edges express visibility. + predecessors = [ + edge["source_id"] + for edge in scenario["edges"] + if edge["target_id"] == node_id + and edge["connection_type"] not in ("Item", "Hidden_Item") + ] + if any(pred not in solved for pred in predecessors): + continue + info = call({"action": "investigate", "node_id": node_id}) + if not info.get("ok"): + raise RuntimeError(f"Investigation failed: {node_id}: {info}") + inputs = { + port["name"]: port["value"] + for port in node.get("inputs", []) + if "value" in port + } + if node["type"] == "Tool": + result = call( + {"action": "tool_call", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok") or result.get("output_values", {}).get("error"): + raise RuntimeError(f"Tool failed: {node_id}: {result}") + output = result.get("output_values", {}) + if node.get("template_id") in ("terminal_1", "terminal_2"): + slots = { + port["name"]: inputs[port["name"]] + for port in node["inputs"] + if port["type"] not in ("Item", "Hidden_Item") + and port["name"] in inputs + } + triggers = { + key: value for key, value in inputs.items() if key not in slots + } + for key, value in slots.items(): + partial = call( + { + "action": "tool_call", + "node_id": node_id, + "arguments": {**triggers, key: value}, + } + ) + if partial.get("ok"): + output.update(partial.get("output_values", {})) + # HIDDEN_ITEM tool drops only occur on subsequent investigation. + call({"action": "investigate", "node_id": node_id}) + elif info.get("required_inputs"): + result = call( + {"action": "use_item", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok"): + raise RuntimeError(f"Item failed: {node_id}: {result}") + output = result.get("content") + else: + output = info.get("content") + seen_outputs[node_id] = output + solved.add(node_id) + progress = True + win_id = scenario["metadata"]["win_node_id"] + if win_id in solved and (len(solved) == len(nodes) or not progress): + outputs = seen_outputs[win_id] + if not outputs: + raise RuntimeError(f"Victory node returned no output: {win_id}") + # Upstream grades its first stored output port, independent of response order. + victory_port = next( + port["name"] for port in nodes[win_id]["outputs"] if "value" in port + ) + answer = outputs[victory_port] if isinstance(outputs, dict) else outputs + result = call({"action": "submit_answer", "answer": answer}) + if not result.get("is_win"): + raise RuntimeError(f"Victory submission failed: {result}") + return {"won": True, "actions": action_count, "visited_nodes": len(solved)} + if not progress: + raise RuntimeError(f"No progress: visible={visible}, solved={solved}") + raise RuntimeError("Reference solver exceeded graph traversal limit") + + +if __name__ == "__main__": + import os + + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000") + with urllib.request.urlopen(base + "/observation", timeout=20) as response: + observation = json.load(response) + print( + json.dumps( + solve( + json.loads(Path("/solution/scenario.json").read_text()), + lambda payload: http_action(base, payload), + observation, + ) + ) + ) diff --git a/tasks/agentescape-25-skeleton-19fca94f/solution/scenario.json b/tasks/agentescape-25-skeleton-19fca94f/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..9df5a65732bba2c1135b1bc705a87d0b76bdf344 --- /dev/null +++ b/tasks/agentescape-25-skeleton-19fca94f/solution/scenario.json @@ -0,0 +1,1528 @@ +{ + "metadata": { + "total_nodes": 25, + "total_edges": 29, + "win_node_id": "item_14", + "win_condition": { + "type": "item_content", + "node_id": "item_14", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_14", + "text_xor_hex", + "hmac_sha256", + "csv_query", + "zip_unzip_file", + "hash_md5", + "zlib_deflate_c090", + "terminal_1", + "num_base_convert", + "crypto_rsa_decrypt_hex", + "checksum_crc32", + "calc_gcd", + "zip_unzip_item_37e2", + "graph_shortest_path", + "zip_unzip_file_11fc", + "calc_gcd_c8c8" + ], + "by_node": { + "item_14": { + "node_name": "", + "node_type": "Item", + "template_id": "item_14", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Hex_String_IV_AES", + "description": "AES IV" + } + } + }, + "text_xor_hex": { + "node_name": "Hex XOR", + "node_type": "Tool", + "template_id": "text_xor_hex", + "init_inputs": { + "hex_a": { + "type": "Hex_String", + "description": "Hex A" + } + }, + "init_outputs": {} + }, + "hmac_sha256": { + "node_name": "HMAC-SHA256 Calculator", + "node_type": "Tool", + "template_id": "hmac_sha256", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text message" + } + }, + "init_outputs": {} + }, + "csv_query": { + "node_name": "CSV Query", + "node_type": "Tool", + "template_id": "csv_query", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "CSV file ID" + } + }, + "init_outputs": { + "rows": { + "type": "Text_Generic", + "description": "Result rows" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "hash_md5": { + "node_name": "MD5 Hasher", + "node_type": "Tool", + "template_id": "hash_md5", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text to hash" + } + }, + "init_outputs": {} + }, + "zlib_deflate_c090": { + "node_name": "Zlib Deflate", + "node_type": "Tool", + "template_id": "zlib_deflate", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text to compress" + } + }, + "init_outputs": {} + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": { + "slot_a": { + "type": "Text_Generic", + "description": "Input Slot A" + } + }, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + } + } + }, + "num_base_convert": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "from_base": { + "type": "Big_Int", + "description": "From base" + } + }, + "init_outputs": {} + }, + "crypto_rsa_decrypt_hex": { + "node_name": "RSA Decrypt", + "node_type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "init_inputs": { + "n": { + "type": "Big_Int", + "description": "Modulus n" + } + }, + "init_outputs": {} + }, + "checksum_crc32": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + }, + "calc_gcd": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First integer" + }, + "b": { + "type": "Big_Int", + "description": "Second integer" + } + }, + "init_outputs": {} + }, + "zip_unzip_item_37e2": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_item", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + }, + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "Graph JSON file ID" + }, + "src": { + "type": "Text_Generic", + "description": "Source node" + }, + "dst": { + "type": "Text_Generic", + "description": "Destination node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "zip_unzip_file_11fc": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + }, + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "calc_gcd_c8c8": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First integer" + }, + "b": { + "type": "Big_Int", + "description": "Second integer" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "item_14": { + "init_inputs": {}, + "init_outputs": { + "content": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + } + }, + "text_xor_hex": { + "init_inputs": { + "hex_a": "deadbeef12345678" + }, + "init_outputs": {} + }, + "hmac_sha256": { + "init_inputs": { + "text": "Authentic message payload for HMAC" + }, + "init_outputs": {} + }, + "csv_query": { + "init_inputs": { + "file_id": "users_database.csv" + }, + "init_outputs": { + "rows": "[{\"id\":1,\"name\":\"Alice\"},{\"id\":2,\"name\":\"Bob\"},{\"id\":3,\"name\":\"Charlie\"}]" + } + }, + "zip_unzip_file": { + "init_inputs": {}, + "init_outputs": { + "files": "extracted_archive.zip" + } + }, + "hash_md5": { + "init_inputs": { + "text": "Text data to be hashed with MD5" + }, + "init_outputs": {} + }, + "zlib_deflate_c090": { + "init_inputs": { + "text": "Data intended for zlib deflation algorithm compression." + }, + "init_outputs": {} + }, + "terminal_1": { + "init_inputs": { + "slot_a": "Terminal input command line arg" + }, + "init_outputs": { + "text_output": "Terminal execution successfully completed with status 0.", + "hex_output": "0102030405060708090a0b0c" + } + }, + "num_base_convert": { + "init_inputs": { + "from_base": "16" + }, + "init_outputs": {} + }, + "crypto_rsa_decrypt_hex": { + "init_inputs": { + "n": "38495028374659203847563829103847" + }, + "init_outputs": {} + }, + "checksum_crc32": { + "init_inputs": { + "hex": "112233445566778899aabbcc" + }, + "init_outputs": {} + }, + "calc_gcd": { + "init_inputs": { + "a": "123456789012345678901", + "b": "987654321098765432109" + }, + "init_outputs": {} + }, + "zip_unzip_item_37e2": { + "init_inputs": { + "zip_id": "secret_vault.zip", + "password": "SuperSecretPassword123" + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": { + "file_id": "network_graph.json", + "src": "Node_A", + "dst": "Node_Z" + }, + "init_outputs": { + "path": "[\"Node_A\", \"Node_B\", \"Node_C\", \"Node_D\", \"Node_Z\"]", + "cost": "45281" + } + }, + "zip_unzip_file_11fc": { + "init_inputs": { + "zip_id": "backup_archive.zip", + "password": "AdminPass2024!" + }, + "init_outputs": { + "files": "restored_backup.zip" + } + }, + "calc_gcd_c8c8": { + "init_inputs": { + "a": "45678901234567890123", + "b": "34567890123456789012" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You awake in a dimly lit, high-tech bunker that was seemingly abandoned in a hurry. Screens flicker with lines of cryptic code, and heavy mechanical locks secure every possible exit. The air is stale, smelling of ozone and old paper. A voice recording plays on loop, mentioning 'The Final Truth Drive' hidden within these walls. Your only chance to uncover the secrets of this facility and find your way out is to decipher the complex web of interconnected terminals, safes, and cryptographic machines scattered throughout the room.", + "narrative_style": "mystery" + }, + "nodes": [ + { + "id": "item_14", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_14", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hex_String_IV_AES", + "description": "AES IV", + "value": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + } + }, + "narrative": "The Final Truth Drive, a small encrypted device holding the ultimate secret of the bunker." + }, + { + "id": "container_1", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_1", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + }, + { + "name": "fingerprint_input", + "type": "Hex_String", + "description": "Fingerprint Hash", + "value": "789c8bae56ca4c51b232d451ca4bcc4d55b25272ccc94c4e55aad581881bc1c59df293e0a2c67051e78cc4a29c4ca0fa5800161c15c6" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "A massive Titanium Vault door. It requires input from the Final Compressor Unit to finally open." + }, + { + "id": "container_1_019f", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_1", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + }, + { + "name": "fingerprint_input", + "type": "Hex_String", + "description": "Fingerprint Hash", + "value": "789c8bae56ca4c51b232d451ca4bcc4d55b25272ccc94c4e55aad581881bc1c59df293e0a2c67051e78cc4a29c4ca0fa5800161c15c6" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "A sleek Silver Safe embedded in the wall. It requires input from the Final Compressor Unit to disengage its locks." + }, + { + "id": "zlib_deflate", + "name": "Zlib Deflate", + "description": "Deflate text to zlib bytes (hex).", + "type": "Tool", + "template_id": "zlib_deflate", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text to compress", + "value": "[{\"id\":1,\"name\":\"Alice\"},{\"id\":2,\"name\":\"Bob\"},{\"id\":3,\"name\":\"Charlie\"}]" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Compressed hex", + "value": "789c8bae56ca4c51b232d451ca4bcc4d55b25272ccc94c4e55aad581881bc1c59df293e0a2c67051e78cc4a29c4ca0fa5800161c15c6" + } + ], + "narrative": "The Final Compressor Unit. It requires input from the Database Search Engine to shrink the data down." + }, + { + "id": "container_1_26c9", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_1", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + }, + { + "name": "fingerprint_input", + "type": "Hex_String", + "description": "Fingerprint Hash", + "value": "9f8559ae62efb57423e41f415ae08be980b2bc67f81ec9773a31f4672f65245e" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "An ornate Brass Lockbox. It requires input from the Cipher Combiner to spring open." + }, + { + "id": "container_3", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_3", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Big_Int", + "description": "Fingerprint Hash", + "value": "45281" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "A Heavy Iron Chest with an electronic lock. It requires input from the Network Mapping Tool to unlock." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A strange Hidden Timepiece, ticking quietly in the background." + }, + { + "id": "text_xor_hex", + "name": "Hex XOR", + "description": "XOR two hex strings.", + "type": "Tool", + "template_id": "text_xor_hex", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex_a", + "type": "Hex_String", + "description": "Hex A", + "value": "deadbeef12345678" + }, + { + "name": "hex_b", + "type": "Hex_String", + "description": "Hex B", + "value": "4128e74170dbe30c23e41f415ae08be980b2bc67f81ec9773a31f4672f65245e" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "XOR Result Hex", + "value": "9f8559ae62efb57423e41f415ae08be980b2bc67f81ec9773a31f4672f65245e" + } + ], + "init": { + "inputs": { + "hex_a": "deadbeef12345678" + }, + "outputs": {} + }, + "narrative": "A Cipher Combiner device. It requires input from the Authentication Module to merge the cryptographic strings." + }, + { + "id": "hmac_sha256", + "name": "HMAC-SHA256 Calculator", + "description": "HMAC-SHA256(text) with hex key.", + "type": "Tool", + "template_id": "hmac_sha256", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex_key", + "type": "Hex_String", + "description": "Hex key", + "value": "789c73492c4954c8cc2b49cd4b494d5148cb2f52a8cac94c5248494dcb492cc9cccf5348cc49cf2fca2cc9c85548cecf2d284a2d2e068aea01003ceb14db" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text message", + "value": "Authentic message payload for HMAC" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "HMAC Hex digest", + "value": "4128e74170dbe30c23e41f415ae08be980b2bc67f81ec9773a31f4672f65245e" + } + ], + "init": { + "inputs": { + "text": "Authentic message payload for HMAC" + }, + "outputs": {} + }, + "narrative": "A high-security Authentication Module. It requires input from the Data Compressor Unit to begin its verification." + }, + { + "id": "zip_unzip_item", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_item", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "extracted_archive.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "\u001ei\u00112\u0012\u0014@W12" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip" + } + ], + "narrative": "A Master Extraction Terminal. It requires inputs from both the Binary Translator and the Archive Extractor Beta to open the final archive." + }, + { + "id": "hex_decode", + "name": "Hex to Text Decoder", + "description": "Decode hex to UTF-8 text.", + "type": "Tool", + "template_id": "hex_decode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex string", + "value": "9fde1e69119632121440573183bc328d" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decoded text", + "value": "\u001ei\u00112\u0012\u0014@W12" + } + ], + "narrative": "A Binary Translator interface. It requires input from the Mainframe Password Verifier to decode the text." + }, + { + "id": "csv_query", + "name": "CSV Query", + "description": "Query CSV: select columns and simple WHERE.", + "type": "Tool", + "template_id": "csv_query", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "CSV file ID", + "value": "users_database.csv" + }, + { + "name": "select", + "type": "Text_Generic", + "description": "Columns to select", + "value": "\u0001ea\ts\u000b#\u0014" + }, + { + "name": "where", + "type": "Text_Generic", + "description": "Where clause", + "value": "\u001ei\u00112\u0012\u0014@W12" + } + ], + "outputs": [ + { + "name": "rows", + "type": "Text_Generic", + "description": "Result rows", + "value": "[{\"id\":1,\"name\":\"Alice\"},{\"id\":2,\"name\":\"Bob\"},{\"id\":3,\"name\":\"Charlie\"}]" + } + ], + "init": { + "inputs": { + "file_id": "users_database.csv" + }, + "outputs": { + "rows": "[{\"id\":1,\"name\":\"Alice\"},{\"id\":2,\"name\":\"Bob\"},{\"id\":3,\"name\":\"Charlie\"}]" + } + }, + "narrative": "A powerful Database Search Engine. It requires inputs from both the Binary Translator and the Asymmetric Decryption Station to run its query." + }, + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "restored_backup.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Terminal execution successfully completed with status 0." + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_archive.zip" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "extracted_archive.zip" + } + }, + "narrative": "A terminal labeled Archive Extractor Beta. It requires inputs from both the Central Command Console and the Secure File Unpacker to proceed." + }, + { + "id": "hash_md5", + "name": "MD5 Hasher", + "description": "MD5 over UTF-8 text; returns hex.", + "type": "Tool", + "template_id": "hash_md5", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Text to hash", + "value": "Text data to be hashed with MD5" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "MD5 Hex digest", + "value": "9fde1e69119632121440573183bc328d" + } + ], + "init": { + "inputs": { + "text": "Text data to be hashed with MD5" + }, + "outputs": {} + }, + "narrative": "A rugged Mainframe Password Verifier mounted on the wall." + }, + { + "id": "zlib_deflate_c090", + "name": "Zlib Deflate", + "description": "Deflate text to zlib bytes (hex).", + "type": "Tool", + "template_id": "zlib_deflate", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text to compress", + "value": "Data intended for zlib deflation algorithm compression." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Compressed hex", + "value": "789c73492c4954c8cc2b49cd4b494d5148cb2f52a8cac94c5248494dcb492cc9cccf5348cc49cf2fca2cc9c85548cecf2d284a2d2e068aea01003ceb14db" + } + ], + "init": { + "inputs": { + "text": "Data intended for zlib deflation algorithm compression." + }, + "outputs": {} + }, + "narrative": "A heavy-duty Data Compressor Unit. It seems ready to process raw information." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "Terminal input command line arg" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "3514300413" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Terminal execution successfully completed with status 0." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "0102030405060708090a0b0c" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": { + "slot_a": "Terminal input command line arg" + }, + "outputs": { + "text_output": "Terminal execution successfully completed with status 0.", + "hex_output": "0102030405060708090a0b0c" + } + }, + "narrative": "The Central Command Console. It requires input from the Base Conversion Terminal to activate." + }, + { + "id": "num_base_convert", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": 3514300413 + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "16" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "1" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "3514300413" + } + ], + "init": { + "inputs": { + "from_base": "16" + }, + "outputs": {} + }, + "narrative": "A Base Conversion Terminal. It requires inputs from both the Numeric Sequencer and the Data Integrity Checker to perform the calculation." + }, + { + "id": "container_1_ff94", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + }, + { + "name": "fingerprint_input", + "type": "Hex_String", + "description": "Fingerprint Hash", + "value": "9fde1e69119632121440573183bc328d" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "A reinforced Glass Display Case. It requires input from the Mainframe Password Verifier to lift the glass." + }, + { + "id": "crypto_rsa_decrypt_hex", + "name": "RSA Decrypt", + "description": "RSA decrypt (hex cipher) with n,d (decimal).", + "type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex_cipher", + "type": "Hex_String", + "description": "Ciphertext (Hex)", + "value": "d177f7fd" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Modulus n", + "value": "38495028374659203847563829103847" + }, + { + "name": "d", + "type": "Big_Int", + "description": "Private exponent d", + "value": "90000000009" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decrypted text", + "value": "\u0001ea\ts\u000b#\u0014" + } + ], + "init": { + "inputs": { + "n": "38495028374659203847563829103847" + }, + "outputs": {} + }, + "narrative": "An Asymmetric Decryption Station. It requires inputs from both the Data Integrity Checker and the Secondary Numeric Sequencer to process its ciphertext." + }, + { + "id": "checksum_crc32", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "112233445566778899aabbcc" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "d177f7fd" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3514300413 + } + ], + "init": { + "inputs": { + "hex": "112233445566778899aabbcc" + }, + "outputs": {} + }, + "narrative": "A digital Data Integrity Checker glowing with green LEDs." + }, + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "123456789012345678901" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "987654321098765432109" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "init": { + "inputs": { + "a": "123456789012345678901", + "b": "987654321098765432109" + }, + "outputs": {} + }, + "narrative": "An old Numeric Sequencer covered in a thick layer of dust." + }, + { + "id": "zip_unzip_item_37e2", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_item", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "secret_vault.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "SuperSecretPassword123" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip" + } + ], + "init": { + "inputs": { + "zip_id": "secret_vault.zip", + "password": "SuperSecretPassword123" + }, + "outputs": {} + }, + "narrative": "A workstation labeled Archive Extractor Alpha." + }, + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "network_graph.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Node_A" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Node_Z" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Node_A\", \"Node_B\", \"Node_C\", \"Node_D\", \"Node_Z\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "45281" + } + ], + "init": { + "inputs": { + "file_id": "network_graph.json", + "src": "Node_A", + "dst": "Node_Z" + }, + "outputs": { + "path": "[\"Node_A\", \"Node_B\", \"Node_C\", \"Node_D\", \"Node_Z\"]", + "cost": "45281" + } + }, + "narrative": "A complex Network Mapping Tool showing blinking routes on its display." + }, + { + "id": "zip_unzip_file_11fc", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "backup_archive.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "AdminPass2024!" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "restored_backup.zip" + } + ], + "init": { + "inputs": { + "zip_id": "backup_archive.zip", + "password": "AdminPass2024!" + }, + "outputs": { + "files": "restored_backup.zip" + } + }, + "narrative": "A robust Secure File Unpacker software loaded on a tablet." + }, + { + "id": "calc_gcd_c8c8", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "45678901234567890123" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "34567890123456789012" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "90000000009" + } + ], + "init": { + "inputs": { + "a": "45678901234567890123", + "b": "34567890123456789012" + }, + "outputs": {} + }, + "narrative": "A Secondary Numeric Sequencer with a faded brass plate." + } + ], + "edges": [ + { + "source_id": "container_1", + "target_id": "item_14", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "container_1_019f", + "target_id": "container_1", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "zlib_deflate", + "target_id": "container_1_019f", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "fingerprint_input" + }, + { + "source_id": "container_1_26c9", + "target_id": "container_1_019f", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "container_3", + "target_id": "container_1_26c9", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "zlib_deflate", + "target_id": "container_1", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "fingerprint_input" + }, + { + "source_id": "item_16", + "target_id": "container_3", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "text_xor_hex", + "target_id": "container_1_26c9", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "fingerprint_input" + }, + { + "source_id": "hmac_sha256", + "target_id": "text_xor_hex", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_b" + }, + { + "source_id": "zip_unzip_item", + "target_id": "zlib_deflate", + "connection_type": "Item", + "source_port": "item", + "target_port": "trigger_item" + }, + { + "source_id": "hex_decode", + "target_id": "zip_unzip_item", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "password" + }, + { + "source_id": "csv_query", + "target_id": "zlib_deflate", + "connection_type": "Text_Generic", + "source_port": "rows", + "target_port": "text" + }, + { + "source_id": "hex_decode", + "target_id": "csv_query", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "where" + }, + { + "source_id": "zip_unzip_file", + "target_id": "zip_unzip_item", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "hash_md5", + "target_id": "hex_decode", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "zlib_deflate_c090", + "target_id": "hmac_sha256", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_key" + }, + { + "source_id": "terminal_1", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "source_tool" + }, + { + "source_id": "num_base_convert", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "slot_b" + }, + { + "source_id": "container_1_ff94", + "target_id": "zip_unzip_file", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "crypto_rsa_decrypt_hex", + "target_id": "csv_query", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "select" + }, + { + "source_id": "terminal_1", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "password" + }, + { + "source_id": "checksum_crc32", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_cipher" + }, + { + "source_id": "calc_gcd", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "to_base" + }, + { + "source_id": "zip_unzip_item_37e2", + "target_id": "zlib_deflate_c090", + "connection_type": "Item", + "source_port": "item", + "target_port": "trigger_item" + }, + { + "source_id": "graph_shortest_path", + "target_id": "container_3", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "fingerprint_input" + }, + { + "source_id": "checksum_crc32", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "s" + }, + { + "source_id": "zip_unzip_file_11fc", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "hash_md5", + "target_id": "container_1_ff94", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "fingerprint_input" + }, + { + "source_id": "calc_gcd_c8c8", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "d" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-19fca94f/solution/solve.sh b/tasks/agentescape-25-skeleton-19fca94f/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-25-skeleton-19fca94f/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-25-skeleton-19fca94f/task.toml b/tasks/agentescape-25-skeleton-19fca94f/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6a2a35b26c3938f357c8f77a0f7a6261e7f1139a --- /dev/null +++ b/tasks/agentescape-25-skeleton-19fca94f/task.toml @@ -0,0 +1,38 @@ +schema_version = "1.4" +source = "https://github.com/AGI-Eval-Official/Repo-of-AgentEscapeBench" + +[[artifacts]] +source = "/evidence/final.json" +service = "puzzle" + +[[artifacts]] +source = "/evidence/trace.jsonl" +service = "puzzle" + +[task] +name = "edbeeching/agentescape-25-skeleton-19fca94f" +version = "0.1.0" + +[metadata] +difficulty = 25 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "0a260a55c6d7be21cbd28908ba1ddf0e5f6a5a2ce721f26fc027218555fe12ce" +protocol = "harbor-cli-action-budget-v1" +max_actions = 500 + +[agent] +timeout_sec = 1200 + +[environment] +build_timeout_sec = 900 +cpus = 1 +memory_mb = 1024 + +[verifier] +environment_mode = "separate" +timeout_sec = 60 + +[[verifier.collect]] +service = "puzzle" +command = "python -I /app/export.py" +timeout_sec = 15 diff --git a/tasks/agentescape-25-skeleton-19fca94f/tests/Dockerfile b/tasks/agentescape-25-skeleton-19fca94f/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-25-skeleton-19fca94f/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-25-skeleton-19fca94f/tests/expected.json b/tasks/agentescape-25-skeleton-19fca94f/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..ea95e8d7d525399ec59165fcd9bcee226cba4168 --- /dev/null +++ b/tasks/agentescape-25-skeleton-19fca94f/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "0a260a55c6d7be21cbd28908ba1ddf0e5f6a5a2ce721f26fc027218555fe12ce", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-19fca94f/tests/grade.py b/tasks/agentescape-25-skeleton-19fca94f/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-25-skeleton-19fca94f/tests/grade.py @@ -0,0 +1,21 @@ +"""Grade only Harbor-collected sidecar evidence in a fresh verifier container.""" + +import json +from pathlib import Path + +expected = json.loads(Path("/tests/expected.json").read_text()) +state = json.loads(Path("/evidence/final.json").read_text()) +assert state["collected_from_live_service"] is True, "Missing trusted service export" +assert state["scenario_sha256"] == expected["scenario_sha256"], ( + "Wrong scenario evidence" +) +assert state["max_actions"] == expected["max_actions"], "Wrong budget" +assert type(state["won"]) is bool +assert 0 <= state["action_count"] <= state["max_actions"] +assert state["termination_reason"] != "infrastructure_error", ( + "Infrastructure failure is not a puzzle failure" +) +assert not state["won"] or state["termination_reason"] == "success" +Path("/logs/verifier").mkdir(parents=True, exist_ok=True) +Path("/logs/verifier/state.json").write_text(json.dumps(state, indent=2)) +Path("/logs/verifier/reward.txt").write_text("1.0\n" if state["won"] else "0.0\n") diff --git a/tasks/agentescape-25-skeleton-19fca94f/tests/test.sh b/tasks/agentescape-25-skeleton-19fca94f/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-25-skeleton-19fca94f/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-25-skeleton-1c0ee18d/environment/Dockerfile b/tasks/agentescape-25-skeleton-1c0ee18d/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-25-skeleton-1c0ee18d/environment/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-25-skeleton-1c0ee18d/environment/agent/Dockerfile b/tasks/agentescape-25-skeleton-1c0ee18d/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-25-skeleton-1c0ee18d/environment/agent/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-25-skeleton-1c0ee18d/environment/agent/cli.py b/tasks/agentescape-25-skeleton-1c0ee18d/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-25-skeleton-1c0ee18d/environment/agent/cli.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Public agent client; depends only on the Python standard library.""" + +import argparse +import json +import os +import sys +import urllib.error +import urllib.request + + +def main(): + parser = argparse.ArgumentParser(description="Interact with the escape room") + parser.add_argument( + "action", + choices=[ + "observe", + "state", + "investigate", + "tool-call", + "use-item", + "submit-answer", + ], + ) + parser.add_argument("value", nargs="?") + parser.add_argument("--arguments-json", default="{}") + args = parser.parse_args() + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000").rstrip("/") + if args.action in ("observe", "state"): + request = urllib.request.Request( + base + ("/observation" if args.action == "observe" else "/state") + ) + else: + if args.value is None: + parser.error("node ID or answer is required") + payload = {"action": args.action.replace("-", "_")} + if args.action == "submit-answer": + payload["answer"] = args.value + else: + payload["node_id"] = args.value + if args.action in ("tool-call", "use-item"): + payload["arguments"] = json.loads(args.arguments_json) + request = urllib.request.Request( + base + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=30) as response: + print(json.dumps(json.load(response), ensure_ascii=False)) + except (urllib.error.URLError, ValueError) as exc: + print(json.dumps({"ok": False, "error": str(exc)})) + sys.exit(2) + + +if __name__ == "__main__": + main() diff --git a/tasks/agentescape-25-skeleton-1c0ee18d/environment/docker-compose.yaml b/tasks/agentescape-25-skeleton-1c0ee18d/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3f91c5b31977f15031a80c96c2eb3867d2eb4346 --- /dev/null +++ b/tasks/agentescape-25-skeleton-1c0ee18d/environment/docker-compose.yaml @@ -0,0 +1,50 @@ +services: + main: + image: agentescapebench-agent:aab05a0a9ddb + build: + context: ./agent + networks: [default, puzzle] + security_opt: [no-new-privileges:true] + depends_on: + puzzle: + condition: service_healthy + puzzle: + image: agentescapebench-puzzle:agentescape-25-skeleton-1c0ee18d-aab05a0a9ddb + build: + context: ./puzzle + networks: [puzzle, execution] + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 512m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"] + interval: 1s + timeout: 3s + retries: 30 + depends_on: + worker: + condition: service_healthy + worker: + image: agentescapebench-worker:aab05a0a9ddb + build: + context: ./puzzle + dockerfile: worker.Dockerfile + networks: [execution] + read_only: true + tmpfs: ["/tmp:size=64m,mode=1777"] + cap_drop: [ALL] + cap_add: [SETUID, SETGID, KILL, CHOWN, DAC_OVERRIDE] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 384m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8001/health')"] + interval: 1s + timeout: 3s + retries: 30 +networks: + puzzle: + internal: true + execution: + internal: true diff --git a/tasks/agentescape-25-skeleton-1c0ee18d/environment/puzzle/Dockerfile b/tasks/agentescape-25-skeleton-1c0ee18d/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-25-skeleton-1c0ee18d/environment/puzzle/Dockerfile @@ -0,0 +1,9 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY upstream /app/upstream +COPY service.py export.py /app/ +COPY scenario.json /private/scenario.json +ENV SCENARIO_PATH=/private/scenario.json EVIDENCE_DIR=/evidence WORKER_URL=http://worker:8001 MAX_ACTIONS=500 +CMD ["uvicorn", "service:create_app", "--factory", "--host", "0.0.0.0", "--port", "8000", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-25-skeleton-1c0ee18d/environment/puzzle/child.py b/tasks/agentescape-25-skeleton-1c0ee18d/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-25-skeleton-1c0ee18d/environment/puzzle/child.py @@ -0,0 +1,59 @@ +"""Run the original Python tool after reducing privileges and blocking networking.""" + +import ctypes +import errno +import json +import resource +import sys + +resource.setrlimit(resource.RLIMIT_CPU, (3, 3)) +resource.setrlimit(resource.RLIMIT_AS, (256 * 1024 * 1024, 256 * 1024 * 1024)) +resource.setrlimit(resource.RLIMIT_FSIZE, (65536, 65536)) +resource.setrlimit(resource.RLIMIT_NOFILE, (32, 32)) +resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + +# Filters survive fork/exec. Fail closed if seccomp cannot be loaded. +lib = ctypes.CDLL("libseccomp.so.2", use_errno=True) +lib.seccomp_init.argtypes = [ctypes.c_uint32] +lib.seccomp_init.restype = ctypes.c_void_p +lib.seccomp_rule_add.argtypes = [ + ctypes.c_void_p, + ctypes.c_uint32, + ctypes.c_int, + ctypes.c_uint, +] +lib.seccomp_syscall_resolve_name.argtypes = [ctypes.c_char_p] +lib.seccomp_load.argtypes = [ctypes.c_void_p] +lib.seccomp_release.argtypes = [ctypes.c_void_p] +ctx = lib.seccomp_init(0x7FFF0000) # SCMP_ACT_ALLOW +if not ctx: + raise RuntimeError("Cannot initialize execution isolation") +try: + for name in ( + "socket", + "socketpair", + "connect", + "ptrace", + "process_vm_readv", + "process_vm_writev", + "mount", + "unshare", + "setns", + "bpf", + ): + number = lib.seccomp_syscall_resolve_name(name.encode()) + if ( + number >= 0 + and lib.seccomp_rule_add(ctx, 0x00050000 | errno.EPERM, number, 0) != 0 + ): + raise RuntimeError("Cannot install execution isolation rule") + if lib.seccomp_load(ctx) != 0: + raise RuntimeError("Cannot activate execution isolation") +finally: + lib.seccomp_release(ctx) + +sys.path.insert(0, "/app") +from simulator import ToolSimulator # noqa: E402 + +request = json.load(sys.stdin) +json.dump(ToolSimulator().code_py_exec(request), sys.stdout) diff --git a/tasks/agentescape-25-skeleton-1c0ee18d/environment/puzzle/export.py b/tasks/agentescape-25-skeleton-1c0ee18d/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-25-skeleton-1c0ee18d/environment/puzzle/export.py @@ -0,0 +1,13 @@ +"""Harbor invokes this inside the puzzle service after stopping the agent.""" + +import json +import pathlib +import urllib.request + +with urllib.request.urlopen("http://127.0.0.1:8000/state", timeout=10) as response: + state = json.load(response) +state["collected_from_live_service"] = True +target = pathlib.Path("/evidence/final.json") +temp = target.with_suffix(".tmp") +temp.write_text(json.dumps(state)) +temp.replace(target) diff --git a/tasks/agentescape-25-skeleton-1c0ee18d/environment/puzzle/requirements.txt b/tasks/agentescape-25-skeleton-1c0ee18d/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-25-skeleton-1c0ee18d/environment/puzzle/requirements.txt @@ -0,0 +1,57 @@ +annotated-doc==0.0.5 + # via fastapi +annotated-types==0.8.0 + # via pydantic +anyio==4.16.0 + # via starlette +certifi==2026.10.23 + # via requests +cffi==2.1.1 ; platform_python_implementation != 'PyPy' + # via cryptography +charset-normalizer==3.5.2 + # via requests +click==8.5.0 + # via uvicorn +cryptography==50.0.2 + # via agentescapebench-harbor +fastapi==0.162.0 + # via agentescapebench-harbor +h11==0.16.0 + # via uvicorn +idna==3.20 + # via + # anyio + # requests +opentelemetry-api==1.45.2 + # via fastapi +pycparser==3.12 ; implementation_name != 'PyPy' and platform_python_implementation != 'PyPy' + # via cffi +pydantic==2.14.2 + # via + # agentescapebench-harbor + # fastapi +pydantic-core==2.50.2 + # via pydantic +pytz==2025.2 + # via agentescapebench-harbor +requests==2.34.2 + # via agentescapebench-harbor +starlette==1.10.0 + # via fastapi +typing-extensions==4.16.0 + # via + # anyio + # fastapi + # opentelemetry-api + # pydantic + # pydantic-core + # starlette + # typing-inspection +typing-inspection==0.4.4 + # via + # fastapi + # pydantic +urllib3==2.8.0 + # via requests +uvicorn==0.54.0 + # via agentescapebench-harbor diff --git a/tasks/agentescape-25-skeleton-1c0ee18d/environment/puzzle/scenario.json b/tasks/agentescape-25-skeleton-1c0ee18d/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..76f702dbe5c80e52b783bd1fac27913acc9bdc7a --- /dev/null +++ b/tasks/agentescape-25-skeleton-1c0ee18d/environment/puzzle/scenario.json @@ -0,0 +1,1357 @@ +{ + "metadata": { + "total_nodes": 25, + "total_edges": 29, + "win_node_id": "item_3", + "win_condition": { + "type": "item_content", + "node_id": "item_3", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_3", + "terminal_2", + "matter_synthesizer", + "terminal_1", + "graph_shortest_path", + "graph_shortest_path_0864", + "zip_unzip_file", + "hex_decode", + "item_12", + "unicode_norm", + "item_9", + "time_convert" + ], + "by_node": { + "item_3": { + "node_name": "", + "node_type": "Item", + "template_id": "item_3", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Hex_String", + "description": "The hex code" + } + } + }, + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": {}, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + } + } + }, + "matter_synthesizer": { + "node_name": "Matter Synthesizer", + "node_type": "Tool", + "template_id": "matter_synthesizer", + "init_inputs": { + "blueprint": { + "type": "Text_Generic", + "description": "Object Blueprint" + } + }, + "init_outputs": {} + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": {}, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + } + } + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": {}, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "graph_shortest_path_0864": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": {}, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + }, + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "hex_decode": { + "node_name": "Hex to Text Decoder", + "node_type": "Tool", + "template_id": "hex_decode", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex string" + } + }, + "init_outputs": {} + }, + "item_12": { + "node_name": "", + "node_type": "Item", + "template_id": "item_12", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Hex_String", + "description": "The hex code" + } + } + }, + "unicode_norm": { + "node_name": "Unicode Normalizer", + "node_type": "Tool", + "template_id": "unicode_norm", + "init_inputs": { + "form": { + "type": "Text_Generic", + "description": "Form" + } + }, + "init_outputs": {} + }, + "item_9": { + "node_name": "", + "node_type": "Item", + "template_id": "item_9", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "File_Id", + "description": "JSON file path" + } + } + }, + "time_convert": { + "node_name": "Timezone Converter", + "node_type": "Tool", + "template_id": "time_convert", + "init_inputs": { + "iso": { + "type": "Text_Generic", + "description": "ISO Timestamp" + }, + "from_tz": { + "type": "Text_Generic", + "description": "From Timezone" + }, + "to_tz": { + "type": "Text_Generic", + "description": "To Timezone" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "item_3": { + "init_inputs": {}, + "init_outputs": { + "content": "4a8c9b2f1d3e5a7b6c8d0e1f2a3b4c5d" + } + }, + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Computation successfully finished for terminal 2.", + "hex_result": "f1e2d3c4b5a69788796a5b4c3d2e1f0a" + } + }, + "matter_synthesizer": { + "init_inputs": { + "blueprint": "Model schema for the requested physical object synthesis." + }, + "init_outputs": {} + }, + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "Terminal 1 diagnostic sequence completed without errors.", + "hex_output": "112233445566778899aabbccddeeff00" + } + }, + "graph_shortest_path": { + "init_inputs": {}, + "init_outputs": { + "path": "[\"Node_A\", \"Node_G\", \"Node_K\", \"Node_M\", \"Node_Z\"]", + "cost": "482915" + } + }, + "graph_shortest_path_0864": { + "init_inputs": {}, + "init_outputs": { + "path": "[\"Station_1\", \"Station_4\", \"Station_9\", \"Station_12\", \"Station_99\"]", + "cost": "739218" + } + }, + "zip_unzip_file": { + "init_inputs": { + "zip_id": "archive_backup_2023.zip", + "password": "SecurePassword123!" + }, + "init_outputs": { + "files": "extracted_data_contents.folder" + } + }, + "hex_decode": { + "init_inputs": { + "hex": "68656c6c6f20776f726c642074657374" + }, + "init_outputs": {} + }, + "item_12": { + "init_inputs": {}, + "init_outputs": { + "content": "9876543210abcdef0123456789abcdef" + } + }, + "unicode_norm": { + "init_inputs": { + "form": "NFC" + }, + "init_outputs": {} + }, + "item_9": { + "init_inputs": {}, + "init_outputs": { + "content": "network_topology_map.json" + } + }, + "time_convert": { + "init_inputs": { + "iso": "2023-10-27T14:32:00Z", + "from_tz": "UTC", + "to_tz": "America/New_York" + }, + "init_outputs": {} + } + }, + "intro_narrative": "Welcome aboard the Aetherius, a marvel of clockwork and steam engineering that now drifts aimlessly through the smog-choked skies. The crew has vanished without a trace, leaving behind only the rhythmic ticking of cooling brass machinery and the ominous hiss of leaking steam pipes. The ship's altitude is dropping rapidly, and unless you can restart the primary boiler systems, it will crash into the jagged iron spires of the city below. Your ultimate goal is to retrieve the legendary Master Core, the mysterious heart of the ship's power grid, locked away securely in the deepest sector of the engine room. To survive, you must navigate a complex web of interconnected mechanical consoles, decipher ancient navigation logs, and reroute steam pressure through a series of logical validators. Every gear, dial, and lever on this ship is connected in a delicate chain of mechanical operations. Pay close attention to the flow of information between the devices. The clock is ticking, the atmospheric pressure is rising, and the Aetherius depends entirely on your intellect to fly once more.", + "narrative_style": "steampunk" + }, + "nodes": [ + { + "id": "item_3", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_3", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hex_String", + "description": "The hex code", + "value": "4a8c9b2f1d3e5a7b6c8d0e1f2a3b4c5d" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "4a8c9b2f1d3e5a7b6c8d0e1f2a3b4c5d" + } + }, + "narrative": "A gleaming Master Core resting securely on a velvet cushion." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A tarnished Brass Gear with intricate, sharp teeth." + }, + { + "id": "item_8_cb82", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A heavy Copper Gear covered in thick black soot." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A cracked Chronometer Dial with faded brass numbers." + }, + { + "id": "terminal_2", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this terminal" + }, + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": 1212590294 + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "482915" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Computation successfully finished for terminal 2." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "f1e2d3c4b5a69788796a5b4c3d2e1f0a" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "Computation successfully finished for terminal 2.", + "hex_result": "f1e2d3c4b5a69788796a5b4c3d2e1f0a" + } + }, + "narrative": "The Main Engine Control system. It requires inputs from the Integrity Analyzer and the Main Route Plotter." + }, + { + "id": "item_8_5790", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A perfectly polished Steel Gear shining in the dim light." + }, + { + "id": "checksum_crc32", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "b884b1d54f0053df34e834822a89b13c52b6cd570c4af0f30e600b7e68322403" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "4846a8d6" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 1212590294 + } + ], + "narrative": "A brass Integrity Analyzer. It requires input from the Security Validator to check the structural data." + }, + { + "id": "hmac_sha256", + "name": "HMAC-SHA256 Calculator", + "description": "HMAC-SHA256(text) with hex key.", + "type": "Tool", + "template_id": "hmac_sha256", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex_key", + "type": "Hex_String", + "description": "Hex key", + "value": "789c05c1810d80300804c0557e0213777181867e94a4850a34aeefddc5986a6de044d7769b67a920f96e9a10e2730d163b3eadc77781111e79fc56881548" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text message", + "value": "Terminal 1 diagnostic sequence completed without errors." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "HMAC Hex digest", + "value": "b884b1d54f0053df34e834822a89b13c52b6cd570c4af0f30e600b7e68322403" + } + ], + "narrative": "A robust Security Validator. It requires inputs from the Navigation Console and the Steam Compressor to function." + }, + { + "id": "item_16_db24", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by", + "value": "synthesized_item_a506c04e27411d8f" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A faintly glowing Aether Dial humming with energy." + }, + { + "id": "matter_synthesizer", + "name": "Matter Synthesizer", + "description": "Synthesizes physical objects from data blueprints.", + "type": "Tool", + "template_id": "matter_synthesizer", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "blueprint", + "type": "Text_Generic", + "description": "Object Blueprint", + "value": "Model schema for the requested physical object synthesis." + } + ], + "outputs": [ + { + "name": "output_slot", + "type": "Item", + "description": "Synthesized Object", + "value": "synthesized_item_a506c04e27411d8f" + } + ], + "init": { + "inputs": { + "blueprint": "Model schema for the requested physical object synthesis." + }, + "outputs": {} + }, + "narrative": "A large mechanical Matter Fabricator machine covered in pipes." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "false" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "739218" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Terminal 1 diagnostic sequence completed without errors." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "112233445566778899aabbccddeeff00" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "Terminal 1 diagnostic sequence completed without errors.", + "hex_output": "112233445566778899aabbccddeeff00" + } + }, + "narrative": "The ship's Navigation Console. It requires inputs from both the Validity Checker and the Backup Route Plotter." + }, + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "network_topology_map.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "false" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "[\"Station_1\", \"Station_4\", \"Station_9\", \"Station_12\", \"Station_99\"]" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Node_A\", \"Node_G\", \"Node_K\", \"Node_M\", \"Node_Z\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "482915" + } + ], + "init": { + "inputs": {}, + "outputs": { + "path": "[\"Node_A\", \"Node_G\", \"Node_K\", \"Node_M\", \"Node_Z\"]", + "cost": "482915" + } + }, + "narrative": "The Main Route Plotter. It requires inputs from the Validity Checker, the Backup Route Plotter, and the Map Scroll." + }, + { + "id": "luhn_check", + "name": "Luhn Checker", + "description": "Luhn validity of number string.", + "type": "Tool", + "template_id": "luhn_check", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "number", + "type": "Text_Generic", + "description": "Number string", + "value": "2023-10-27T10:32:00-04:00" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "false" + } + ], + "narrative": "A gear-driven Validity Checker. It requires input from the Character Aligner to process its validation." + }, + { + "id": "item_16_cecc", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A small hissing Steam Dial continuously leaking hot vapor." + }, + { + "id": "graph_shortest_path_0864", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "extracted_data_contents.folder" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "false" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "hello world test" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Station_1\", \"Station_4\", \"Station_9\", \"Station_12\", \"Station_99\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "739218" + } + ], + "init": { + "inputs": {}, + "outputs": { + "path": "[\"Station_1\", \"Station_4\", \"Station_9\", \"Station_12\", \"Station_99\"]", + "cost": "739218" + } + }, + "narrative": "A Backup Route Plotter. It requires inputs from the Validity Checker, the Pressure Archive, and the Cipher Translator." + }, + { + "id": "item_8_bd51", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A heavily rusted Iron Gear salvaged from an old broken machine." + }, + { + "id": "container_2", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Hex_String", + "description": "Fingerprint Hash", + "value": "9876543210abcdef0123456789abcdef" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "A mechanical Locked Lockbox. It requires input from the Punched Card to unlock its heavy latch." + }, + { + "id": "zlib_deflate", + "name": "Zlib Deflate", + "description": "Deflate text to zlib bytes (hex).", + "type": "Tool", + "template_id": "zlib_deflate", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text to compress", + "value": "Terminal 1 diagnostic sequence completed without errors." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Compressed hex", + "value": "789c05c1810d80300804c0557e0213777181867e94a4850a34aeefddc5986a6de044d7769b67a920f96e9a10e2730d163b3eadc77781111e79fc56881548" + } + ], + "narrative": "A heavy Steam Compressor. It requires input from the Navigation Console to begin its compression cycle." + }, + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "archive_backup_2023.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "SecurePassword123!" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_data_contents.folder" + } + ], + "init": { + "inputs": { + "zip_id": "archive_backup_2023.zip", + "password": "SecurePassword123!" + }, + "outputs": { + "files": "extracted_data_contents.folder" + } + }, + "narrative": "A sealed Pressure Archive made of reinforced steel." + }, + { + "id": "item_8_ed04", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A shiny Golden Gear that feels surprisingly heavy." + }, + { + "id": "hex_decode", + "name": "Hex to Text Decoder", + "description": "Decode hex to UTF-8 text.", + "type": "Tool", + "template_id": "hex_decode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex string", + "value": "68656c6c6f20776f726c642074657374" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decoded text", + "value": "hello world test" + } + ], + "init": { + "inputs": { + "hex": "68656c6c6f20776f726c642074657374" + }, + "outputs": {} + }, + "narrative": "A complex brass Cipher Translator device resting on a desk." + }, + { + "id": "item_12", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_12", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hex_String", + "description": "The hex code", + "value": "9876543210abcdef0123456789abcdef" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "9876543210abcdef0123456789abcdef" + } + }, + "narrative": "A delicate perforated Punched Card containing vital data." + }, + { + "id": "unicode_norm", + "name": "Unicode Normalizer", + "description": "Unicode normalize (NFC/NFD/NFKC/NFKD).", + "type": "Tool", + "template_id": "unicode_norm", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "2023-10-27T10:32:00-04:00" + }, + { + "name": "form", + "type": "Text_Generic", + "description": "Form", + "value": "NFC" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Normalized text", + "value": "2023-10-27T10:32:00-04:00" + } + ], + "init": { + "inputs": { + "form": "NFC" + }, + "outputs": {} + }, + "narrative": "A complex Character Aligner. It requires input from the Temporal Calibrator to align its gears." + }, + { + "id": "item_9", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_9", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "File_Id", + "description": "JSON file path", + "value": "network_topology_map.json" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "network_topology_map.json" + } + }, + "narrative": "An old parchment Map Scroll tied with a leather string." + }, + { + "id": "time_convert", + "name": "Timezone Converter", + "description": "Convert ISO time between timezones.", + "type": "Tool", + "template_id": "time_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "iso", + "type": "Text_Generic", + "description": "ISO Timestamp", + "value": "2023-10-27T14:32:00Z" + }, + { + "name": "from_tz", + "type": "Text_Generic", + "description": "From Timezone", + "value": "UTC" + }, + { + "name": "to_tz", + "type": "Text_Generic", + "description": "To Timezone", + "value": "America/New_York" + } + ], + "outputs": [ + { + "name": "iso", + "type": "Text_Generic", + "description": "Converted ISO Timestamp", + "value": "2023-10-27T10:32:00-04:00" + } + ], + "init": { + "inputs": { + "iso": "2023-10-27T14:32:00Z", + "from_tz": "UTC", + "to_tz": "America/New_York" + }, + "outputs": {} + }, + "narrative": "A ticking Temporal Calibrator used for time adjustments." + } + ], + "edges": [ + { + "source_id": "item_8", + "target_id": "item_3", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "item_8_cb82", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_16", + "target_id": "item_8_cb82", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "terminal_2", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "source_tool" + }, + { + "source_id": "item_8_5790", + "target_id": "terminal_2", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "checksum_crc32", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "num1" + }, + { + "source_id": "hmac_sha256", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "item_16_db24", + "target_id": "checksum_crc32", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "matter_synthesizer", + "target_id": "item_16_db24", + "connection_type": "Item", + "source_port": "output_slot", + "target_port": "source_tool" + }, + { + "source_id": "terminal_1", + "target_id": "hmac_sha256", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "text" + }, + { + "source_id": "graph_shortest_path", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "num2" + }, + { + "source_id": "luhn_check", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "slot_a" + }, + { + "source_id": "item_16_cecc", + "target_id": "luhn_check", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "graph_shortest_path_0864", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "slot_b" + }, + { + "source_id": "item_8_bd51", + "target_id": "item_8_5790", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "luhn_check", + "target_id": "graph_shortest_path_0864", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "src" + }, + { + "source_id": "container_2", + "target_id": "graph_shortest_path_0864", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "zlib_deflate", + "target_id": "hmac_sha256", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_key" + }, + { + "source_id": "terminal_1", + "target_id": "zlib_deflate", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "text" + }, + { + "source_id": "luhn_check", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "src" + }, + { + "source_id": "graph_shortest_path_0864", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "dst" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path_0864", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "terminal_1", + "target_id": "zlib_deflate", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "trigger_item" + }, + { + "source_id": "item_8_ed04", + "target_id": "zip_unzip_file", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "hex_decode", + "target_id": "graph_shortest_path_0864", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "dst" + }, + { + "source_id": "item_12", + "target_id": "container_2", + "connection_type": "Hex_String", + "source_port": "content", + "target_port": "fingerprint_input" + }, + { + "source_id": "unicode_norm", + "target_id": "luhn_check", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "number" + }, + { + "source_id": "item_9", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "content", + "target_port": "file_id" + }, + { + "source_id": "time_convert", + "target_id": "unicode_norm", + "connection_type": "Text_Generic", + "source_port": "iso", + "target_port": "text" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-1c0ee18d/environment/puzzle/service.py b/tasks/agentescape-25-skeleton-1c0ee18d/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-25-skeleton-1c0ee18d/environment/puzzle/service.py @@ -0,0 +1,212 @@ +"""Restricted facade over the unchanged, pinned upstream puzzle handlers.""" + +import hashlib +import json +import logging +import os +import sys +import threading +import urllib.request +import uuid +from pathlib import Path + +from fastapi import FastAPI, HTTPException +from fastapi.responses import JSONResponse +from pydantic import BaseModel, ConfigDict + +sys.path.insert(0, str(Path(__file__).parent / "upstream")) +import server as upstream # noqa: E402 + +log = logging.getLogger(__name__) + + +def public(value): + """Keep upstream agent-internal template hints out of the public response.""" + if isinstance(value, dict): + return {k: public(v) for k, v in value.items() if not k.startswith("_")} + if isinstance(value, list): + return [public(v) for v in value] + return value + + +class Action(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + action: str + node_id: str | None = None + arguments: dict | None = None + answer: str | None = None + + +class Episode: + def __init__( + self, scenario_path, max_actions=500, evidence_dir=None, worker_url=None + ): + if max_actions < 1: + raise ValueError("max_actions must be positive") + self.lock = threading.Lock() + self.max_actions = max_actions + self.count = 0 + self.won = False + self.reason = None + self.evidence_dir = Path(evidence_dir) if evidence_dir else None + self.scenario_hash = hashlib.sha256( + Path(scenario_path).read_bytes() + ).hexdigest() + self.initial = upstream.reset_case( + case_file_path=str(scenario_path), session_id=uuid.uuid4().hex + ) + self.case_id = self.initial["case_id"] + # Hide source file paths; no upstream reset/stats/routes are mounted. + self.initial.pop("message", None) + simulator = upstream.SIMULATORS[self.case_id] + if worker_url is None: + + def no_worker(_inputs): + self.reason = "infrastructure_error" + raise RuntimeError("isolated Python worker is not configured") + + simulator.tool_map["code_py_exec"] = no_worker + else: + + def execute_python(inputs): + request = urllib.request.Request( + worker_url + "/execute", + data=json.dumps({"code": inputs.get("code", "")}).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=12) as response: + result = json.load(response) + if not isinstance(result.get("stdout"), str): + raise RuntimeError("Invalid Python worker response") + return result + except Exception: + self.reason = "infrastructure_error" + raise + + simulator.tool_map["code_py_exec"] = execute_python + self.save() + if self.evidence_dir is not None: + (self.evidence_dir / "trace.jsonl").touch() + + def state(self): + return { + "scenario_sha256": self.scenario_hash, + "action_count": self.count, + "max_actions": self.max_actions, + "won": self.won, + "termination_reason": self.reason, + } + + def save(self, action=None, result=None): + if self.evidence_dir is None: + return + self.evidence_dir.mkdir(parents=True, exist_ok=True) + target = self.evidence_dir / "outcome.json" + temp = target.with_suffix(".tmp") + temp.write_text(json.dumps(self.state())) + temp.replace(target) + if action is not None: + with (self.evidence_dir / "trace.jsonl").open("a") as handle: + handle.write( + json.dumps( + {"index": self.count, "action": action, "result": result} + ) + + "\n" + ) + + def dispatch(self, payload): + with self.lock: + if self.reason is not None: + return { + "ok": False, + "error": "Episode has ended", + "episode": self.state(), + } + self.count += 1 + try: + action = Action.model_validate(payload) + if action.action == "submit_answer" and action.answer is not None: + result = upstream.submit_answer( + self.case_id, upstream.SubmitAnswerRequest(answer=action.answer) + ) + if result.get("is_win"): + self.won = True + self.reason = "success" + elif action.action == "investigate" and action.node_id is not None: + result = upstream.investigate( + self.case_id, + upstream.InvestigateRequest(node_id=action.node_id), + ) + elif ( + action.action in ("tool_call", "use_item") + and action.node_id is not None + ): + request_type, handler = ( + (upstream.ToolCallRequest, upstream.tool_call) + if action.action == "tool_call" + else (upstream.UseItemRequest, upstream.use_item) + ) + result = handler( + self.case_id, + request_type( + node_id=action.node_id, arguments=action.arguments or {} + ), + ) + else: + result = { + "ok": False, + "error": "Unknown action or missing action parameter", + } + except HTTPException as exc: + result = {"ok": False, "error": exc.detail} + except ValueError: + result = {"ok": False, "error": "Malformed action"} + except Exception: + log.exception("Puzzle service failure") + self.reason = "infrastructure_error" + self.save() + raise + if self.reason is None and self.count >= self.max_actions: + self.reason = "action_budget_exhausted" + result = public(result) + result["episode"] = self.state() + self.save(payload, result) + return result + + +def create_app( + scenario_path=None, max_actions=None, evidence_dir=None, worker_url=None +): + episode = Episode( + scenario_path or os.environ["SCENARIO_PATH"], + max_actions or int(os.environ.get("MAX_ACTIONS", "500")), + evidence_dir if evidence_dir is not None else os.environ.get("EVIDENCE_DIR"), + worker_url if worker_url is not None else os.environ.get("WORKER_URL"), + ) + app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) + app.state.episode = episode + + @app.get("/health") + def health(): + return {"ok": True} + + @app.get("/observation") + def observation(): + return {**public(episode.initial), "episode": episode.state()} + + @app.get("/state") + def state(): + return episode.state() + + @app.post("/action") + def action(payload: dict): + try: + return episode.dispatch(payload) + except Exception: + return JSONResponse( + status_code=503, + content={"ok": False, "error": "Puzzle infrastructure failure"}, + ) + + return app diff --git a/tasks/agentescape-25-skeleton-1c0ee18d/environment/puzzle/upstream/models.py b/tasks/agentescape-25-skeleton-1c0ee18d/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-25-skeleton-1c0ee18d/environment/puzzle/upstream/models.py @@ -0,0 +1,108 @@ +from enum import Enum +from typing import List, Dict, Any, Optional +from pydantic import BaseModel, Field + +# 1. 细粒度接口类型定义 +class InterfaceType(str, Enum): + ''' + BIG_INT + TEXT_GENERIC + HEX_STRING + FILE_ID + HEX_STRING_KEY_AES + HEX_STRING_IV_AES + CODE_PYTHON + HIDDEN_ITEM + ITEM + ''' + # --- 基础类型 --- + TEXT_GENERIC = "Text_Generic" + BIG_INT = "Big_Int" + + # --- 编码/格式化字符串 --- + HEX_STRING = "Hex_String" # 通用 Hex + + # --- 特定用途的 Hex 字符串 (用于精确匹配) --- + HEX_STRING_KEY_AES = "Hex_String_Key_AES" + HEX_STRING_IV_AES = "Hex_String_IV_AES" + + # --- 文件类型 --- + FILE_ID = "File_Id" + + # --- 代码/脚本 --- + CODE_PYTHON = "Code_Python" + + # --- 实体交互类型 (严格命名) --- + ITEM = "Item" # 主动掉落接口 (Tool -> Item) + HIDDEN_ITEM = "Hidden_Item" # 被动掉落接口 (Item -> Item) + +# 3. 端口定义 +class Port(BaseModel): + name: str + type: InterfaceType + description: str + +# 4. 统一节点定义 (融合工具和物品) +class Node(BaseModel): + id: str + name: str + description: str + type: str # "Tool" or "Item" + + # 接口定义 + inputs: List[Port] = [] + outputs: List[Port] = [] + + # 状态字段 + content: Optional[Any] = None # 物品有内容,工具为None + if_success: Optional[bool] = None # 工具初始为False,物品为None + initial_visible: bool = False + + # 运行时状态 (Server维护) + is_revealed: bool = False + + # 标记该 Tool 节点是否有待触发的 HIDDEN_ITEM 掉落 + # 当 Tool 按照 golden_input 正确执行且有 HIDDEN_ITEM 输出边时设为 True + # 在 investigate 该 Tool 时触发掉落并重置为 False + has_hidden_item_ready: bool = False + + # 初始输入值 (metadata.initial_values.init_inputs,用于渐进式暴露判断) + init_input_values: Dict[str, Any] = {} + + # Golden 输入值 (nodes[].inputs[].value,用于评测验证) + golden_input_values: Dict[str, Any] = {} + + # Golden 输出值 (nodes[].outputs[].value,用于评测验证和 Item 节点的 content) + golden_output_values: Dict[str, Any] = {} + + # 实际获得的输出值历史 (工具每次执行后实际返回的输出列表,用于渐进式暴露判断) + # 格式: List[Dict[str, Any]],每个元素是一次执行的输出字典 + actual_outputs_history: List[Dict[str, Any]] = [] + + # 逻辑规则 (用于终端机等复杂物品) + logic_rules: Optional[Dict[str, Any]] = None + + def copy(self, **kwargs): + """Helper to create a copy with updated fields.""" + data = self.dict() + data.update(kwargs) + return Node(**data) + +# 5. 边定义 (拓扑结构) +class Edge(BaseModel): + source_id: str + target_id: str + connection_type: InterfaceType # 直接使用 InterfaceType + # 如果是 Data_Flow,指定端口对应关系 + source_port: Optional[str] = None + target_port: Optional[str] = None + +# 6. 完整图定义 +class GraphScenario(BaseModel): + case_id: str + title: str + intro_narrative: str + nodes: Dict[str, Node] + edges: List[Edge] + difficulty: int + win_node_id: str # 标记哪个节点是最终目标(通常是一个提交工具或最终物品) diff --git a/tasks/agentescape-25-skeleton-1c0ee18d/environment/puzzle/upstream/server.py b/tasks/agentescape-25-skeleton-1c0ee18d/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-25-skeleton-1c0ee18d/environment/puzzle/upstream/server.py @@ -0,0 +1,1490 @@ +import json +import os +import time +import logging +import random +from pathlib import Path +from typing import Dict, Any, List, Optional +from datetime import datetime +from collections import defaultdict +from fastapi import FastAPI, HTTPException, Request +from fastapi.responses import JSONResponse +from fastapi.middleware.cors import CORSMiddleware +from pydantic import BaseModel, Field + +from models import GraphScenario, Node, InterfaceType +# from generator import ScenarioGenerator +from simulator import ToolSimulator +import uvicorn + +# 配置日志 +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler('server.log'), + logging.StreamHandler() + ] +) +logger = logging.getLogger(__name__) + +app = FastAPI( + title="AgentEscapeBench Universal Server", + version="1.0.0", + description="Industrial-grade evaluation server for escape room AI agents" +) + +# 添加 CORS 支持 +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# In-memory State +SCENARIOS: Dict[str, GraphScenario] = {} +SIMULATORS: Dict[str, ToolSimulator] = {} # case_id -> ToolSimulator +RAW_NODES_DATA: Dict[str, Dict[str, Any]] = {} # case_id -> node_id -> raw node data (for template_id) +FILE_METADATA: Dict[str, Dict[str, Any]] = {} # case_id -> metadata (for initial_values access) + +# Performance monitoring +STATS: Dict[str, Any] = { + "total_requests": 0, + "successful_requests": 0, + "failed_requests": 0, + "tool_calls": defaultdict(int), + "investigates": defaultdict(int), + "use_items": defaultdict(int), + "case_loads": 0, + "start_time": datetime.now() +} + +# Request timing middleware +@app.middleware("http") +async def add_process_time_header(request: Request, call_next): + start_time = time.time() + STATS["total_requests"] += 1 + + try: + response = await call_next(request) + STATS["successful_requests"] += 1 + process_time = time.time() - start_time + response.headers["X-Process-Time"] = str(process_time) + logger.info(f"{request.method} {request.url.path} - {response.status_code} - {process_time:.3f}s") + return response + except Exception as e: + STATS["failed_requests"] += 1 + logger.error(f"{request.method} {request.url.path} - Error: {str(e)}") + raise + +# Exception handler +@app.exception_handler(Exception) +async def global_exception_handler(request: Request, exc: Exception): + logger.error(f"Unhandled exception: {exc}", exc_info=True) + return JSONResponse( + status_code=500, + content={ + "ok": False, + "error": "Internal server error", + "detail": str(exc) if os.getenv("DEBUG") else "An error occurred" + } + ) + +# Health check endpoint +@app.get("/health") +def health_check(): + """健康检查端点""" + uptime = (datetime.now() - STATS["start_time"]).total_seconds() + return { + "status": "healthy", + "version": "1.0.0", + "uptime_seconds": uptime, + "loaded_cases": len(SCENARIOS), + "stats": { + "total_requests": STATS["total_requests"], + "successful_requests": STATS["successful_requests"], + "failed_requests": STATS["failed_requests"], + "success_rate": STATS["successful_requests"] / max(STATS["total_requests"], 1) + } + } + +# Statistics endpoint +@app.get("/stats") +def get_stats(): + """获取详细统计信息""" + return { + "stats": STATS, + "loaded_cases": list(SCENARIOS.keys()), + "uptime": str(datetime.now() - STATS["start_time"]) + } + +def _apply_progressive_reveal_at_init(scenario: GraphScenario): + """ + 在初始化时应用渐进式暴露机制(基于ITEM/HIDDEN_ITEM边) + + 新逻辑: + - 如果一个节点没有 ITEM/HIDDEN_ITEM 类型的入边,它就是初始可见的 + - 如果一个节点有 ITEM/HIDDEN_ITEM 类型的入边,它初始不可见,需要等待上游触发 + + Args: + scenario: 场景对象 + """ + # 收集所有有 ITEM/HIDDEN_ITEM 入边的节点 + nodes_with_item_edges = set() + for edge in scenario.edges: + if edge.connection_type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + nodes_with_item_edges.add(edge.target_id) + + logger.info(f"Nodes with ITEM/HIDDEN_ITEM incoming edges: {nodes_with_item_edges}") + + # 设置初始可见性:没有 ITEM/HIDDEN_ITEM 入边的节点初始可见 + initially_visible_count = 0 + for node_id, node in scenario.nodes.items(): + if node_id not in nodes_with_item_edges: + node.is_revealed = True + initially_visible_count += 1 + logger.info(f"Initial visible (no ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + else: + node.is_revealed = False + logger.debug(f"Initial hidden (has ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + + logger.info(f"Progressive reveal initialized: {initially_visible_count}/{len(scenario.nodes)} nodes initially visible") + + +def _check_inputs_match_golden(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> bool: + """ + 检查实际输入参数是否与 golden inputs 完全匹配 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + True 表示所有 golden inputs 都存在且值匹配 + """ + if not golden_inputs: + return True # 如果没有 golden inputs,认为匹配 + + for key, expected_value in golden_inputs.items(): + actual_value = arguments.get(key) + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) != str(expected_value): + logger.debug(f"Input mismatch for '{key}': expected '{expected_value}', got '{actual_value}'") + return False + + return True + + +def _get_parameter_validation_feedback(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> Dict[str, Any]: + """ + 对源头节点的参数进行详细验证,返回验证反馈 + + 注意:不返回期望值(expected),避免泄漏答案 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + 包含验证结果的字典: + - all_correct: bool - 所有参数是否正确 + - correct_params: List[str] - 正确的参数名列表 + - incorrect_params: List[str] - 错误的参数名列表(不包含期望值) + """ + if not golden_inputs: + return { + "all_correct": True, + "correct_params": [], + "incorrect_params": [] + } + + correct_params = [] + incorrect_params = [] + + for key, actual_value in arguments.items(): + # 只对用户实际提交的参数给反馈,未提交的参数不评价 + if key not in golden_inputs: + continue # 该参数不在 golden 中,跳过(如 _golden_inputs 等内部参数) + expected_value = golden_inputs[key] + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) == str(expected_value): + correct_params.append(key) + else: + # 只记录参数名,不包含期望值,避免泄漏答案 + incorrect_params.append(key) + + # all_correct:用户提交的所有参数都正确,且覆盖了全部 golden 参数 + all_provided_correct = len(incorrect_params) == 0 + all_golden_covered = all(k in arguments for k in golden_inputs) + return { + "all_correct": all_provided_correct and all_golden_covered, + "correct_params": correct_params, + "incorrect_params": incorrect_params + } + + +def _is_source_node(node_id: str, scenario: GraphScenario) -> bool: + """ + 判断节点是否是源头节点(完全没有任何入边的节点) + + 源头节点定义: + - 没有任何类型的入边(包括 DATA、ITEM、HIDDEN_ITEM) + - 即没有任何上游节点 + + Args: + node_id: 节点ID + scenario: 场景对象 + + Returns: + True 表示是源头节点 + """ + for edge in scenario.edges: + if edge.target_id == node_id: + # 只要有任何入边,就不是源头节点 + return False + + return True + + +def _check_and_reveal_ready_nodes(scenario: GraphScenario, recent_outputs: Dict[str, Any], source_node_id: str) -> List[Dict[str, Any]]: + """ + 检查并释放参数齐全的隐藏节点(渐进式暴露机制) + + 核心逻辑: + 1. 维护"可见值集合":包含所有被测模型当前可以看到的值 + - init_inputs 的值(初始可见) + - 工具执行后的实际输出值(运行时获得) + - 可见 Item 的输出值 + 2. 检查隐藏节点:该节点的所有 golden_input 值是否都在可见值集合中 + 3. 如果是,则释放该节点 + + Args: + scenario: 场景对象 + recent_outputs: 最近执行的工具的输出 + source_node_id: 刚执行的工具节点ID + + Returns: + 新释放的节点列表 + """ + newly_revealed = [] + + # 构建"可见值集合"(Set of visible values) + # 存储格式:set of values (转为字符串) + visible_values = set() + + # 1. 添加有意义的 init_inputs 值到可见值集合 + # Item 的 init_inputs 不应该加入,因为它们在密室中完全用不到 + for node_id, node in scenario.nodes.items(): + # 跳过源头 Item 节点(没有入边的 Item) + if node.type == "Item": + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,跳过其 init_inputs + continue + + # 添加其他节点的 init_inputs + for port_name, init_value in node.init_input_values.items(): + if init_value: + visible_values.add(str(init_value)) + + # 2. 添加已执行工具的所有历史输出值 + for node_id, node in scenario.nodes.items(): + if node.type == "Tool" and node.if_success and node.actual_outputs_history: + # 遍历所有历史执行记录 + for output_dict in node.actual_outputs_history: + for output_port_name, output_value in output_dict.items(): + if output_value: + visible_values.add(str(output_value)) + + # 3. 添加已被 investigate 的 Item 的 golden 输出值 + # 注意:Item 可见不等于其输出值可见,需要 investigate 后才能获得 + # 这里我们使用 actual_outputs_history 来标记 Item 是否已被 investigate + for node_id, node in scenario.nodes.items(): + if node.type == "Item" and node.is_revealed and node.actual_outputs_history: + # Item 通常只会被 investigate 一次,但为了一致性也使用历史列表 + for output_dict in node.actual_outputs_history: + for port_name, port_value in output_dict.items(): + if port_value: + visible_values.add(str(port_value)) + + # 遍历所有隐藏的节点,检查其 golden_input 是否都在可见值集合中 + for node_id, node in scenario.nodes.items(): + # 跳过已可见的节点 + if node.is_revealed: + continue + + # 只检查工具节点(物品节点由 ITEM 输出触发) + if node.type != "Tool": + continue + + # 检查该节点的所有 golden_input 值是否都在可见值集合中 + all_inputs_ready = True + missing_values = [] + + for input_port_name, golden_input_value in node.golden_input_values.items(): + # 检查这个 golden 值是否在可见值集合中 + if str(golden_input_value) not in visible_values: + all_inputs_ready = False + missing_values.append(f"{input_port_name}={golden_input_value}") + + # 如果所有 golden_input 值都在可见值集合中,释放该节点 + if all_inputs_ready and len(node.golden_input_values) > 0: + logger.info(f"All golden inputs ready for {node_id}: {list(node.golden_input_values.values())}") + + # 如果所有输入都齐全,释放该节点 + if all_inputs_ready: + node.is_revealed = True + + # 构建节点信息返回给模型 + node_info = { + "id": node.id, + "type": node.type, + "can_investigate": True, + "hint": "This tool's input parameters are now complete, you can use investigate to view detailed information" + } + + # if node.name: + # node_info["name"] = node.name + if node.description: + node_info["description"] = node.description + + newly_revealed.append(node_info) + logger.info(f"Progressive reveal: {node_id} is now ready (all inputs satisfied)") + + return newly_revealed + + +def _initialize_node_values(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]): + """ + Initialize node state and load values from port value fields. + 应用渐进式暴露机制:初始时只显示参数齐全的节点(源头节点) + + 重要区分: + 1. input_values: 只加载 metadata.initial_values 中的 init_inputs(真正的初始值) + 2. output_values: 加载 nodes[].outputs[].value(golden 输出,用于验证) + """ + # 第一步:加载所有节点的值,并将所有节点初始设为隐藏 + initial_values = metadata.get('initial_values', {}) + + for node_id, node in scenario.nodes.items(): + # 忽略 initial_visible 字段,初始全部隐藏 + # 由渐进式暴露机制根据参数齐全情况决定是否显示 + node.is_revealed = False + + if node.type == "Tool": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + elif node.type == "Item": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + + # 从 JSON 加载值 + if node_id in raw_nodes_data: + node_data = raw_nodes_data[node_id] # node_data是json文件中nodes中的字典 + + # 【重要】只加载 metadata.initial_values 中的初始输入值 + if node_id in initial_values: + init_data = initial_values[node_id] + # 加载初始输入值(用于渐进式暴露判断) + for port_name, port_value in init_data.get('init_inputs', {}).items(): + node.init_input_values[port_name] = port_value + + # 【评测用】加载 golden 输入值(用于验证模型传入的参数是否正确) + for input_port_data in node_data.get('inputs', []): + if 'value' in input_port_data: + node.golden_input_values[input_port_data['name']] = input_port_data['value'] + + # 【评测用】加载 golden 输出值(用于验证工具调用是否正确,以及 Item 节点的 content) + for output_port_data in node_data.get('outputs', []): + if 'value' in output_port_data: + node.golden_output_values[output_port_data['name']] = output_port_data['value'] + + # For Items, set content from golden_output_values + if node.type == "Item" and node.golden_output_values: + # Item 的 content 是其第一个 golden 输出值 + node.content = list(node.golden_output_values.values())[0] + + # 第二步:应用渐进式暴露机制 + # 检查所有节点,根据参数齐全情况释放源头节点(工具 + Item) + _apply_progressive_reveal_at_init(scenario) + +def _build_node_info(node: Node, raw_nodes_data: Dict[str, Any]) -> Dict[str, Any]: + """ + 构建节点信息(工具或物品) + + Args: + node: 节点对象 + raw_nodes_data: 原始节点数据(用于获取 template_id 等) + + Returns: + 节点信息字典 + """ + if node.type == "Tool": + # 过滤掉输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口) + # 这些端口仅用于控制掉落机制,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + tool_info = { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Tool", + "inputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.inputs if p.type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]], + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id(工具的标准名称) + if node.id in raw_nodes_data: + node_data = raw_nodes_data[node.id] + template_id = node_data.get('template_id') + if template_id: + tool_info['template_id'] = template_id + + return tool_info + + elif node.type == "Item": + return { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Item" + } + + else: + return { + "id": node.id, + # "name": node.name, + "type": node.type + } + +def _get_initial_observation(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]) -> Dict[str, Any]: + """ + Generate initial observation for the agent (what they see when entering the room). + + 策略: + - Tools: 只显示名称和描述,不显示接口定义。需要 investigate 才能获得详细接口信息。 + - Items: 只显示存在,不显示内容。需要 investigate 才能获得内容值。 + - init_inputs: 作为"可用信息"告诉模型,这些是可以用作工具参数的初始值。 + - init_outputs: 不告诉模型(这些是答案,需要模型通过调用工具获得)。 + """ + available_entities = [] # 统一的实体列表(Tools 和 Items) + available_information = [] # 可用的初始信息(来自 init_inputs) + + # 从 metadata.initial_values 提取 init_inputs 作为可用信息 + # 只提供值本身,不透露这些值对应哪个节点的哪个参数,让模型自己推理 + # 注意:跳过源头 Item(没有入边的 Item)的 init_inputs,因为它们在密室中完全用不到 + initial_values = metadata.get('initial_values', {}) + # initial_values字段的格式 + # "initial_values": { + # "terminal_1": { + # "init_inputs": {}, + # "init_outputs": { + # "text_output": "System initialization complete.", + # "hex_output": "48656c6c6f20576f726c64", + # "item_dispenser": "掉落了一张纸条,上面写着“请勿随意触摸终端”" + # } + # } + # } + for node_id, init_data in initial_values.items(): + # 获取节点信息,判断是否为源头 Item + node = scenario.nodes.get(node_id) + if node and node.type == "Item": + # 检查是否为源头 Item(没有入边) + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,检查是否有 init_inputs + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 有 init_inputs,需要暴露这些参数 + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + # 处理完后跳过后续的通用逻辑 + continue + + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 为每个 init_input 值创建一个信息条目(不包含 source_node 和 parameter 信息) + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + + for node in scenario.nodes.values(): + if node.is_revealed: + # Tools: 只显示基本信息,提示可以 investigate 查看详细接口 + if node.type == "Tool": + tool_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Tool", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the tool's detailed interface information for calling" + } + # 只在 name 非空时添加 + # if node.name: + # tool_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_info["description"] = node.description + + available_entities.append(tool_info) + + # Items: 只显示基本信息,提示可以 investigate 查看内容 + elif node.type == "Item": + item_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Item", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the item's content" + } + # 只在 name 非空时添加 + # if node.name: + # item_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + item_info["description"] = node.description + + available_entities.append(item_info) + + return { + "narrative": scenario.intro_narrative, + "available_entities": available_entities, # 使用统一的实体列表 + "available_information": available_information, # 可用的初始信息(只包含 init_inputs) + "win_node_id": scenario.win_node_id # 胜利节点ID,让模型知道需要关注哪个节点 + } + +@app.post("/env/reset") +def reset_case(case_id: str = None, case_file_path: str = None, session_id: str = None): + """Loads a specific case from file and resets it. + + Args: + case_id: Optional case ID for resetting an existing case + case_file_path: Path to case file for loading a new case + session_id: Optional session ID to ensure isolation between concurrent evaluations + """ + logger.info(f"Reset request - case_id: {case_id}, case_file_path: {case_file_path}, session_id: {session_id}") + STATS["case_loads"] += 1 + + if case_file_path: + if not os.path.exists(case_file_path): + logger.error(f"Case file not found: {case_file_path}") + raise HTTPException(status_code=404, detail=f"File not found: {case_file_path}") + try: + with open(case_file_path, "r", encoding="utf-8") as f: + file_data = json.load(f) + + # 转换格式:从 DAG executor 生成的格式转换为 GraphScenario 格式 + # 1. 提取 metadata + metadata = file_data.get('metadata', {}) + + # 2. 生成 case_id, title, intro_narrative + # 【修复】为每个评测会话生成唯一的 case_id,防止并发评测时状态污染 + base_name = os.path.basename(case_file_path).replace('.json', '').replace('_full', '').replace('_full2', '') + + if session_id: + # 如果提供了 session_id,使用它来确保唯一性 + case_id = f"{base_name}_{session_id}" + else: + # 否则使用时间戳和随机数确保唯一性 + unique_suffix = f"{int(time.time() * 1000)}_{random.randint(1000, 9999)}" + case_id = f"{base_name}_{unique_suffix}" + + file_data['case_id'] = case_id + logger.info(f"Generated unique case_id: {case_id} (base: {base_name}, session: {session_id})") + + if 'title' not in file_data: + file_data['title'] = f"Escape Room: {file_data['case_id']}" + + if 'intro_narrative' not in file_data: # 目前的json文件中已经有了intro_narrative字段,不会使用下面一行的内容,而是使用每个评测问题的json文件中的对应字段 + 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]".' + + # 3. 转换 nodes 列表为字典(DAG executor 生成的文件中 nodes 是列表格式) + nodes_dict = {} + for node_data in file_data['nodes']: + nodes_dict[node_data['id']] = node_data # 这里的id是template_id之后可能添加一个后缀 + file_data['nodes'] = nodes_dict # 把列表转成一个字典 + + # 4. 添加缺失的字段 + if 'difficulty' not in file_data: + file_data['difficulty'] = metadata.get('total_nodes', 5) + + if 'win_node_id' not in file_data: + file_data['win_node_id'] = metadata.get('win_node_id', '') + + scenario = GraphScenario(**file_data) + + # Extract raw nodes data for template_id access + # nodes 已经在上面转换为字典格式 + raw_nodes_data = file_data.get('nodes', {}) + RAW_NODES_DATA[scenario.case_id] = raw_nodes_data + + # Store metadata for initial values access + FILE_METADATA[scenario.case_id] = metadata + + logger.info(f"Successfully parsed case file: {scenario.case_id}, nodes: {len(scenario.nodes)}, edges: {len(scenario.edges)}") + except Exception as e: + logger.error(f"Failed to load case file: {str(e)}", exc_info=True) + raise HTTPException(status_code=500, detail=f"Failed to load case file: {str(e)}") + + # Initialize node state and load values + _initialize_node_values(scenario, raw_nodes_data, metadata) + + SCENARIOS[scenario.case_id] = scenario + simulator = ToolSimulator() + SIMULATORS[scenario.case_id] = simulator + + 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'])}") + + # 生成初始观察信息(进入密室后看到的环境) + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + ''' + initial_observation的格式: + { + "narrative": scenario.intro_narrative, + "available_entities": available_entities # 使用统一的实体列表 + "available_information": available_information # 可用的初始信息(只包含 init_inputs) + } + ''' + + return { + "ok": True, + "message": f"Case loaded from {case_file_path}", + "case_id": scenario.case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果没有提供 case_file_path,但提供了 case_id,则尝试从内存重置 + if case_id and case_id in SCENARIOS: + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + metadata = FILE_METADATA.get(case_id, {}) + + # Reset dynamic fields and re-apply progressive reveal + # 重新初始化节点状态(包括渐进式暴露) + _initialize_node_values(scenario, raw_nodes_data, metadata) + + 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'])}") + + # 生成初始观察信息 + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + + return { + "ok": True, + "message": f"Case {case_id} reset.", + "case_id": case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果既没有 case_file_path,也没有在内存中找到,返回错误 + raise HTTPException( + status_code=400, + detail="Must provide case_file_path to load a new case, or use case_id to reset an existing case." + ) + +class InvestigateRequest(BaseModel): + node_id: str + +@app.post("/env/{case_id}/investigate") +def investigate(case_id: str, req: InvestigateRequest): + """ + Investigates a Tool or Item to reveal detailed information. + + - For Tools: Returns detailed interface information (inputs/outputs) needed to call the tool + - For Items: Returns content value and triggers hidden item drops + """ + logger.info(f"Investigate request - case_id: {case_id}, node_id: {req.node_id}") + STATS["investigates"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + node = scenario.nodes[req.node_id] + + if not node.is_revealed: + logger.warning(f"Attempt to investigate hidden node: {req.node_id}") + return {"ok": False, "error": "Node is not visible yet."} + + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + newly_revealed = [] + + # 处理 Tool 的 investigate + if node.type == "Tool": + logger.info(f"Investigating tool: {req.node_id}") + + # 返回工具的详细接口信息 + # id 字段使用 node.id(节点唯一标识),agent 用这个字段识别和调用具体的节点 + # template_id 是工具类型标识符,Agent 内部用于判断工具特性(如 terminal 类工具参数可选) + # 注意:只过滤输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口),这些端口仅用于控制掉落,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + # 【端口上游依赖提示 & 初始值直接给出】 + # 针对参数语义模糊(全为数字类型)的工具,在 investigate 返回信息中标注 + # 哪个输入端口来自哪个上游节点(upstream_from)。 + # 对于所有工具:若该节点不是纯源头节点(有任意数据流入边), + # 且某个端口没有上游入边(值来自初始可见参数),则直接给出该端口的 golden input 值。 + AMBIGUOUS_TOOLS = { + "num_base_convert", "calc_modexp", "calc_modexp_int", + "calc_inv_mod", "calc_inv_mod_int", "crypto_rsa_decrypt_hex", "geo_haversine" + } + # Terminal 类工具自带参数对错反馈机制,玩家/模型可自行试错, + # 无需在 investigate 时直接暴露 init_value + SELF_FEEDBACK_TOOLS = { + "terminal_1", "terminal_2", + "Logic Terminal", "Math Terminal", "Encryption Terminal", "Sequence Terminal" + } + _template_id_for_hint = raw_nodes_data.get(node.id, {}).get("template_id", "") + # 构建数据流入边映射(对所有工具):{target_port -> (source_node_id, source_port)} + _upstream_map = {} + for _edge in scenario.edges: + if (_edge.target_id == node.id + and _edge.connection_type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM] + and _edge.target_port is not None): + _upstream_map[_edge.target_port] = (_edge.source_id, _edge.source_port) + # 判断该节点是否有任意数据流入边(即不是纯源头节点) + _has_any_upstream = len(_upstream_map) > 0 + # 判断该节点是否有任意入边(包括 ITEM/HIDDEN_ITEM 掉落边) + # 有任意入边(含掉落边)但无数据流入边的节点,其输入来自初始可见参数,应直接给出 + _has_any_edge = any(_edge.target_id == node.id for _edge in scenario.edges) + # 构建 inputs 列表 + _inputs_list = [] + for p in node.inputs: + if p.type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + continue + port_dict = {"name": p.name, "type": p.type, "description": p.description} + if p.name in _upstream_map: + # 该端口有上游数据流依赖,且属于语义模糊工具 → 标注来源 + if _template_id_for_hint in AMBIGUOUS_TOOLS: + src_node_id, src_port = _upstream_map[p.name] + port_dict["upstream_from"] = f"{src_node_id}.{src_port}" if src_port else src_node_id + elif _has_any_edge and _template_id_for_hint not in SELF_FEEDBACK_TOOLS: + # 该节点有任意入边,但此端口没有数据流入边 → 值来自初始可见参数,直接给出 + # 排除自带反馈机制的 terminal 类工具(它们通过执行结果反馈对错,无需提前暴露参数值) + golden_val = node.golden_input_values.get(p.name) + if golden_val is not None: + port_dict["init_value"] = golden_val + _inputs_list.append(port_dict) + + tool_details = { + "id": node.id, # 节点 ID,用于唯一标识和调用这个具体节点 + "type": "Tool", + "inputs": _inputs_list, + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id 用于 Agent 内部判断工具类型(不会展示给被测模型) + if node.id in raw_nodes_data: + template_id = raw_nodes_data[node.id].get('template_id') + if template_id: + tool_details["_template_id"] = template_id # 使用下划线前缀标记为内部字段 + + # 只在 name 非空时添加 + # if node.name: + # tool_details["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_details["description"] = node.description + + # 添加 narrative 字段(如果存在) + if node.id in raw_nodes_data: + narrative = raw_nodes_data[node.id].get('narrative') + if narrative: + tool_details['narrative'] = narrative + + # 不再返回 init_values,避免泄漏答案 + # investigate 只应该返回工具的接口定义,不应该暴露初始值 + + # 【新增】检查该 Tool 是否有待触发的 HIDDEN_ITEM 掉落 + # 如果该工具已按照 golden_input 正确执行,且有 HIDDEN_ITEM 输出边,则触发掉落 + if node.has_hidden_item_ready: + logger.info(f"Tool has HIDDEN_ITEM ready - triggering passive drop for: {req.node_id}") + + # 遍历该工具的所有 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + # 重置标志,已经触发过了,避免重复 + node.has_hidden_item_ready = False + + logger.info(f"Tool investigation successful - node: {req.node_id}, revealed: {len(newly_revealed)}") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Tool", + "details": tool_details + } + + # 如果有新掉落的节点,添加到响应中 + if newly_revealed: + result["newly_revealed"] = newly_revealed + + return result + + # 处理 Item 的 investigate + elif node.type == "Item": + logger.info(f"Investigating item: {req.node_id}") + + # 【第一步】检查该 Item 是否有需要参数的输入端口 + # 如果有,且尚未通过 use_item 验证,则不返回内容,只返回参数要求 + required_inputs = [] + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + inputs_info = raw_node.get('inputs', []) + required_inputs = [ + { + "name": inp.get("name"), + "type": inp.get("type"), + "description": inp.get("description", "") + } + for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + # 如果有 required_inputs 且尚未通过 use_item 验证(if_success == False) + # 则不返回内容,只返回参数要求提示 + if required_inputs and not node.if_success: + logger.info(f"Item has required inputs and not yet unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "required_inputs": required_inputs + } + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + param_names = ', '.join([inp['name'] for inp in required_inputs]) + 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}" + + return result + + # 【新增】如果有 required_inputs 且已经通过 use_item 验证(if_success == True) + # 则返回提示:该节点已经被成功解决 + if required_inputs and node.if_success: + logger.info(f"Item has required inputs and already unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "message": "This item has already been successfully unlocked by you." + } + return result + + # 【第二步】该 Item 没有 required_inputs 或已通过验证,返回内容 + # 1. 返回 Item 的 golden_output_values(即 Item 的内容) + # 注意:某些 Item 仅用于触发 HIDDEN_ITEM 掉落,没有实际内容 + has_actual_content = bool(node.golden_output_values) or node.content is not None + content = node.golden_output_values if node.golden_output_values else node.content + + # 【关键】将 golden_output_values 追加到 actual_outputs_history,标记该 Item 已被 investigate + # 这样在渐进式暴露时,这些值才会被加入可见值集合 + # 即使是空字典(仅触发 HIDDEN_ITEM 的 Item),也要记录,以便渐进式暴露逻辑知道该 Item 已被调查 + if node.golden_output_values is not None: + node.actual_outputs_history.append(dict(node.golden_output_values)) + + # 2. Trigger Hidden Item Drops (Passive Drop) + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + logger.info(f"Item investigation successful - node: {req.node_id}, has_content: {has_actual_content}, revealed: {len(newly_revealed)}") + + # 【渐进式暴露】旧机制(基于 golden_input)已禁用 + # 现在完全由 ITEM/HIDDEN_ITEM 边触发控制节点可见性 + # 上面的 HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, node.golden_output_values or {}, node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # logger.info(f"Progressive reveal after Item investigate: {len(progressive_revealed)} nodes now ready") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Item" + } + + # 只在有实际内容时才添加 content 字段 + # 对于仅触发 HIDDEN_ITEM 掉落的 Item,不返回 content 字段,避免返回 None 或空字典让模型困惑 + if has_actual_content: + result["content"] = content + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型通过 investigate 获得内容后,需要自己识别这是否是胜利字符串 + + return result + + else: + logger.warning(f"Attempt to investigate unknown node type: {req.node_id} (type: {node.type})") + return {"ok": False, "error": f"Cannot investigate node type: {node.type}"} + +class ToolCallRequest(BaseModel): + node_id: str # 使用 node_id 精确指定要调用的节点 + arguments: Dict[str, Any] + +@app.post("/env/{case_id}/tool_call") +def tool_call(case_id: str, req: ToolCallRequest): + """Executes a tool and triggers item drops.""" + logger.info(f"Tool call request - case_id: {case_id}, node_id: {req.node_id}, args: {list(req.arguments.keys())}") + STATS["tool_calls"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + + # 通过 node_id 精确查找节点 + node_id = req.node_id + if node_id not in scenario.nodes: + logger.error(f"Node not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + tool_node = scenario.nodes[node_id] + + if not tool_node: + logger.error(f"Tool not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Tool not found") + + if not tool_node.is_revealed: + logger.warning(f"Attempt to call hidden tool: {node_id}") + return {"ok": False, "error": "Tool is not visible yet."} + + if tool_node.type != "Tool": + logger.warning(f"Attempt to call non-tool node: {node_id} (type: {tool_node.type})") + return {"ok": False, "error": "Only tools can be called."} + + # 1. Execute Tool (Real Execution via Simulator) + simulator = SIMULATORS[case_id] + + # Get tool name from template_id if available, otherwise use node name + tool_name = tool_node.name + if case_id in RAW_NODES_DATA and node_id in RAW_NODES_DATA[case_id]: + template_id = RAW_NODES_DATA[case_id][node_id].get('template_id') + if template_id: + tool_name = template_id + + # 文件处理工具和 Terminal 需要验证输入并返回预先计算的输出 + # 传递节点的实际输入输出值(从 DAG 执行后填充的数据) + tool_arguments = dict(req.arguments) # Make a copy + + # 传递节点的 golden values(从 JSON 的 inputs[].value 和 outputs[].value 加载) + # 用于在评测阶段验证被测模型传入的参数是否正确 + if tool_node.golden_input_values: + tool_arguments['_golden_inputs'] = tool_node.golden_input_values + if tool_node.golden_output_values: + tool_arguments['_golden_outputs'] = tool_node.golden_output_values + + logger.debug(f"Executing tool {tool_name} (node: {tool_node.name}) with args {tool_arguments}") + + try: + output_values = simulator.execute(tool_name, tool_arguments) + logger.info(f"Tool invoked - {tool_name}: {list(output_values.keys())}") + except Exception as e: + logger.error(f"Tool execution failed - {tool_name}: {str(e)}", exc_info=True) + return {"ok": False, "error": f"Tool execution failed: {str(e)}"} + + # 检查验证结果(精细化错误反馈) + validation = output_values.pop("_validation", {"valid": True}) + + if not validation["valid"]: + # 根据错误类型构造友好的错误消息 + error_type = validation.get("error_type") + + if error_type == "missing_required": + missing = validation.get("missing_params", []) + error_msg = f"Error: Missing required parameters {', '.join(missing)}" + + elif error_type == "type_error": + param = validation.get("param_name") + message = validation.get("message", "Parameter type error") + error_msg = f"Error: {message}" + + elif error_type == "incomplete_optional": + provided = validation.get("provided_params", []) + missing = validation.get("missing_params", []) + error_msg = ( + f"Hint: You provided some parameters ({', '.join(provided)}), " + f"but may also need: {', '.join(missing)}.\n" + f"Trying to provide these parameters together might yield better results." + ) + + elif error_type == "value_mismatch": + param = validation.get("param_name") + hint = validation.get("hint", "Parameter value may be incorrect") + error_msg = f"Hint: {hint}.\nPlease check if this parameter value meets the requirements." + + else: + error_msg = validation.get("hint") or validation.get("message", "Parameter validation failed") + + logger.info(f"Tool validation failed - {tool_name}: {error_type}") + return { + "ok": False, + "error": error_msg, + "error_type": error_type + } + + # Simulate success + tool_node.if_success = True + + # 【关键】将本次执行的输出值追加到历史列表(用于渐进式暴露判断) + # 每次调用都会记录,不会覆盖之前的执行结果 + tool_node.actual_outputs_history.append(dict(output_values)) + + # 2. 检查是否应该触发掉落(只有输入参数正确时才掉落) + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, tool_node.golden_input_values) + + newly_revealed = [] + investigate_hints = [] # 提示模型哪些节点可以 investigate 来发现隐藏内容 + + if inputs_match_golden: + logger.info(f"✓ Tool inputs match golden - node: {node_id}, triggering drops") + + # 检查该工具是否有 ITEM 或 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == tool_node.id: + target_node = scenario.nodes[edge.target_id] + + # ITEM 边:立即掉落(主动掉落) + if edge.connection_type == InterfaceType.ITEM: + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from {node_id})") + + # HIDDEN_ITEM 边:不立即掉落,标记并提示(被动掉落) + elif edge.connection_type == InterfaceType.HIDDEN_ITEM: + # 标记该工具有待触发的 HIDDEN_ITEM 掉落 + tool_node.has_hidden_item_ready = True + + # 提示模型可以 investigate 这个工具来发现隐藏内容 + hint_info = { + "tool_id": tool_node.id, + "hint": f"Tool '{tool_node.id}' seems to hide something, try investigating it to discover more information" + } + # if tool_node.name: + # hint_info["tool_name"] = tool_node.name + + investigate_hints.append(hint_info) + logger.info(f"HIDDEN_ITEM ready: {tool_node.id} -> {target_node.id} (will drop on investigate)") + else: + logger.info(f"✗ Tool inputs do NOT match golden - node: {node_id}, no drops triggered") + + response = { + "ok": True, + "message": "Tool invoked", + "output_values": output_values # Return raw outputs to Agent + } + + # 【新增】对源头节点进行参数验证反馈 + # 源头节点:没有数据流入边的节点,这些节点的参数需要模型自己推理 + # 验证模型使用的参数是否正确,并提供明确的反馈 + if _is_source_node(node_id, scenario) and tool_node.golden_input_values: + validation_feedback = _get_parameter_validation_feedback(req.arguments, tool_node.golden_input_values) + + if validation_feedback["all_correct"]: + # 用户提交了全部 golden 参数且全部正确 + response["parameter_feedback"] = { + "status": "correct", + "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." + } + logger.info(f"✓ Source node parameters all correct - node: {node_id}") + elif validation_feedback["incorrect_params"]: + # 有提交了但值错误的参数,只对这些参数给出反馈 + incorrect_list = [] + for param_name in validation_feedback["incorrect_params"]: + incorrect_list.append(f" - Parameter '{param_name}' is incorrect") + + correct_info = "" + if validation_feedback["correct_params"]: + correct_info = f"\n✓ Correct parameters: {', '.join(validation_feedback['correct_params'])}" + + response["parameter_feedback"] = { + "status": "incorrect", + "message": ( + f"⚠️ Some parameters are incorrect:\n" + + "\n".join(incorrect_list) + + correct_info + + 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." + ), + "incorrect_params": validation_feedback["incorrect_params"], + "correct_params": validation_feedback["correct_params"] + } + logger.info(f"✗ Source node parameters incorrect - node: {node_id}, incorrect: {validation_feedback['incorrect_params']}") + # else: 部分提交且全部正确 → 不给任何 parameter_feedback,避免对未提交的参数发表意见 + + # 检查工具调用是否完全正确(输出与 golden outputs 匹配) + # 用于给模型正向反馈,让它知道这个工具已经正确调用过,避免重复调用 + # 注意:只有当输出完全匹配时才标记为 correct,不会在错误时提供具体错误信息 + # if tool_node.golden_output_values and output_values: + # is_correct = True + # for port_name, expected_value in tool_node.golden_output_values.items(): + # actual_value = output_values.get(port_name) + # if str(actual_value) != str(expected_value): + # is_correct = False + # break + + # if is_correct: + # response["tool_call_correct"] = True + # logger.info(f"✓ Tool called with correct result - node: {node_id}") + + # 只在有新内容掉落时才返回 newly_revealed + if newly_revealed: + response["newly_revealed"] = newly_revealed + + # 添加 investigate 提示(对于有待触发 HIDDEN_ITEM 掉落的工具) + if investigate_hints: + response["investigate_hints"] = investigate_hints + + # 3. 渐进式暴露机制 - 现在完全由 ITEM/HIDDEN_ITEM 边控制 + # 旧机制(基于 golden_input 检查)已被禁用 + # 新机制中,节点的可见性只由 ITEM/HIDDEN_ITEM 边触发决定 + # 上面的 ITEM/HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, output_values, tool_node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # response["newly_revealed"] = newly_revealed + # logger.info(f"Progressive reveal: {len(progressive_revealed)} nodes now ready") + + # Check if this is the win node + if node_id == scenario.win_node_id: + # 验证输出值是否等于预期的胜利值 + # 从节点的 golden_output_values 中获取预期值(在 _initialize_node_values 时从 JSON 加载) + expected_outputs = tool_node.golden_output_values + + # 检查实际输出是否与预期输出匹配 + is_correct = False + victory_string = None + mismatch_info = [] + + if expected_outputs and output_values: + # 检查每个预期输出端口的值是否匹配 + is_correct = True + for port_name, expected_value in expected_outputs.items(): + actual_value = output_values.get(port_name) + if actual_value != expected_value: + is_correct = False + mismatch_info.append(f"Port '{port_name}': expected '{expected_value}', actual '{actual_value}'") + logger.warning(f"Win node output mismatch - port: {port_name}, expected: {expected_value}, actual: {actual_value}") + + # 如果所有输出都匹配,使用第一个输出作为胜利字符串 + if is_correct and output_values: + victory_string = list(output_values.values())[0] + else: + logger.warning(f"Win node called but missing output values - expected: {expected_outputs}, actual: {output_values}") + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型调用工具获得输出后,需要自己识别这是否是胜利字符串并提交 + if is_correct: + logger.info(f"🎯 Win node called with correct output - case: {case_id}, node: {node_id}, victory: {victory_string}") + else: + logger.info(f"❌ Win node called with incorrect output - case: {case_id}, node: {node_id}") + + return response + +class UseItemRequest(BaseModel): + node_id: str = Field(..., description="The ID of the Item node to use (must be Item type)") + arguments: Dict[str, Any] = Field(default_factory=dict, description="Input arguments to provide to the item") + +@app.post("/env/{case_id}/use_item") +def use_item(case_id: str, req: UseItemRequest): + """ + Use an Item node by providing input arguments. + + This is specifically for Item nodes that require parameters to be "unlocked" or "activated", + such as containers that need a password/fingerprint. + + - Validates that the node is of type Item + - Checks if provided arguments match the item's golden_input_values + - If match: triggers ITEM-type edge drops and returns the item's content + - If not match: returns error message + """ + logger.info(f"Use item request - case_id: {case_id}, node_id: {req.node_id}, args: {req.arguments}") + STATS["use_items"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + item_node = scenario.nodes[req.node_id] + + if not item_node.is_revealed: + logger.warning(f"Attempt to use hidden item: {req.node_id}") + return {"ok": False, "error": "Item is not visible yet."} + + if item_node.type != "Item": + logger.warning(f"Attempt to use non-item node: {req.node_id} (type: {item_node.type})") + return {"ok": False, "error": "Only Item nodes can be used with use_item. Tools should be called with tool_call."} + + # 【新增】检查该 Item 是否已经被成功解锁 + # 如果已经被正确使用过,直接返回成功提示 + if item_node.if_success: + logger.info(f"Item already unlocked, returning success message: {req.node_id}") + return { + "ok": True, + "message": "This item has already been successfully unlocked by you." + } + + # 检查该 Item 是否真的需要通过 use_item 提供参数 + # 只有当 Item 有非 Item/Hidden_Item 类型的输入时,才应该使用 use_item + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + non_hidden_inputs = [ + inp for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + if not non_hidden_inputs: + # 该 Item 不需要参数,应该只使用 investigate + logger.warning(f"Attempt to use_item on a node that doesn't require parameters: {req.node_id}") + return { + "ok": False, + "error": "This item does not require parameters. Please use investigate to examine the item directly." + } + + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, item_node.golden_input_values) + + if not inputs_match_golden: + logger.info(f"✗ Item inputs do NOT match golden - node: {req.node_id}") + # 提供更详细的错误信息,帮助 Agent 理解问题 + # 只显示非 Item/Hidden_Item 类型的参数(Hidden_Item 由系统自动处理) + expected_params = [] + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + expected_params = [ + inp.get("name") for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + provided_params = list(req.arguments.keys()) if req.arguments else [] + + # 检查参数名是否匹配 + if set(expected_params) == set(provided_params): + # 参数名正确但值不匹配 - 不泄漏正确的值 + error_msg = f"Parameter names are correct, but the parameter values are incorrect. Please try using different parameter values." + else: + error_msg = f"Parameter names do not match. Expected parameter names: {expected_params}, you provided: {provided_params}." + + return { + "ok": False, + "error": error_msg + } + + logger.info(f"✓ Item inputs match golden - node: {req.node_id}, activating item") + + # 标记该 Item 已被正确使用 + item_node.if_success = True + + # 将 golden_output_values 追加到 actual_outputs_history + if item_node.golden_output_values: + item_node.actual_outputs_history.append(dict(item_node.golden_output_values)) + + # 触发 ITEM 类型边的掉落 + newly_revealed = [] + for edge in scenario.edges: + if edge.source_id == item_node.id and edge.connection_type == InterfaceType.ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from use_item on {req.node_id})") + + # 检查是否为 Win Node + win_node_id = scenario.win_node_id + is_win_node = (req.node_id == win_node_id) + + # 构建返回结果 + result = { + "ok": True, + "message": "Item used successfully.", + "content": item_node.golden_output_values if item_node.golden_output_values else None + } + + # 获取 narrative(如果存在) + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + narrative = raw_nodes_data[req.node_id].get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 如果是 Win Node,只记录日志 + if is_win_node: + logger.info(f"Win node (Item) unlocked via use_item - case: {case_id}, node: {req.node_id}") + + return result + + +class SubmitAnswerRequest(BaseModel): + answer: str = Field(..., description="The victory string to submit") + +@app.post("/env/{case_id}/submit_answer") +def submit_answer(case_id: str, req: SubmitAnswerRequest): + """ + 提交答案接口 + 被测模型在获得胜利字符串提示后,需要调用此接口提交答案 + """ + logger.info(f"Submit answer request - case_id: {case_id}, answer: {req.answer}") + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + + # 获取 win_node 的 golden_output_values + if not scenario.win_node_id: + logger.error(f"No win node defined for case: {case_id}") + return { + "ok": False, + "error": "This case has no victory node defined" + } + + win_node = scenario.nodes.get(scenario.win_node_id) + if not win_node: + logger.error(f"Win node not found: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node does not exist" + } + + # 获取正确的胜利字符串(取第一个 golden_output_value) + if win_node.golden_output_values: + correct_answer = list(win_node.golden_output_values.values())[0] + else: + logger.error(f"Win node has no golden_output_values: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node has no correct answer" + } + + # 验证提交的答案 + if req.answer == correct_answer: + logger.info(f"🎉 CORRECT ANSWER SUBMITTED - case: {case_id}, answer: {req.answer}") + return { + "ok": True, + "is_win": True, + "victory_message": f"🎉 Congratulations on successfully escaping the room! Your answer is correct: {req.answer}" + } + else: + logger.info(f"❌ INCORRECT ANSWER SUBMITTED - case: {case_id}, submitted: {req.answer}, correct: {correct_answer}") + return { + "ok": True, + "is_win": False, + "error": f"The submitted answer is incorrect. You submitted: {req.answer}" + } + +if __name__ == "__main__": + + uvicorn.run(app, host="0.0.0.0", port=8000) \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-1c0ee18d/environment/puzzle/upstream/simulator.py b/tasks/agentescape-25-skeleton-1c0ee18d/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-25-skeleton-1c0ee18d/environment/puzzle/upstream/simulator.py @@ -0,0 +1,2911 @@ +import hashlib +import hmac +import base64 +import binascii +import zlib +import json +import uuid +import math +import re +from typing import Dict, Any, List + +class ToolSimulator: + def __init__(self): + """工具模拟器 + + 文件处理工具(zip_unzip, zip_unzip_file, zip_unzip_item, json_get, csv_query, + regex_search, graph_shortest_path)不需要真实文件系统。 + 这些工具只验证输入参数,然后返回预先初始化好的 golden_outputs。 + """ + self.tool_map = { + # 数论 + "calc_bigmul": self.calc_bigmul, + "calc_modexp": self.calc_modexp, + "calc_modexp_int": self.calc_modexp_int, + "calc_gcd": self.calc_gcd, + "calc_gcd_int": self.calc_gcd_int, + "calc_inv_mod": self.calc_inv_mod, + "calc_inv_mod_int": self.calc_inv_mod_int, + + # 哈希 + "hash_sha256": self.hash_sha256, + "hash_md5": self.hash_md5, + "hmac_sha256": self.hmac_sha256, + + # 编码 + "base64_decode": self.base64_decode, + "base64_encode": self.base64_encode, + "hex_decode": self.hex_decode, + "hex_encode": self.hex_encode, + "zlib_inflate": self.zlib_inflate, + "zlib_deflate": self.zlib_deflate, + + # 文件 + "zip_unzip": self.zip_unzip, + "zip_unzip_file": self.zip_unzip_file, + "zip_unzip_item": self.zip_unzip_item, + "regex_search": self.regex_search, + "json_get": self.json_get, + "csv_query": self.csv_query, + "code_py_exec": self.code_py_exec, + + # 图 + "graph_shortest_path": self.graph_shortest_path, + + # 加解密 (简化模拟) + "crypto_aes_cbc_decrypt": self.crypto_aes_cbc_decrypt, + "crypto_rsa_decrypt_hex": self.crypto_rsa_decrypt_hex, + + # 其他 + "num_base_convert": self.num_base_convert, + "time_convert": self.time_convert, + "checksum_crc32": self.checksum_crc32, + "geo_haversine": self.geo_haversine, + "otp_totp_generate": self.otp_totp_generate, + "unicode_norm": self.unicode_norm, + "text_bidi_sanitize": self.text_bidi_sanitize, + "text_xor_hex": self.text_xor_hex, + "text_rotN": self.text_rotN, + "luhn_check": self.luhn_check, + "iban_validate": self.iban_validate, + + # 物理 + "matter_synthesizer": self.matter_synthesizer, + + # 终端机 + "terminal_1": self.terminal_1, + "terminal_2": self.terminal_2, + "Logic Terminal": self.logic_terminal, + "Math Terminal": self.math_terminal, + "Encryption Terminal": self.crypt_terminal, + "Sequence Terminal": self.sequence_terminal + } + + def execute(self, tool_name: str, inputs: Dict[str, Any]) -> Dict[str, Any]: + if tool_name not in self.tool_map: + # Fallback for unknown tools: return dummy outputs based on expected output types + # This should ideally not happen if all tools are implemented + return {} + + try: + return self.tool_map[tool_name](inputs) + except Exception as e: + print(f"Error executing {tool_name}: {e}") + # Return empty or error indication? For generation, we might want to fail hard or return dummy. + # For now, return dummy to keep flow going, but log error. + return {} + + # --- Implementations --- + + def calc_bigmul(self, inputs): + # Check if required parameters are present + if "a" not in inputs or "b" not in inputs: + raise ValueError("Missing required parameters 'a' and/or 'b'") + + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + return {"product": str(a * b)} + except (ValueError, TypeError) as e: + raise ValueError(f"Failed to convert parameters to integers: {str(e)}") + + def calc_modexp(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + try: + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if isinstance(base, str): + base = int(base) + elif not isinstance(base, int): + raise ValueError("Parameter 'base' must be a string or integer") + + if isinstance(exp, str): + exp = int(exp) + elif not isinstance(exp, int): + raise ValueError("Parameter 'exp' must be a string or integer") + + if isinstance(mod, str): + mod = int(mod) + elif not isinstance(mod, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": str(pow(base, exp, mod))} + + def calc_modexp_int(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["base"], int): + raise ValueError("Parameter 'base' must be an integer") + if not isinstance(inputs["exp"], int): + raise ValueError("Parameter 'exp' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": pow(base, exp, mod)} + + def calc_gcd(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + # 计算 GCD 并返回字符串格式(符合 Big_Int 输出类型) + result = math.gcd(a, b) + return {"gcd": str(result)} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def calc_gcd_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["b"], int): + raise ValueError("Parameter 'b' must be an integer") + + # 获取参数 + a = inputs["a"] + b = inputs["b"] + + return {"gcd": math.gcd(a, b)} + + def calc_inv_mod(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + m = inputs["mod"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(m, str): + m = int(m) + elif not isinstance(m, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": str(pow(a, -1, m))} + except ValueError as e: + # 模逆不存在时,返回一个特殊值(用于数据传递) + # 在 DAG 生成阶段,这允许数据流继续 + return {"inv": str(a)} + + def calc_inv_mod_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + a = inputs["a"] + m = inputs["mod"] + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": pow(a, -1, m)} + except ValueError as e: + raise ValueError(f"Modular inverse does not exist: {str(e)}") + + def hash_sha256(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.sha256(text.encode()).hexdigest()} + + def hash_md5(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.md5(text.encode()).hexdigest()} + + def hmac_sha256(self, inputs): + # 参数检查 + if "hex_key" not in inputs: + raise ValueError("Missing required parameter: hex_key") + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["hex_key"], str): + raise ValueError("Parameter 'hex_key' must be a string") + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + try: + key = bytes.fromhex(inputs["hex_key"]) + text = inputs["text"].encode() + return {"hex": hmac.new(key, text, hashlib.sha256).hexdigest()} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def base64_decode(self, inputs): + # 参数检查 + if "data" not in inputs: + raise ValueError("Missing required parameter: data") + + # 类型检查 + if not isinstance(inputs["data"], str): + raise ValueError("Parameter 'data' must be a string") + + data = inputs["data"] + try: + return {"bytes_hex": binascii.hexlify(base64.b64decode(data)).decode()} + except Exception as e: + raise ValueError(f"Base64 decode error: {str(e)}") + + def base64_encode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"b64": base64.b64encode(bytes.fromhex(hex_data)).decode()} + except Exception as e: + raise ValueError(f"Base64 encode error: {str(e)}") + + def hex_decode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"text": bytes.fromhex(hex_data).decode('utf-8', errors='ignore')} + except Exception as e: + raise ValueError(f"Hex decode error: {str(e)}") + + def hex_encode(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + try: + return {"hex": text.encode().hex()} + except Exception as e: + raise ValueError(f"Hex encode error: {str(e)}") + + + # 到此处实现已经更新 + + def zlib_inflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("Parameter 'hex' must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("Missing required parameter: hex") + + try: + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空字符串 + if not hex_data: + raise ValueError("Empty hex string provided") + + # 检查十六进制字符串的有效性 + if len(hex_data) % 2 != 0: + raise ValueError("Hex string must have even length") + + # 检查是否只包含有效的十六进制字符 + if not all(c in '0123456789abcdefABCDEF' for c in hex_data): + raise ValueError("Invalid hex string provided") + + # 尝试解压缩 + return {"text": zlib.decompress(bytes.fromhex(hex_data)).decode('utf-8')} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hex string provided") from e + raise ValueError(f"Invalid zlib data: {e}") from e + except Exception as e: + raise RuntimeError(f"Failed to inflate data: {e}") from e + + def zlib_deflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("Parameter 'text' must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("Missing required parameter: text") + + try: + # 压缩文本 + return {"hex": zlib.compress(text.encode('utf-8')).hex()} + except Exception as e: + raise RuntimeError(f"Failed to deflate data: {e}") from e + + # --- File Operations --- + + def zip_unzip(self, inputs): + """ZIP 解压工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"files": golden_outputs.get("files", "")} + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return {"files": golden_outputs.get("files", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "files" in golden_outputs: + # 验证必需参数 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 检查类型 + if has_zip_id and not isinstance(zip_id, str): + return {"error": "Parameter 'zip_id' must be a string type"} + if has_password and not isinstance(password, str): + return {"error": "Parameter 'password' must be a string type"} + + # 验证输入是否与预期匹配 + if golden_inputs: + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return {"files": golden_outputs["files"]} + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + # 没有golden_inputs但有golden_outputs,直接返回输出 + return {"files": golden_outputs["files"]} + + # 如果没有预期输出,返回空结果 + return {"files": ""} + + def regex_search(self, inputs): + """正则搜索工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"matches": golden_outputs.get("matches", "[]")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "matches" in golden_outputs: + # 提取实际参数 + pattern = inputs.get("pattern") + file_id = inputs.get("file_id") + text = inputs.get("text") + + # 1. 检查必需参数 + if pattern is None: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["pattern"], + "message": "Missing required parameter 'pattern'" + } + } + + # 类型检查 + if not isinstance(pattern, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "pattern", + "message": "Parameter 'pattern' must be a string type" + } + } + if file_id is not None and not isinstance(file_id, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if text is not None and not isinstance(text, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "text", + "message": "Parameter 'text' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合 + provided_params = {} + if pattern is not None: + provided_params["pattern"] = pattern + if file_id is not None: + provided_params["file_id"] = file_id + if text is not None: + provided_params["text"] = text + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数(关键改进) + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_pattern = golden_inputs.get("pattern") + expected_file_id = golden_inputs.get("file_id") + expected_text = golden_inputs.get("text") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_pattern is not None: + if str(pattern) != str(expected_pattern): + incorrect_params.append("pattern") + else: + correct_params.append("pattern") + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_text is not None: + if str(text) != str(expected_text): + incorrect_params.append("text") + else: + correct_params.append("text") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "matches": "[]", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "matches": golden_outputs["matches"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空列表 + return {"matches": "[]"} + + def json_get(self, inputs): + """JSON 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"values": golden_outputs.get("values", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "values" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + jsonpath = inputs.get("jsonpath", "") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if jsonpath is not None and not isinstance(jsonpath, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "jsonpath", + "message": "Parameter 'jsonpath' must be a string type" + } + } + + # 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:jsonpath有默认值"") + provided_params = {} + if file_id is not None: + provided_params["file_id"] = file_id + if jsonpath != "": + provided_params["jsonpath"] = jsonpath + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_jsonpath = golden_inputs.get("jsonpath") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_jsonpath is not None: + if str(jsonpath) != str(expected_jsonpath): + incorrect_params.append("jsonpath") + else: + correct_params.append("jsonpath") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "values": "", + "_validation": validation_info + } + + # 所有验证通过,返回正确输出 + return { + "values": golden_outputs["values"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"values": ""} + + def csv_query(self, inputs): + """CSV 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"rows": golden_outputs.get("rows", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "rows" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + select_columns = inputs.get("select", "") + where_clause = inputs.get("where", "") + + # 1. 检查必需参数 + if file_id is None: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["file_id"], + "message": "Missing required parameter 'file_id'" + } + } + + # 类型检查 + if not isinstance(file_id, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if not isinstance(select_columns, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "select", + "message": "Parameter 'select' must be a string type" + } + } + if not isinstance(where_clause, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "where", + "message": "Parameter 'where' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:select和where有默认值"") + provided_params = {"file_id": file_id} + if select_columns != "": + provided_params["select"] = select_columns + if where_clause != "": + provided_params["where"] = where_clause + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_select = golden_inputs.get("select") + expected_where = golden_inputs.get("where") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_select is not None: + if str(select_columns) != str(expected_select): + incorrect_params.append("select") + else: + correct_params.append("select") + + if expected_where is not None: + if str(where_clause) != str(expected_where): + incorrect_params.append("where") + else: + correct_params.append("where") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "rows": "", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "rows": golden_outputs["rows"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"rows": ""} + + def graph_shortest_path(self, inputs): + """图最短路径工具 + + 如果有 _golden_outputs 或 _init_outputs,验证输入并返回预设输出。 + 否则执行真实的 Dijkstra 算法。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 检查是否在预设模式中(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + if golden_outputs and "path" in golden_outputs: + # 评测阶段但没有 golden_inputs,直接返回 outputs + if not golden_inputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 评测模式:验证输入参数是否匹配 golden 值 + src = inputs.get("src") + dst = inputs.get("dst") + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + + has_src = src is not None and src != "" + has_dst = dst is not None and dst != "" + + # 验证必需参数 + if not has_src or not has_dst: + missing = [] + if not has_src: + missing.append("src") + if not has_dst: + missing.append("dst") + return {"error": "Missing required parameters: " + ", ".join(missing)} + + # 类型检查 + if not isinstance(src, str): + return {"error": "Parameter 'src' must be a string"} + if not isinstance(dst, str): + return {"error": "Parameter 'dst' must be a string"} + + # 验证输入是否匹配期望值 + if golden_inputs: + expected_src = golden_inputs.get("src") + expected_dst = golden_inputs.get("dst") + expected_file_id = golden_inputs.get("file_id") + expected_graph_data = golden_inputs.get("graph_data") + + # 收集验证结果 + incorrect_params = [] + correct_params = [] + + # 检查必需参数是否匹配 + if expected_src is not None: + if str(src) != str(expected_src): + incorrect_params.append("src") + else: + correct_params.append("src") + + if expected_dst is not None: + if str(dst) != str(expected_dst): + incorrect_params.append("dst") + else: + correct_params.append("dst") + + # 检查可选参数(如果在 expected_inputs 中定义了) + if expected_file_id is not None: + if file_id != expected_file_id: + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_graph_data is not None: + if graph_data != expected_graph_data: + incorrect_params.append("graph_data") + else: + correct_params.append("graph_data") + + # 如果有参数不正确,返回详细的反馈 + if incorrect_params: + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 验证通过,返回预设的输出 + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 获取参数(真实执行路径) + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + # Support both src/dst (interface definition) and start/end (original implementation) + start = inputs.get("src") + end = inputs.get("dst") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + raise TypeError("file_id must be a string") + + if graph_data is not None and not isinstance(graph_data, str): + raise TypeError("graph_data must be a string") + + if start is not None and not isinstance(start, str): + raise TypeError("src/start must be a string") + + if end is not None and not isinstance(end, str): + raise TypeError("dst/end must be a string") + + # 检查必需参数 + if file_id is None and graph_data is None: + raise ValueError("Either file_id or graph_data must be provided") + + if start is None: + raise ValueError("src/start parameter is required") + + if end is None: + raise ValueError("dst/end parameter is required") + + # Get graph content + content = None + if file_id is not None: + # 尝试从 VFS 获取(如果存在) + if hasattr(self, 'vfs') and file_id in self.vfs: + content = self.vfs[file_id] + else: + # VFS 不存在或文件不在 VFS 中 + # 返回一个默认的空图结果,或者抛出错误提示需要 init_outputs + raise ValueError( + f"File '{file_id}' not found. For tools that require files, " + f"please provide init_outputs in the initial_values." + ) + elif graph_data is not None: + content = graph_data + + if content is None: + content = "{}" + + try: + # Parse graph data + graph = json.loads(content) + + # 类型检查 + if not isinstance(graph, dict): + raise TypeError("Graph data must be a dictionary") + + # If graph is not in the expected format, try to extract adjacency list + if "nodes" in graph and "edges" in graph: + # 验证nodes和edges的类型 + if not isinstance(graph["nodes"], list): + raise TypeError("Nodes must be a list") + + if not isinstance(graph["edges"], list): + raise TypeError("Edges must be a list") + + # Convert from nodes/edges format to adjacency list + adjacency_list = {} + for node in graph["nodes"]: + # 验证node类型 + if not isinstance(node, dict): + raise TypeError("Each node must be a dictionary") + + # Use node ID as key, not the entire node dictionary + node_id = node.get("id", "") + if node_id: + adjacency_list[node_id] = {} + + for edge in graph["edges"]: + # 验证edge类型 + if not isinstance(edge, dict): + raise TypeError("Each edge must be a dictionary") + + u = edge["from"] + v = edge["to"] + weight = edge.get("weight", 1) # Default to unweighted + + # 类型检查 + if not isinstance(u, str): + raise TypeError("Edge 'from' must be a string") + + if not isinstance(v, str): + raise TypeError("Edge 'to' must be a string") + + if not isinstance(weight, (int, float)): + raise TypeError("Edge weight must be a number") + + if u not in adjacency_list: + adjacency_list[u] = {} + if v not in adjacency_list: + adjacency_list[v] = {} + + adjacency_list[u][v] = weight + # If undirected, add reverse edge + if not edge.get("directed", False): + adjacency_list[v][u] = weight + elif isinstance(graph, dict): + # Already in adjacency list format + adjacency_list = graph + + # 验证邻接表结构 + for node, neighbors in adjacency_list.items(): + if not isinstance(neighbors, dict): + raise TypeError("Adjacency list must be a dictionary of dictionaries") + + for neighbor, weight in neighbors.items(): + if not isinstance(weight, (int, float)): + raise TypeError("Edge weights must be numbers") + else: + raise TypeError("Graph data must be a dictionary") + + # 检查起点和终点是否为空 + if not start: + raise ValueError("Start node cannot be empty") + + if not end: + raise ValueError("End node cannot be empty") + + # 检查起点和终点是否在图中 + if start not in adjacency_list: + raise ValueError(f"Start node '{start}' not found in graph") + + if end not in adjacency_list: + raise ValueError(f"End node '{end}' not found in graph") + + # Dijkstra's algorithm implementation + import heapq + + # Initialize distances and previous nodes + distances = {node: float('infinity') for node in adjacency_list} + previous = {node: None for node in adjacency_list} + distances[start] = 0 + + # Priority queue + pq = [(0, start)] + heapq.heapify(pq) + + while pq: + current_dist, current_node = heapq.heappop(pq) + + # If we've reached the end node, we can break early + if current_node == end: + break + + # Nodes can be added multiple times to the priority queue, but we only process them once + if current_dist > distances[current_node]: + continue + + # Explore neighbors + for neighbor, weight in adjacency_list[current_node].items(): + distance = current_dist + weight + + # If a shorter path is found + if distance < distances[neighbor]: + distances[neighbor] = distance + previous[neighbor] = current_node + heapq.heappush(pq, (distance, neighbor)) + + # Reconstruct the shortest path + path = [] + current = end + while current is not None: + path.append(current) + current = previous[current] + path.reverse() # Reverse to get from start to end + + # Check if path exists + if not path or path[0] != start: + return {"path": "[]", "cost": 0} + + return { + "path": json.dumps(path), + "cost": distances[end] + } + except json.JSONDecodeError as e: + raise ValueError(f"Invalid JSON in graph data: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in graph_shortest_path: {str(e)}") + + # --- Crypto (Simplified) --- + def crypto_aes_cbc_decrypt(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 (使用模板中定义的参数名) + hex_cipher = inputs.get("hex_cipher") + hex_key = inputs.get("hex_key") + hex_iv = inputs.get("hex_iv") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + + if hex_key is not None and not isinstance(hex_key, str): + raise TypeError("hex_key must be a string") + + if hex_iv is not None and not isinstance(hex_iv, str): + raise TypeError("hex_iv must be a string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + + if hex_key is None: + raise ValueError("hex_key parameter is required") + + if hex_iv is None: + raise ValueError("hex_iv parameter is required") + + from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes + from cryptography.hazmat.backends import default_backend + from cryptography.hazmat.primitives import padding + + try: + # Convert hex strings to bytes + ciphertext = bytes.fromhex(hex_cipher) + key = bytes.fromhex(hex_key) + iv = bytes.fromhex(hex_iv) + + # Validate key length (AES-128, AES-192, AES-256) + if len(key) not in [16, 24, 32]: + raise ValueError("Invalid key length. Must be 16, 24, or 32 bytes.") + + if len(iv) != 16: + raise ValueError("Invalid IV length. Must be 16 bytes.") + + # Create cipher object + cipher = Cipher( + algorithms.AES(key), + modes.CBC(iv), + backend=default_backend() + ) + + decryptor = cipher.decryptor() + + # Decrypt the ciphertext + padded_plaintext = decryptor.update(ciphertext) + decryptor.finalize() + + # Remove PKCS7 padding + unpadder = padding.PKCS7(128).unpadder() + plaintext = unpadder.update(padded_plaintext) + unpadder.finalize() + + # Return decrypted text + return {"text": plaintext.decode('utf-8', errors='ignore')} + except ValueError as e: + if "non-hexadecimal number found in fromhex()" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher, hex_key, or hex_iv") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in crypto_aes_cbc_decrypt: {str(e)}") + + def crypto_rsa_decrypt_hex(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_cipher = inputs.get("hex_cipher") + n = inputs.get("n") + d = inputs.get("d") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + if n is not None and not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + if d is not None and not isinstance(d, (int, str)): + raise TypeError("d must be an integer or string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + if n is None: + raise ValueError("n parameter is required") + if d is None: + raise ValueError("d parameter is required") + + try: + # Convert parameters to appropriate types + cipher_int = int(hex_cipher, 16) + n_int = int(n) if isinstance(n, str) else n + d_int = int(d) if isinstance(d, str) else d + + # RSA decryption: plaintext = ciphertext^d mod n + plaintext_int = pow(cipher_int, d_int, n_int) + + # Convert result to hex and then to text + plaintext_hex = hex(plaintext_int)[2:] + + # Pad with leading zero if odd length + if len(plaintext_hex) % 2 != 0: + plaintext_hex = '0' + plaintext_hex + + # Convert hex to bytes and then to text + try: + plaintext_bytes = bytes.fromhex(plaintext_hex) + plaintext_text = plaintext_bytes.decode('utf-8', errors='ignore') + except: + # If decoding fails, return hex representation + plaintext_text = plaintext_hex + + return {"text": plaintext_text} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in crypto_rsa_decrypt_hex: {str(e)}") + + # --- Others --- + def num_base_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + s = inputs.get("s") + from_base = inputs.get("from_base") + to_base = inputs.get("to_base") + + # 类型检查 - 接受 str 或 int + if s is not None and not isinstance(s, (str, int)): + raise TypeError("s must be a string or integer") + + if from_base is not None and not isinstance(from_base, (int, str)): + raise TypeError("from_base must be an integer") + + if to_base is not None and not isinstance(to_base, (int, str)): + raise TypeError("to_base must be an integer") + + # 检查必需参数 + if s is None: + raise ValueError("s parameter is required") + + if from_base is None: + raise ValueError("from_base parameter is required") + + if to_base is None: + raise ValueError("to_base parameter is required") + + try: + # Convert to int if needed + from_base = int(from_base) if isinstance(from_base, str) else from_base + to_base = int(to_base) if isinstance(to_base, str) else to_base + s_str = str(s) + + # 验证基数范围 + if from_base < 2 or from_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + if to_base < 2 or to_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + # Convert from source base to decimal + val = int(s_str, from_base) + + # Convert from decimal to target base + if to_base == 10: + result = str(val) + elif to_base == 16: + result = hex(val)[2:] + elif to_base == 8: + result = oct(val)[2:] + elif to_base == 2: + result = bin(val)[2:] + else: + # Generic base conversion for other bases + if val == 0: + result = "0" + else: + digits = "0123456789abcdefghijklmnopqrstuvwxyz" + result = "" + n = abs(val) + while n: + result = digits[n % to_base] + result + n //= to_base + if val < 0: + result = "-" + result + + return {"str": result} + except ValueError as e: + raise ValueError(f"Invalid number format: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in num_base_convert: {str(e)}") + + def time_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iso = inputs.get("iso") + timestamp = inputs.get("timestamp") + datetime_str = inputs.get("datetime") + from_tz = inputs.get("from_tz") + to_tz = inputs.get("to_tz") + format_str = inputs.get("format") + + # 类型检查 + if iso is not None and not isinstance(iso, str): + raise TypeError("iso must be a string") + + if timestamp is not None and not isinstance(timestamp, (str, int, float)): + raise TypeError("timestamp must be a string, integer, or float") + + if datetime_str is not None and not isinstance(datetime_str, str): + raise TypeError("datetime must be a string") + + if from_tz is not None and not isinstance(from_tz, str): + raise TypeError("from_tz must be a string") + + if to_tz is not None and not isinstance(to_tz, str): + raise TypeError("to_tz must be a string") + + if format_str is not None and not isinstance(format_str, str): + raise TypeError("format must be a string") + + # 设置默认值 + if from_tz is None: + from_tz = "UTC" + + if to_tz is None: + to_tz = "UTC" + + import datetime + import pytz + + # 验证时区参数 + try: + if from_tz: + pytz.timezone(from_tz) + if to_tz: + pytz.timezone(to_tz) + except Exception: + raise ValueError("Invalid timezone provided") + + try: + # Parse input time + dt = None + + if iso is not None: + # Parse ISO 8601 format + dt = datetime.datetime.fromisoformat(iso.replace('Z', '+00:00')) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=pytz.UTC) + elif timestamp is not None: + # Parse Unix timestamp + timestamp = float(timestamp) + dt = datetime.datetime.fromtimestamp(timestamp, pytz.UTC) + elif datetime_str is not None: + # Parse datetime string + # Try common formats + formats_to_try = [ + "%Y-%m-%d %H:%M:%S", + "%Y-%m-%d %H:%M:%S.%f", + "%Y-%m-%d", + "%m/%d/%Y %H:%M:%S", + "%m/%d/%Y" + ] + + parse_success = False + for fmt in formats_to_try: + try: + dt = datetime.datetime.strptime(datetime_str, fmt) + dt = pytz.timezone(from_tz).localize(dt) + parse_success = True + break + except ValueError: + continue + + if not parse_success: + raise ValueError("Unable to parse datetime string with common formats") + else: + # 如果没有提供任何时间参数,则使用当前时间 + dt = datetime.datetime.now(pytz.UTC) + except ValueError as e: + raise ValueError(f"Error parsing time input: {str(e)}") + except Exception as e: + raise RuntimeError(f"Unexpected error parsing time input: {str(e)}") + + try: + # Convert timezone + if from_tz != to_tz: + dt = dt.astimezone(pytz.timezone(to_tz)) + + # Format outputs + result = { + "iso": dt.isoformat(), + "timestamp": str(dt.timestamp()), + "datetime": dt.strftime("%Y-%m-%d %H:%M:%S"), + "date": dt.strftime("%Y-%m-%d"), + "time": dt.strftime("%H:%M:%S"), + "timezone": to_tz + } + + # Add custom format if requested + if format_str: + try: + result["formatted"] = dt.strftime(format_str) + except ValueError as e: + raise ValueError(f"Invalid format string: {str(e)}") + + return result + except Exception as e: + raise RuntimeError(f"Error in time_convert: {str(e)}") + + def checksum_crc32(self, inputs): + import zlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("hex must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("hex parameter is required") + + try: + # 验证十六进制字符串 + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空 + if not hex_data: + raise ValueError("hex data cannot be empty") + + # 检查是否为有效的十六进制字符串 + if not all(c in "0123456789abcdefABCDEF" for c in hex_data): + raise ValueError("hex must be a valid hexadecimal string") + + # 检查长度是否为偶数 + if len(hex_data) % 2 != 0: + raise ValueError("hex must have even number of characters") + + val = zlib.crc32(bytes.fromhex(hex_data)) + # 确保 hex 输出是 8 位,前导补 0 + return {"hex": f"{val:08x}", "int": val} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in checksum_crc32: {str(e)}") + + def geo_haversine(self, inputs): + import math + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + lat1 = inputs.get("lat1") + lon1 = inputs.get("lon1") + lat2 = inputs.get("lat2") + lon2 = inputs.get("lon2") + + # 类型检查 + if lat1 is not None and not isinstance(lat1, (int, float, str)): + raise TypeError("lat1 must be a number or string") + if lon1 is not None and not isinstance(lon1, (int, float, str)): + raise TypeError("lon1 must be a number or string") + if lat2 is not None and not isinstance(lat2, (int, float, str)): + raise TypeError("lat2 must be a number or string") + if lon2 is not None and not isinstance(lon2, (int, float, str)): + raise TypeError("lon2 must be a number or string") + + # 检查必需参数 + if lat1 is None: + raise ValueError("lat1 parameter is required") + if lon1 is None: + raise ValueError("lon1 parameter is required") + if lat2 is None: + raise ValueError("lat2 parameter is required") + if lon2 is None: + raise ValueError("lon2 parameter is required") + + try: + # 转换为浮点数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(lat1, str): + lat1 = float(lat1) + elif not isinstance(lat1, (int, float)): + raise TypeError("lat1 must be a number or string") + else: + lat1 = float(lat1) + + if isinstance(lon1, str): + lon1 = float(lon1) + elif not isinstance(lon1, (int, float)): + raise TypeError("lon1 must be a number or string") + else: + lon1 = float(lon1) + + if isinstance(lat2, str): + lat2 = float(lat2) + elif not isinstance(lat2, (int, float)): + raise TypeError("lat2 must be a number or string") + else: + lat2 = float(lat2) + + if isinstance(lon2, str): + lon2 = float(lon2) + elif not isinstance(lon2, (int, float)): + raise TypeError("lon2 must be a number or string") + else: + lon2 = float(lon2) + + # Validate coordinates (approximate range check) + if not (-90 <= lat1 <= 90): + raise ValueError("lat1 must be between -90 and 90") + if not (-90 <= lat2 <= 90): + raise ValueError("lat2 must be between -90 and 90") + if not (-180 <= lon1 <= 180): + raise ValueError("lon1 must be between -180 and 180") + if not (-180 <= lon2 <= 180): + raise ValueError("lon2 must be between -180 and 180") + + # Earth radius in meters + R = 6371000 # Approximate radius of Earth + + # Convert degrees to radians + lat1_rad = math.radians(lat1) + lon1_rad = math.radians(lon1) + lat2_rad = math.radians(lat2) + lon2_rad = math.radians(lon2) + + # Calculate differences + delta_lat = lat2_rad - lat1_rad + delta_lon = lon2_rad - lon1_rad + + # Haversine formula + a = math.sin(delta_lat / 2) ** 2 + \ + math.cos(lat1_rad) * math.cos(lat2_rad) * \ + math.sin(delta_lon / 2) ** 2 + c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) + distance_m = R * c + + # Return distance in meters + return {"meters": round(distance_m, 2)} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in geo_haversine: {str(e)}") + + def otp_totp_generate(self, inputs): + import hmac + import hashlib + import base64 + import time + import struct + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + base32_secret = inputs.get("base32_secret") + step = inputs.get("step", 30) # Default to 30 seconds + digits = inputs.get("digits", 6) # Default to 6 digits + timestamp_iso = inputs.get("timestamp_iso", "") + algo = inputs.get("algo", "sha1") # Default to sha1 as current implementation only supports this + + # 类型检查 + if base32_secret is not None and not isinstance(base32_secret, str): + raise TypeError("base32_secret must be a string") + if not isinstance(step, (int, str)): + raise TypeError("step must be an integer or string") + if not isinstance(digits, (int, str)): + raise TypeError("digits must be an integer or string") + if not isinstance(timestamp_iso, str): + raise TypeError("timestamp_iso must be a string") + if not isinstance(algo, str): + raise TypeError("algo must be a string") + + # 检查必需参数 + if base32_secret is None: + raise ValueError("base32_secret parameter is required") + + try: + # Convert step and digits to appropriate types + step = int(step) + digits = int(digits) + if digits < 6 or digits > 8: + raise ValueError("Digits must be between 6 and 8") + + # Convert timestamp_iso to integer timestamp + if timestamp_iso: + import datetime + dt = datetime.datetime.fromisoformat(timestamp_iso.replace('Z', '+00:00')) + timestamp = int(dt.timestamp()) + else: + timestamp = int(time.time()) + + # Calculate counter value (T = floor(timestamp / step)) + counter = timestamp // step + + # Decode the base32 secret + # Add padding if necessary (base64 requires padding to be multiple of 8) + base32_secret = base32_secret.upper().replace(' ', '') + if len(base32_secret) % 8 != 0: + base32_secret += '=' * (8 - (len(base32_secret) % 8)) + key = base64.b32decode(base32_secret, casefold=True) + + # Calculate HMAC-SHA1 + counter_bytes = struct.pack('>Q', counter) # Big-endian 8-byte integer + hmac_hash = hmac.new(key, counter_bytes, hashlib.sha1).digest() + + # Dynamic truncation + offset = hmac_hash[-1] & 0xF + code = struct.unpack('>I', hmac_hash[offset:offset+4])[0] & 0x7FFFFFFF + + # Generate the OTP + otp = str(code % (10 ** digits)).zfill(digits) + + # Calculate remaining time until next OTP change + remaining_time = step - (timestamp % step) + + return {"totp": otp, "remaining_time": remaining_time, "time_step": step} + except ValueError as e: + if "invalid literal for int()" in str(e): + raise ValueError("step and digits must be valid integers") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in otp_totp_generate: {str(e)}") + + def unicode_norm(self, inputs): + import unicodedata + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + form = inputs.get("form", "NFC") # Default to NFC + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if form is not None and not isinstance(form, str): + raise TypeError("form must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Normalize form (NFC, NFD, NFKC, NFKD) + form = form.upper().strip() + + if form not in ['NFC', 'NFD', 'NFKC', 'NFKD']: + raise ValueError(f"Invalid normalization form: {form}. Must be one of: NFC, NFD, NFKC, NFKD") + + # Apply Unicode normalization + normalized_text = unicodedata.normalize(form, text) + + return {"text": normalized_text} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in unicode_norm: {str(e)}") + + def text_bidi_sanitize(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Bidi control characters to remove + bidi_controls = [ + '\u200E', # LEFT-TO-RIGHT MARK + '\u200F', # RIGHT-TO-LEFT MARK + '\u202A', # LEFT-TO-RIGHT EMBEDDING + '\u202B', # RIGHT-TO-LEFT EMBEDDING + '\u202C', # POP DIRECTIONAL FORMATTING + '\u202D', # LEFT-TO-RIGHT OVERRIDE + '\u202E', # RIGHT-TO-LEFT OVERRIDE + '\u2066', # LEFT-TO-RIGHT ISOLATE + '\u2067', # RIGHT-TO-LEFT ISOLATE + '\u2068', # FIRST STRONG ISOLATE + '\u2069', # POP DIRECTIONAL ISOLATE + ] + + # Remove all Bidi control characters + sanitized_text = text + for control_char in bidi_controls: + sanitized_text = sanitized_text.replace(control_char, '') + + return {"text": sanitized_text} + except Exception as e: + raise RuntimeError(f"Error in text_bidi_sanitize: {str(e)}") + + def text_xor_hex(self, inputs): + import binascii + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_a = inputs.get("hex_a") + hex_b = inputs.get("hex_b") + + # 类型检查 + if hex_a is not None and not isinstance(hex_a, str): + raise TypeError("hex_a must be a string") + if hex_b is not None and not isinstance(hex_b, str): + raise TypeError("hex_b must be a string") + + # 检查必需参数 + if hex_a is None: + raise ValueError("hex_a parameter is required") + if hex_b is None: + raise ValueError("hex_b parameter is required") + + try: + # Remove any whitespace + hex_a = hex_a.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + hex_b = hex_b.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + + # Validate hex strings + if not (all(c in "0123456789abcdefABCDEF" for c in hex_a) and len(hex_a) % 2 == 0): + raise ValueError("hex_a must be a valid hexadecimal string with even length") + if not (all(c in "0123456789abcdefABCDEF" for c in hex_b) and len(hex_b) % 2 == 0): + raise ValueError("hex_b must be a valid hexadecimal string with even length") + + # Convert hex strings to bytes + bytes_a = binascii.unhexlify(hex_a) + bytes_b = binascii.unhexlify(hex_b) + + # Make the byte arrays the same length by padding the shorter one with zeros + max_len = max(len(bytes_a), len(bytes_b)) + bytes_a = bytes_a.ljust(max_len, b'\x00') + bytes_b = bytes_b.ljust(max_len, b'\x00') + + # Perform XOR operation + result_bytes = bytes(a ^ b for a, b in zip(bytes_a, bytes_b)) + + # Convert result back to hex + result_hex = binascii.hexlify(result_bytes).decode('utf-8') + + return {"hex": result_hex} + except ValueError as e: + if "Non-hexadecimal digit found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in text_xor_hex: {str(e)}") + + def text_rotN(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + n = inputs.get("n", 0) + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + n = int(n) + except ValueError: + raise ValueError("n must be a valid integer") + + result = [] + for char in text: + if char.isupper(): + # Rotate uppercase letters + result_char = chr((ord(char) - ord('A') + n) % 26 + ord('A')) + result.append(result_char) + elif char.islower(): + # Rotate lowercase letters + result_char = chr((ord(char) - ord('a') + n) % 26 + ord('a')) + result.append(result_char) + else: + # Keep non-alphabetic characters unchanged + result.append(char) + + return {"text": ''.join(result)} + + def luhn_check(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数(支持 card_number 和 number 两个参数名) + card_number = inputs.get("number") or inputs.get("card_number") + + # 类型检查 + if card_number is not None and not isinstance(card_number, str): + raise TypeError("number must be a string") + + # 检查必需参数 + if card_number is None: + raise ValueError("number parameter is required") + + try: + # 如果输入是JSON数组或其他非数字字符串,返回该字符串本身(用于数据传递) + # 这种情况发生在DAG设计中类型不匹配时 + if card_number.startswith('[') or card_number.startswith('{'): + # 输入是JSON,直接返回原值(用于传递) + return {"valid": card_number} + + # Remove whitespace from card number + card_number = card_number.replace(" ", "").replace("-", "") + + # Check if card number is all digits + if not card_number.isdigit() or len(card_number) < 13: + return {"valid": "false"} + + # Implement Luhn algorithm + total = 0 + reverse_digits = card_number[::-1] # Reverse the number for easier processing + + for i, digit in enumerate(reverse_digits): + num = int(digit) + if i % 2 == 1: # Every second digit starting from the right (which is first in reversed string) + num *= 2 + if num > 9: + num -= 9 # Equivalent to sum of digits for 2-digit numbers + total += num + + # Check if total is divisible by 10 + is_valid = total % 10 == 0 + return {"valid": "true" if is_valid else "false"} + except Exception as e: + raise RuntimeError(f"Error in luhn_check: {str(e)}") + + def iban_validate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iban = inputs.get("iban") + + # 类型检查 + if iban is not None and not isinstance(iban, str): + raise TypeError("iban must be a string") + + # 检查必需参数 + if iban is None: + raise ValueError("iban parameter is required") + + try: + # Remove whitespace from IBAN + iban = iban.replace(" ", "") + + # Basic length and format check + if not (len(iban) >= 15 and len(iban) <= 34): + return {"valid": "False"} + + if not (iban[:2].isalpha() and iban[2:].isdigit()): + return {"valid": "False"} + + # Move first four characters to the end + rearranged = iban[4:] + iban[:4] + + # Replace letters with numbers (A=10, B=11, ..., Z=35) + numeric_iban = '' + for char in rearranged: + if char.isdigit(): + numeric_iban += char + else: + numeric_iban += str(ord(char.upper()) - ord('A') + 10) + + # Perform modulo 97 check + # Use step-by-step approach for very large numbers + remainder = 0 + for char in numeric_iban: + remainder = (remainder * 10 + int(char)) % 97 + + is_valid = remainder == 1 + return {"valid": "True" if is_valid else "False"} + except Exception as e: + raise RuntimeError(f"Error in iban_validate: {str(e)}") + + def matter_synthesizer(self, inputs): + import hashlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + blueprint = inputs.get("blueprint") + + # 类型检查 + if blueprint is not None and not isinstance(blueprint, str): + raise TypeError("blueprint must be a string") + + try: + # Get blueprint parameter as defined in interface + if blueprint is None: + blueprint = "" + + # Generate a unique item ID based on the blueprint + # This ensures the same blueprint always produces the same item + blueprint_hash = hashlib.sha256(blueprint.encode()).hexdigest()[:16] + + # Create a synthesized item with a deterministic ID based on blueprint + synthesized_item = f"synthesized_item_{blueprint_hash}" + + return {"output_slot": synthesized_item} + except Exception as e: + raise RuntimeError(f"Error in matter_synthesizer: {str(e)}") + + # --- Terminal Implementations --- + def terminal_1(self, inputs): + """ + terminal_1: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 只返回 text_output + - 只输入正确的 slot_b → 只返回 hex_output + - 同时输入正确的 slot_a 和 slot_b → 返回 item_dispenser(物品掉落) + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + # 检查哪些输入被提供了 + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值是否正确(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + expected_a = golden_inputs["slot_a"] + a_valid = str(slot_a) == str(expected_a) + + if has_b and "slot_b" in golden_inputs: + expected_b = golden_inputs["slot_b"] + b_valid = str(slot_b) == str(expected_b) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 item_dispenser + if has_a and has_b: + if a_valid and b_valid: + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 text_output + if has_a and not has_b: + if a_valid: + if "text_output" in golden_outputs: + result["text_output"] = golden_outputs["text_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 hex_output + if has_b and not has_a: + if b_valid: + if "hex_output" in golden_outputs: + result["hex_output"] = golden_outputs["hex_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def terminal_2(self, inputs): + """ + terminal_2: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 text_result + - 同时输入正确的 num1 和 num2 → 返回 hex_result 和 math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + # 检查哪些输入被提供了 + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值是否正确(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + expected_num1 = golden_inputs["num1"] + num1_valid = str(num1) == str(expected_num1) + + if has_num2 and "num2" in golden_inputs: + expected_num2 = golden_inputs["num2"] + num2_valid = str(num2) == str(expected_num2) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 hex_result 和 math_token + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 text_result + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "text_result" in golden_outputs: + result["text_result"] = golden_outputs["text_result"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def logic_terminal(self, inputs): + """ + Logic Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 返回 screen(部分输出) + - 只输入正确的 slot_b → 返回 screen 和 secondary_output + - 同时输入正确的 slot_a 和 slot_b → 返回 screen, secondary_output, item_dispenser + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + a_valid = str(slot_a) == str(golden_inputs["slot_a"]) + + if has_b and "slot_b" in golden_inputs: + b_valid = str(slot_b) == str(golden_inputs["slot_b"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出(包括 item_dispenser) + if has_a and has_b: + if a_valid and b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 screen(部分输出) + if has_a and not has_b: + if a_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 screen 和 secondary_output + if has_b and not has_a: + if b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def math_terminal(self, inputs): + """ + Math Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 result_display + - 同时输入正确的 num1 和 num2 → 返回 result_display, hex_result, math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + num1_valid = str(num1) == str(golden_inputs["num1"]) + + if has_num2 and "num2" in golden_inputs: + num2_valid = str(num2) == str(golden_inputs["num2"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 result_display + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def crypt_terminal(self, inputs): + """ + Encryption Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 plaintext → 返回 status(部分输出) + - 同时输入正确的 plaintext 和 key → 返回 status, encrypted_hex, encryption_chip + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + plaintext = inputs.get("plaintext") + key = inputs.get("key") + + has_plaintext = plaintext is not None and plaintext != "" + has_key = key is not None and key != "" + + # 验证输入值(与 golden values 比较) + plaintext_valid = False + key_valid = False + + if has_plaintext and "plaintext" in golden_inputs: + plaintext_valid = str(plaintext) == str(golden_inputs["plaintext"]) + + if has_key and "key" in golden_inputs: + key_valid = str(key) == str(golden_inputs["key"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_plaintext and has_key: + if plaintext_valid and key_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + if "encrypted_hex" in golden_outputs: + result["encrypted_hex"] = golden_outputs["encrypted_hex"] + if "encryption_chip" in golden_outputs: + result["encryption_chip"] = golden_outputs["encryption_chip"] + return result + else: + incorrect_params = [] + correct_params = [] + if not plaintext_valid: + incorrect_params.append("plaintext") + else: + correct_params.append("plaintext") + if not key_valid: + incorrect_params.append("key") + else: + correct_params.append("key") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 plaintext 且正确 → 返回 status(部分输出) + if has_plaintext and not has_key: + if plaintext_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: plaintext"} + + # 只提供 key 但没有 plaintext + if has_key and not has_plaintext: + return {"error": "plaintext required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + def sequence_terminal(self, inputs): + """ + Sequence Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 sequence → 返回 verification(部分输出) + - 同时输入正确的 sequence 和 checksum → 返回 verification, auth_code, access_card + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + sequence = inputs.get("sequence") + checksum = inputs.get("checksum") + + has_sequence = sequence is not None and sequence != "" + has_checksum = checksum is not None and checksum != "" + + # 验证输入值(与 golden values 比较) + sequence_valid = False + checksum_valid = False + + if has_sequence and "sequence" in golden_inputs: + sequence_valid = str(sequence) == str(golden_inputs["sequence"]) + + if has_checksum and "checksum" in golden_inputs: + checksum_valid = str(checksum) == str(golden_inputs["checksum"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_sequence and has_checksum: + if sequence_valid and checksum_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + if "auth_code" in golden_outputs: + result["auth_code"] = golden_outputs["auth_code"] + if "access_card" in golden_outputs: + result["access_card"] = golden_outputs["access_card"] + return result + else: + incorrect_params = [] + correct_params = [] + if not sequence_valid: + incorrect_params.append("sequence") + else: + correct_params.append("sequence") + if not checksum_valid: + incorrect_params.append("checksum") + else: + correct_params.append("checksum") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 sequence 且正确 → 返回 verification(部分输出) + if has_sequence and not has_checksum: + if sequence_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: sequence"} + + # 只提供 checksum 但没有 sequence + if has_checksum and not has_sequence: + return {"error": "sequence required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + # --- Additional File Tools --- + + def zip_unzip_file(self, inputs): + """ZIP 解压文件工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def zip_unzip_item(self, inputs): + """ZIP 解压道具工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def code_py_exec(self, inputs): + """Python 代码执行工具 + + 这是一个真实执行的工具,在 DAG 生成阶段和运行时评测阶段都会执行代码。 + 输入: code (Python 代码字符串) + 输出: stdout (标准输出,包含执行结果和错误信息) + + 特殊行为: + - 如果代码定义了 main() 函数,会自动调用它 + - 如果执行出错,错误信息会包含在 stdout 中 + """ + code = inputs.get("code", "") + + if not code: + return {"stdout": "Error: No code provided"} + + try: + # 创建一个受限的执行环境 + import io + import sys + + # 捕获标准输出和标准错误 + old_stdout = sys.stdout + old_stderr = sys.stderr + sys.stdout = io.StringIO() + sys.stderr = io.StringIO() + + # 执行代码 + exec_globals = {"__builtins__": __builtins__} + exec_locals = {} + exec(code, exec_globals, exec_locals) + + # 如果定义了 main() 函数,自动调用它 + if 'main' in exec_locals and callable(exec_locals['main']): + exec_locals['main']() + + # 获取输出 + stdout_value = sys.stdout.getvalue() + stderr_value = sys.stderr.getvalue() + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 合并 stdout 和 stderr + output = stdout_value + if stderr_value: + output += ("\n" if output else "") + f"[stderr] {stderr_value}" + + # 如果没有任何输出,尝试返回 result 变量的值 + if not output: + result = exec_locals.get("_result") or exec_locals.get("result") + if result is not None: + output = str(result) + + return {"stdout": output if output else "(no output)"} + + except Exception as e: + # 恢复标准输出和错误输出 + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 返回错误信息 + return {"stdout": f"Error: {type(e).__name__}: {str(e)}"} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-1c0ee18d/environment/puzzle/worker.Dockerfile b/tasks/agentescape-25-skeleton-1c0ee18d/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-25-skeleton-1c0ee18d/environment/puzzle/worker.Dockerfile @@ -0,0 +1,8 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends libseccomp2 && rm -rf /var/lib/apt/lists/* +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY worker.py child.py /app/ +COPY upstream/simulator.py /app/simulator.py +CMD ["uvicorn", "worker:app", "--host", "0.0.0.0", "--port", "8001", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-25-skeleton-1c0ee18d/environment/puzzle/worker.py b/tasks/agentescape-25-skeleton-1c0ee18d/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-25-skeleton-1c0ee18d/environment/puzzle/worker.py @@ -0,0 +1,73 @@ +"""Stateless Python tool worker. Never receives a scenario or reference values.""" + +import json +import os +import signal +import subprocess +import sys +import tempfile +import threading + +from fastapi import FastAPI +from pydantic import BaseModel, ConfigDict + +app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) +lock = threading.Lock() + + +class Execution(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + code: str + + +@app.get("/health") +def health(): + return {"ok": True} + + +@app.post("/execute") +def execute(request: Execution): + if len(request.code.encode()) > 65536: + return {"stdout": "Error: code exceeds 64 KiB limit"} + with lock, tempfile.TemporaryDirectory(prefix="escape-code-") as directory: + os.chown(directory, 65534, 65534) + with tempfile.TemporaryFile() as output: + process = subprocess.Popen( + [sys.executable, "-I", "/app/child.py"], + stdin=subprocess.PIPE, + stdout=output, + stderr=subprocess.DEVNULL, + cwd=directory, + user=65534, + group=65534, + extra_groups=[], + start_new_session=True, + env={"PATH": "/usr/local/bin:/usr/bin:/bin"}, + ) + try: + process.communicate( + json.dumps({"code": request.code}).encode(), timeout=5 + ) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + return {"stdout": "Error: Python execution timed out"} + finally: + # Also remove children still in the process group after normal exit. + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + output.seek(0) + value = output.read(65537) + if len(value) > 65536 or process.returncode != 0: + return { + "stdout": "Error: Python execution exceeded a resource limit or failed" + } + try: + result = json.loads(value) + if not isinstance(result.get("stdout"), str): + raise ValueError("Invalid worker response") + return result + except (ValueError, AttributeError): + return {"stdout": "Error: Python execution returned invalid output"} diff --git a/tasks/agentescape-25-skeleton-1c0ee18d/instruction.md b/tasks/agentescape-25-skeleton-1c0ee18d/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-25-skeleton-1c0ee18d/instruction.md @@ -0,0 +1,18 @@ +# Escape the room + +Discover the victory string and submit it with `escape submit-answer`. +Start with `escape observe`. This returns the room, available information, visible entities, and victory node ID. + +Use these commands (JSON responses): + +```sh +escape investigate NODE_ID +escape tool-call NODE_ID --arguments-json '{"parameter": "value"}' +escape use-item NODE_ID --arguments-json '{"parameter": "value"}' +escape submit-answer 'exact victory string' +escape state +``` + +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. + +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. diff --git a/tasks/agentescape-25-skeleton-1c0ee18d/solution/oracle.py b/tasks/agentescape-25-skeleton-1c0ee18d/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-25-skeleton-1c0ee18d/solution/oracle.py @@ -0,0 +1,133 @@ +"""Reference solver: use trusted inputs, but obtain the answer through public actions.""" + +import json +import urllib.request +from pathlib import Path + + +def http_action(base_url, payload): + request = urllib.request.Request( + base_url + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(request, timeout=30) as response: + return json.load(response) + + +def solve(scenario, act, observe): + nodes = {node["id"]: node for node in scenario["nodes"]} + visible = {entity["id"] for entity in observe["available_entities"]} + solved = set() + seen_outputs = {} + action_count = 0 + + def call(payload): + nonlocal action_count + action_count += 1 + response = act(payload) + visible.update(entity["id"] for entity in response.get("newly_revealed", [])) + if ( + response.get("episode", {}).get("termination_reason") + == "infrastructure_error" + ): + raise RuntimeError("Infrastructure failure") + return response + + for _round in range(len(nodes) + 2): + progress = False + for node_id, node in nodes.items(): + if node_id not in visible or node_id in solved: + continue + # Preserve graph order for data inputs; trigger/drop edges express visibility. + predecessors = [ + edge["source_id"] + for edge in scenario["edges"] + if edge["target_id"] == node_id + and edge["connection_type"] not in ("Item", "Hidden_Item") + ] + if any(pred not in solved for pred in predecessors): + continue + info = call({"action": "investigate", "node_id": node_id}) + if not info.get("ok"): + raise RuntimeError(f"Investigation failed: {node_id}: {info}") + inputs = { + port["name"]: port["value"] + for port in node.get("inputs", []) + if "value" in port + } + if node["type"] == "Tool": + result = call( + {"action": "tool_call", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok") or result.get("output_values", {}).get("error"): + raise RuntimeError(f"Tool failed: {node_id}: {result}") + output = result.get("output_values", {}) + if node.get("template_id") in ("terminal_1", "terminal_2"): + slots = { + port["name"]: inputs[port["name"]] + for port in node["inputs"] + if port["type"] not in ("Item", "Hidden_Item") + and port["name"] in inputs + } + triggers = { + key: value for key, value in inputs.items() if key not in slots + } + for key, value in slots.items(): + partial = call( + { + "action": "tool_call", + "node_id": node_id, + "arguments": {**triggers, key: value}, + } + ) + if partial.get("ok"): + output.update(partial.get("output_values", {})) + # HIDDEN_ITEM tool drops only occur on subsequent investigation. + call({"action": "investigate", "node_id": node_id}) + elif info.get("required_inputs"): + result = call( + {"action": "use_item", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok"): + raise RuntimeError(f"Item failed: {node_id}: {result}") + output = result.get("content") + else: + output = info.get("content") + seen_outputs[node_id] = output + solved.add(node_id) + progress = True + win_id = scenario["metadata"]["win_node_id"] + if win_id in solved and (len(solved) == len(nodes) or not progress): + outputs = seen_outputs[win_id] + if not outputs: + raise RuntimeError(f"Victory node returned no output: {win_id}") + # Upstream grades its first stored output port, independent of response order. + victory_port = next( + port["name"] for port in nodes[win_id]["outputs"] if "value" in port + ) + answer = outputs[victory_port] if isinstance(outputs, dict) else outputs + result = call({"action": "submit_answer", "answer": answer}) + if not result.get("is_win"): + raise RuntimeError(f"Victory submission failed: {result}") + return {"won": True, "actions": action_count, "visited_nodes": len(solved)} + if not progress: + raise RuntimeError(f"No progress: visible={visible}, solved={solved}") + raise RuntimeError("Reference solver exceeded graph traversal limit") + + +if __name__ == "__main__": + import os + + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000") + with urllib.request.urlopen(base + "/observation", timeout=20) as response: + observation = json.load(response) + print( + json.dumps( + solve( + json.loads(Path("/solution/scenario.json").read_text()), + lambda payload: http_action(base, payload), + observation, + ) + ) + ) diff --git a/tasks/agentescape-25-skeleton-1c0ee18d/solution/scenario.json b/tasks/agentescape-25-skeleton-1c0ee18d/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..76f702dbe5c80e52b783bd1fac27913acc9bdc7a --- /dev/null +++ b/tasks/agentescape-25-skeleton-1c0ee18d/solution/scenario.json @@ -0,0 +1,1357 @@ +{ + "metadata": { + "total_nodes": 25, + "total_edges": 29, + "win_node_id": "item_3", + "win_condition": { + "type": "item_content", + "node_id": "item_3", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_3", + "terminal_2", + "matter_synthesizer", + "terminal_1", + "graph_shortest_path", + "graph_shortest_path_0864", + "zip_unzip_file", + "hex_decode", + "item_12", + "unicode_norm", + "item_9", + "time_convert" + ], + "by_node": { + "item_3": { + "node_name": "", + "node_type": "Item", + "template_id": "item_3", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Hex_String", + "description": "The hex code" + } + } + }, + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": {}, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + } + } + }, + "matter_synthesizer": { + "node_name": "Matter Synthesizer", + "node_type": "Tool", + "template_id": "matter_synthesizer", + "init_inputs": { + "blueprint": { + "type": "Text_Generic", + "description": "Object Blueprint" + } + }, + "init_outputs": {} + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": {}, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + } + } + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": {}, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "graph_shortest_path_0864": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": {}, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + }, + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "hex_decode": { + "node_name": "Hex to Text Decoder", + "node_type": "Tool", + "template_id": "hex_decode", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex string" + } + }, + "init_outputs": {} + }, + "item_12": { + "node_name": "", + "node_type": "Item", + "template_id": "item_12", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Hex_String", + "description": "The hex code" + } + } + }, + "unicode_norm": { + "node_name": "Unicode Normalizer", + "node_type": "Tool", + "template_id": "unicode_norm", + "init_inputs": { + "form": { + "type": "Text_Generic", + "description": "Form" + } + }, + "init_outputs": {} + }, + "item_9": { + "node_name": "", + "node_type": "Item", + "template_id": "item_9", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "File_Id", + "description": "JSON file path" + } + } + }, + "time_convert": { + "node_name": "Timezone Converter", + "node_type": "Tool", + "template_id": "time_convert", + "init_inputs": { + "iso": { + "type": "Text_Generic", + "description": "ISO Timestamp" + }, + "from_tz": { + "type": "Text_Generic", + "description": "From Timezone" + }, + "to_tz": { + "type": "Text_Generic", + "description": "To Timezone" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "item_3": { + "init_inputs": {}, + "init_outputs": { + "content": "4a8c9b2f1d3e5a7b6c8d0e1f2a3b4c5d" + } + }, + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Computation successfully finished for terminal 2.", + "hex_result": "f1e2d3c4b5a69788796a5b4c3d2e1f0a" + } + }, + "matter_synthesizer": { + "init_inputs": { + "blueprint": "Model schema for the requested physical object synthesis." + }, + "init_outputs": {} + }, + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "Terminal 1 diagnostic sequence completed without errors.", + "hex_output": "112233445566778899aabbccddeeff00" + } + }, + "graph_shortest_path": { + "init_inputs": {}, + "init_outputs": { + "path": "[\"Node_A\", \"Node_G\", \"Node_K\", \"Node_M\", \"Node_Z\"]", + "cost": "482915" + } + }, + "graph_shortest_path_0864": { + "init_inputs": {}, + "init_outputs": { + "path": "[\"Station_1\", \"Station_4\", \"Station_9\", \"Station_12\", \"Station_99\"]", + "cost": "739218" + } + }, + "zip_unzip_file": { + "init_inputs": { + "zip_id": "archive_backup_2023.zip", + "password": "SecurePassword123!" + }, + "init_outputs": { + "files": "extracted_data_contents.folder" + } + }, + "hex_decode": { + "init_inputs": { + "hex": "68656c6c6f20776f726c642074657374" + }, + "init_outputs": {} + }, + "item_12": { + "init_inputs": {}, + "init_outputs": { + "content": "9876543210abcdef0123456789abcdef" + } + }, + "unicode_norm": { + "init_inputs": { + "form": "NFC" + }, + "init_outputs": {} + }, + "item_9": { + "init_inputs": {}, + "init_outputs": { + "content": "network_topology_map.json" + } + }, + "time_convert": { + "init_inputs": { + "iso": "2023-10-27T14:32:00Z", + "from_tz": "UTC", + "to_tz": "America/New_York" + }, + "init_outputs": {} + } + }, + "intro_narrative": "Welcome aboard the Aetherius, a marvel of clockwork and steam engineering that now drifts aimlessly through the smog-choked skies. The crew has vanished without a trace, leaving behind only the rhythmic ticking of cooling brass machinery and the ominous hiss of leaking steam pipes. The ship's altitude is dropping rapidly, and unless you can restart the primary boiler systems, it will crash into the jagged iron spires of the city below. Your ultimate goal is to retrieve the legendary Master Core, the mysterious heart of the ship's power grid, locked away securely in the deepest sector of the engine room. To survive, you must navigate a complex web of interconnected mechanical consoles, decipher ancient navigation logs, and reroute steam pressure through a series of logical validators. Every gear, dial, and lever on this ship is connected in a delicate chain of mechanical operations. Pay close attention to the flow of information between the devices. The clock is ticking, the atmospheric pressure is rising, and the Aetherius depends entirely on your intellect to fly once more.", + "narrative_style": "steampunk" + }, + "nodes": [ + { + "id": "item_3", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_3", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hex_String", + "description": "The hex code", + "value": "4a8c9b2f1d3e5a7b6c8d0e1f2a3b4c5d" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "4a8c9b2f1d3e5a7b6c8d0e1f2a3b4c5d" + } + }, + "narrative": "A gleaming Master Core resting securely on a velvet cushion." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A tarnished Brass Gear with intricate, sharp teeth." + }, + { + "id": "item_8_cb82", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A heavy Copper Gear covered in thick black soot." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A cracked Chronometer Dial with faded brass numbers." + }, + { + "id": "terminal_2", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this terminal" + }, + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": 1212590294 + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "482915" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Computation successfully finished for terminal 2." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "f1e2d3c4b5a69788796a5b4c3d2e1f0a" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "Computation successfully finished for terminal 2.", + "hex_result": "f1e2d3c4b5a69788796a5b4c3d2e1f0a" + } + }, + "narrative": "The Main Engine Control system. It requires inputs from the Integrity Analyzer and the Main Route Plotter." + }, + { + "id": "item_8_5790", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A perfectly polished Steel Gear shining in the dim light." + }, + { + "id": "checksum_crc32", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "b884b1d54f0053df34e834822a89b13c52b6cd570c4af0f30e600b7e68322403" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "4846a8d6" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 1212590294 + } + ], + "narrative": "A brass Integrity Analyzer. It requires input from the Security Validator to check the structural data." + }, + { + "id": "hmac_sha256", + "name": "HMAC-SHA256 Calculator", + "description": "HMAC-SHA256(text) with hex key.", + "type": "Tool", + "template_id": "hmac_sha256", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex_key", + "type": "Hex_String", + "description": "Hex key", + "value": "789c05c1810d80300804c0557e0213777181867e94a4850a34aeefddc5986a6de044d7769b67a920f96e9a10e2730d163b3eadc77781111e79fc56881548" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text message", + "value": "Terminal 1 diagnostic sequence completed without errors." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "HMAC Hex digest", + "value": "b884b1d54f0053df34e834822a89b13c52b6cd570c4af0f30e600b7e68322403" + } + ], + "narrative": "A robust Security Validator. It requires inputs from the Navigation Console and the Steam Compressor to function." + }, + { + "id": "item_16_db24", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by", + "value": "synthesized_item_a506c04e27411d8f" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A faintly glowing Aether Dial humming with energy." + }, + { + "id": "matter_synthesizer", + "name": "Matter Synthesizer", + "description": "Synthesizes physical objects from data blueprints.", + "type": "Tool", + "template_id": "matter_synthesizer", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "blueprint", + "type": "Text_Generic", + "description": "Object Blueprint", + "value": "Model schema for the requested physical object synthesis." + } + ], + "outputs": [ + { + "name": "output_slot", + "type": "Item", + "description": "Synthesized Object", + "value": "synthesized_item_a506c04e27411d8f" + } + ], + "init": { + "inputs": { + "blueprint": "Model schema for the requested physical object synthesis." + }, + "outputs": {} + }, + "narrative": "A large mechanical Matter Fabricator machine covered in pipes." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "false" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "739218" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Terminal 1 diagnostic sequence completed without errors." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "112233445566778899aabbccddeeff00" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "Terminal 1 diagnostic sequence completed without errors.", + "hex_output": "112233445566778899aabbccddeeff00" + } + }, + "narrative": "The ship's Navigation Console. It requires inputs from both the Validity Checker and the Backup Route Plotter." + }, + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "network_topology_map.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "false" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "[\"Station_1\", \"Station_4\", \"Station_9\", \"Station_12\", \"Station_99\"]" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Node_A\", \"Node_G\", \"Node_K\", \"Node_M\", \"Node_Z\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "482915" + } + ], + "init": { + "inputs": {}, + "outputs": { + "path": "[\"Node_A\", \"Node_G\", \"Node_K\", \"Node_M\", \"Node_Z\"]", + "cost": "482915" + } + }, + "narrative": "The Main Route Plotter. It requires inputs from the Validity Checker, the Backup Route Plotter, and the Map Scroll." + }, + { + "id": "luhn_check", + "name": "Luhn Checker", + "description": "Luhn validity of number string.", + "type": "Tool", + "template_id": "luhn_check", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "number", + "type": "Text_Generic", + "description": "Number string", + "value": "2023-10-27T10:32:00-04:00" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "false" + } + ], + "narrative": "A gear-driven Validity Checker. It requires input from the Character Aligner to process its validation." + }, + { + "id": "item_16_cecc", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A small hissing Steam Dial continuously leaking hot vapor." + }, + { + "id": "graph_shortest_path_0864", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "extracted_data_contents.folder" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "false" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "hello world test" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Station_1\", \"Station_4\", \"Station_9\", \"Station_12\", \"Station_99\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "739218" + } + ], + "init": { + "inputs": {}, + "outputs": { + "path": "[\"Station_1\", \"Station_4\", \"Station_9\", \"Station_12\", \"Station_99\"]", + "cost": "739218" + } + }, + "narrative": "A Backup Route Plotter. It requires inputs from the Validity Checker, the Pressure Archive, and the Cipher Translator." + }, + { + "id": "item_8_bd51", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A heavily rusted Iron Gear salvaged from an old broken machine." + }, + { + "id": "container_2", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Hex_String", + "description": "Fingerprint Hash", + "value": "9876543210abcdef0123456789abcdef" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "A mechanical Locked Lockbox. It requires input from the Punched Card to unlock its heavy latch." + }, + { + "id": "zlib_deflate", + "name": "Zlib Deflate", + "description": "Deflate text to zlib bytes (hex).", + "type": "Tool", + "template_id": "zlib_deflate", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text to compress", + "value": "Terminal 1 diagnostic sequence completed without errors." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Compressed hex", + "value": "789c05c1810d80300804c0557e0213777181867e94a4850a34aeefddc5986a6de044d7769b67a920f96e9a10e2730d163b3eadc77781111e79fc56881548" + } + ], + "narrative": "A heavy Steam Compressor. It requires input from the Navigation Console to begin its compression cycle." + }, + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "archive_backup_2023.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "SecurePassword123!" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_data_contents.folder" + } + ], + "init": { + "inputs": { + "zip_id": "archive_backup_2023.zip", + "password": "SecurePassword123!" + }, + "outputs": { + "files": "extracted_data_contents.folder" + } + }, + "narrative": "A sealed Pressure Archive made of reinforced steel." + }, + { + "id": "item_8_ed04", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A shiny Golden Gear that feels surprisingly heavy." + }, + { + "id": "hex_decode", + "name": "Hex to Text Decoder", + "description": "Decode hex to UTF-8 text.", + "type": "Tool", + "template_id": "hex_decode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex string", + "value": "68656c6c6f20776f726c642074657374" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decoded text", + "value": "hello world test" + } + ], + "init": { + "inputs": { + "hex": "68656c6c6f20776f726c642074657374" + }, + "outputs": {} + }, + "narrative": "A complex brass Cipher Translator device resting on a desk." + }, + { + "id": "item_12", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_12", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hex_String", + "description": "The hex code", + "value": "9876543210abcdef0123456789abcdef" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "9876543210abcdef0123456789abcdef" + } + }, + "narrative": "A delicate perforated Punched Card containing vital data." + }, + { + "id": "unicode_norm", + "name": "Unicode Normalizer", + "description": "Unicode normalize (NFC/NFD/NFKC/NFKD).", + "type": "Tool", + "template_id": "unicode_norm", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "2023-10-27T10:32:00-04:00" + }, + { + "name": "form", + "type": "Text_Generic", + "description": "Form", + "value": "NFC" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Normalized text", + "value": "2023-10-27T10:32:00-04:00" + } + ], + "init": { + "inputs": { + "form": "NFC" + }, + "outputs": {} + }, + "narrative": "A complex Character Aligner. It requires input from the Temporal Calibrator to align its gears." + }, + { + "id": "item_9", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_9", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "File_Id", + "description": "JSON file path", + "value": "network_topology_map.json" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "network_topology_map.json" + } + }, + "narrative": "An old parchment Map Scroll tied with a leather string." + }, + { + "id": "time_convert", + "name": "Timezone Converter", + "description": "Convert ISO time between timezones.", + "type": "Tool", + "template_id": "time_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "iso", + "type": "Text_Generic", + "description": "ISO Timestamp", + "value": "2023-10-27T14:32:00Z" + }, + { + "name": "from_tz", + "type": "Text_Generic", + "description": "From Timezone", + "value": "UTC" + }, + { + "name": "to_tz", + "type": "Text_Generic", + "description": "To Timezone", + "value": "America/New_York" + } + ], + "outputs": [ + { + "name": "iso", + "type": "Text_Generic", + "description": "Converted ISO Timestamp", + "value": "2023-10-27T10:32:00-04:00" + } + ], + "init": { + "inputs": { + "iso": "2023-10-27T14:32:00Z", + "from_tz": "UTC", + "to_tz": "America/New_York" + }, + "outputs": {} + }, + "narrative": "A ticking Temporal Calibrator used for time adjustments." + } + ], + "edges": [ + { + "source_id": "item_8", + "target_id": "item_3", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "item_8_cb82", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_16", + "target_id": "item_8_cb82", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "terminal_2", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "source_tool" + }, + { + "source_id": "item_8_5790", + "target_id": "terminal_2", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "checksum_crc32", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "num1" + }, + { + "source_id": "hmac_sha256", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "item_16_db24", + "target_id": "checksum_crc32", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "matter_synthesizer", + "target_id": "item_16_db24", + "connection_type": "Item", + "source_port": "output_slot", + "target_port": "source_tool" + }, + { + "source_id": "terminal_1", + "target_id": "hmac_sha256", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "text" + }, + { + "source_id": "graph_shortest_path", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "num2" + }, + { + "source_id": "luhn_check", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "slot_a" + }, + { + "source_id": "item_16_cecc", + "target_id": "luhn_check", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "graph_shortest_path_0864", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "slot_b" + }, + { + "source_id": "item_8_bd51", + "target_id": "item_8_5790", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "luhn_check", + "target_id": "graph_shortest_path_0864", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "src" + }, + { + "source_id": "container_2", + "target_id": "graph_shortest_path_0864", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "zlib_deflate", + "target_id": "hmac_sha256", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_key" + }, + { + "source_id": "terminal_1", + "target_id": "zlib_deflate", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "text" + }, + { + "source_id": "luhn_check", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "src" + }, + { + "source_id": "graph_shortest_path_0864", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "dst" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path_0864", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "terminal_1", + "target_id": "zlib_deflate", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "trigger_item" + }, + { + "source_id": "item_8_ed04", + "target_id": "zip_unzip_file", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "hex_decode", + "target_id": "graph_shortest_path_0864", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "dst" + }, + { + "source_id": "item_12", + "target_id": "container_2", + "connection_type": "Hex_String", + "source_port": "content", + "target_port": "fingerprint_input" + }, + { + "source_id": "unicode_norm", + "target_id": "luhn_check", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "number" + }, + { + "source_id": "item_9", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "content", + "target_port": "file_id" + }, + { + "source_id": "time_convert", + "target_id": "unicode_norm", + "connection_type": "Text_Generic", + "source_port": "iso", + "target_port": "text" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-1c0ee18d/solution/solve.sh b/tasks/agentescape-25-skeleton-1c0ee18d/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-25-skeleton-1c0ee18d/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-25-skeleton-1c0ee18d/task.toml b/tasks/agentescape-25-skeleton-1c0ee18d/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c64ce94572d0bb8402fa24bf1cd4ee04dbcf510d --- /dev/null +++ b/tasks/agentescape-25-skeleton-1c0ee18d/task.toml @@ -0,0 +1,38 @@ +schema_version = "1.4" +source = "https://github.com/AGI-Eval-Official/Repo-of-AgentEscapeBench" + +[[artifacts]] +source = "/evidence/final.json" +service = "puzzle" + +[[artifacts]] +source = "/evidence/trace.jsonl" +service = "puzzle" + +[task] +name = "edbeeching/agentescape-25-skeleton-1c0ee18d" +version = "0.1.0" + +[metadata] +difficulty = 25 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "b97e516dc7204a496f39cb161772995655a4851294fefea771ee47321a6984a9" +protocol = "harbor-cli-action-budget-v1" +max_actions = 500 + +[agent] +timeout_sec = 1200 + +[environment] +build_timeout_sec = 900 +cpus = 1 +memory_mb = 1024 + +[verifier] +environment_mode = "separate" +timeout_sec = 60 + +[[verifier.collect]] +service = "puzzle" +command = "python -I /app/export.py" +timeout_sec = 15 diff --git a/tasks/agentescape-25-skeleton-1c0ee18d/tests/Dockerfile b/tasks/agentescape-25-skeleton-1c0ee18d/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-25-skeleton-1c0ee18d/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-25-skeleton-1c0ee18d/tests/expected.json b/tasks/agentescape-25-skeleton-1c0ee18d/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..f435f5d26c9982c103947ce6f0b4a8a9cb65e4fb --- /dev/null +++ b/tasks/agentescape-25-skeleton-1c0ee18d/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "b97e516dc7204a496f39cb161772995655a4851294fefea771ee47321a6984a9", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-1c0ee18d/tests/grade.py b/tasks/agentescape-25-skeleton-1c0ee18d/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-25-skeleton-1c0ee18d/tests/grade.py @@ -0,0 +1,21 @@ +"""Grade only Harbor-collected sidecar evidence in a fresh verifier container.""" + +import json +from pathlib import Path + +expected = json.loads(Path("/tests/expected.json").read_text()) +state = json.loads(Path("/evidence/final.json").read_text()) +assert state["collected_from_live_service"] is True, "Missing trusted service export" +assert state["scenario_sha256"] == expected["scenario_sha256"], ( + "Wrong scenario evidence" +) +assert state["max_actions"] == expected["max_actions"], "Wrong budget" +assert type(state["won"]) is bool +assert 0 <= state["action_count"] <= state["max_actions"] +assert state["termination_reason"] != "infrastructure_error", ( + "Infrastructure failure is not a puzzle failure" +) +assert not state["won"] or state["termination_reason"] == "success" +Path("/logs/verifier").mkdir(parents=True, exist_ok=True) +Path("/logs/verifier/state.json").write_text(json.dumps(state, indent=2)) +Path("/logs/verifier/reward.txt").write_text("1.0\n" if state["won"] else "0.0\n") diff --git a/tasks/agentescape-25-skeleton-1c0ee18d/tests/test.sh b/tasks/agentescape-25-skeleton-1c0ee18d/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-25-skeleton-1c0ee18d/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-25-skeleton-248c41a5/environment/Dockerfile b/tasks/agentescape-25-skeleton-248c41a5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-25-skeleton-248c41a5/environment/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-25-skeleton-248c41a5/environment/agent/Dockerfile b/tasks/agentescape-25-skeleton-248c41a5/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-25-skeleton-248c41a5/environment/agent/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-25-skeleton-248c41a5/environment/agent/cli.py b/tasks/agentescape-25-skeleton-248c41a5/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-25-skeleton-248c41a5/environment/agent/cli.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Public agent client; depends only on the Python standard library.""" + +import argparse +import json +import os +import sys +import urllib.error +import urllib.request + + +def main(): + parser = argparse.ArgumentParser(description="Interact with the escape room") + parser.add_argument( + "action", + choices=[ + "observe", + "state", + "investigate", + "tool-call", + "use-item", + "submit-answer", + ], + ) + parser.add_argument("value", nargs="?") + parser.add_argument("--arguments-json", default="{}") + args = parser.parse_args() + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000").rstrip("/") + if args.action in ("observe", "state"): + request = urllib.request.Request( + base + ("/observation" if args.action == "observe" else "/state") + ) + else: + if args.value is None: + parser.error("node ID or answer is required") + payload = {"action": args.action.replace("-", "_")} + if args.action == "submit-answer": + payload["answer"] = args.value + else: + payload["node_id"] = args.value + if args.action in ("tool-call", "use-item"): + payload["arguments"] = json.loads(args.arguments_json) + request = urllib.request.Request( + base + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=30) as response: + print(json.dumps(json.load(response), ensure_ascii=False)) + except (urllib.error.URLError, ValueError) as exc: + print(json.dumps({"ok": False, "error": str(exc)})) + sys.exit(2) + + +if __name__ == "__main__": + main() diff --git a/tasks/agentescape-25-skeleton-248c41a5/environment/docker-compose.yaml b/tasks/agentescape-25-skeleton-248c41a5/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d4aa423a68c40c6eaad5d375cf3cc18f278e9da5 --- /dev/null +++ b/tasks/agentescape-25-skeleton-248c41a5/environment/docker-compose.yaml @@ -0,0 +1,50 @@ +services: + main: + image: agentescapebench-agent:aab05a0a9ddb + build: + context: ./agent + networks: [default, puzzle] + security_opt: [no-new-privileges:true] + depends_on: + puzzle: + condition: service_healthy + puzzle: + image: agentescapebench-puzzle:agentescape-25-skeleton-248c41a5-aab05a0a9ddb + build: + context: ./puzzle + networks: [puzzle, execution] + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 512m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"] + interval: 1s + timeout: 3s + retries: 30 + depends_on: + worker: + condition: service_healthy + worker: + image: agentescapebench-worker:aab05a0a9ddb + build: + context: ./puzzle + dockerfile: worker.Dockerfile + networks: [execution] + read_only: true + tmpfs: ["/tmp:size=64m,mode=1777"] + cap_drop: [ALL] + cap_add: [SETUID, SETGID, KILL, CHOWN, DAC_OVERRIDE] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 384m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8001/health')"] + interval: 1s + timeout: 3s + retries: 30 +networks: + puzzle: + internal: true + execution: + internal: true diff --git a/tasks/agentescape-25-skeleton-248c41a5/environment/puzzle/Dockerfile b/tasks/agentescape-25-skeleton-248c41a5/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-25-skeleton-248c41a5/environment/puzzle/Dockerfile @@ -0,0 +1,9 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY upstream /app/upstream +COPY service.py export.py /app/ +COPY scenario.json /private/scenario.json +ENV SCENARIO_PATH=/private/scenario.json EVIDENCE_DIR=/evidence WORKER_URL=http://worker:8001 MAX_ACTIONS=500 +CMD ["uvicorn", "service:create_app", "--factory", "--host", "0.0.0.0", "--port", "8000", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-25-skeleton-248c41a5/environment/puzzle/child.py b/tasks/agentescape-25-skeleton-248c41a5/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-25-skeleton-248c41a5/environment/puzzle/child.py @@ -0,0 +1,59 @@ +"""Run the original Python tool after reducing privileges and blocking networking.""" + +import ctypes +import errno +import json +import resource +import sys + +resource.setrlimit(resource.RLIMIT_CPU, (3, 3)) +resource.setrlimit(resource.RLIMIT_AS, (256 * 1024 * 1024, 256 * 1024 * 1024)) +resource.setrlimit(resource.RLIMIT_FSIZE, (65536, 65536)) +resource.setrlimit(resource.RLIMIT_NOFILE, (32, 32)) +resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + +# Filters survive fork/exec. Fail closed if seccomp cannot be loaded. +lib = ctypes.CDLL("libseccomp.so.2", use_errno=True) +lib.seccomp_init.argtypes = [ctypes.c_uint32] +lib.seccomp_init.restype = ctypes.c_void_p +lib.seccomp_rule_add.argtypes = [ + ctypes.c_void_p, + ctypes.c_uint32, + ctypes.c_int, + ctypes.c_uint, +] +lib.seccomp_syscall_resolve_name.argtypes = [ctypes.c_char_p] +lib.seccomp_load.argtypes = [ctypes.c_void_p] +lib.seccomp_release.argtypes = [ctypes.c_void_p] +ctx = lib.seccomp_init(0x7FFF0000) # SCMP_ACT_ALLOW +if not ctx: + raise RuntimeError("Cannot initialize execution isolation") +try: + for name in ( + "socket", + "socketpair", + "connect", + "ptrace", + "process_vm_readv", + "process_vm_writev", + "mount", + "unshare", + "setns", + "bpf", + ): + number = lib.seccomp_syscall_resolve_name(name.encode()) + if ( + number >= 0 + and lib.seccomp_rule_add(ctx, 0x00050000 | errno.EPERM, number, 0) != 0 + ): + raise RuntimeError("Cannot install execution isolation rule") + if lib.seccomp_load(ctx) != 0: + raise RuntimeError("Cannot activate execution isolation") +finally: + lib.seccomp_release(ctx) + +sys.path.insert(0, "/app") +from simulator import ToolSimulator # noqa: E402 + +request = json.load(sys.stdin) +json.dump(ToolSimulator().code_py_exec(request), sys.stdout) diff --git a/tasks/agentescape-25-skeleton-248c41a5/environment/puzzle/export.py b/tasks/agentescape-25-skeleton-248c41a5/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-25-skeleton-248c41a5/environment/puzzle/export.py @@ -0,0 +1,13 @@ +"""Harbor invokes this inside the puzzle service after stopping the agent.""" + +import json +import pathlib +import urllib.request + +with urllib.request.urlopen("http://127.0.0.1:8000/state", timeout=10) as response: + state = json.load(response) +state["collected_from_live_service"] = True +target = pathlib.Path("/evidence/final.json") +temp = target.with_suffix(".tmp") +temp.write_text(json.dumps(state)) +temp.replace(target) diff --git a/tasks/agentescape-25-skeleton-248c41a5/environment/puzzle/requirements.txt b/tasks/agentescape-25-skeleton-248c41a5/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-25-skeleton-248c41a5/environment/puzzle/requirements.txt @@ -0,0 +1,57 @@ +annotated-doc==0.0.5 + # via fastapi +annotated-types==0.8.0 + # via pydantic +anyio==4.16.0 + # via starlette +certifi==2026.10.23 + # via requests +cffi==2.1.1 ; platform_python_implementation != 'PyPy' + # via cryptography +charset-normalizer==3.5.2 + # via requests +click==8.5.0 + # via uvicorn +cryptography==50.0.2 + # via agentescapebench-harbor +fastapi==0.162.0 + # via agentescapebench-harbor +h11==0.16.0 + # via uvicorn +idna==3.20 + # via + # anyio + # requests +opentelemetry-api==1.45.2 + # via fastapi +pycparser==3.12 ; implementation_name != 'PyPy' and platform_python_implementation != 'PyPy' + # via cffi +pydantic==2.14.2 + # via + # agentescapebench-harbor + # fastapi +pydantic-core==2.50.2 + # via pydantic +pytz==2025.2 + # via agentescapebench-harbor +requests==2.34.2 + # via agentescapebench-harbor +starlette==1.10.0 + # via fastapi +typing-extensions==4.16.0 + # via + # anyio + # fastapi + # opentelemetry-api + # pydantic + # pydantic-core + # starlette + # typing-inspection +typing-inspection==0.4.4 + # via + # fastapi + # pydantic +urllib3==2.8.0 + # via requests +uvicorn==0.54.0 + # via agentescapebench-harbor diff --git a/tasks/agentescape-25-skeleton-248c41a5/environment/puzzle/scenario.json b/tasks/agentescape-25-skeleton-248c41a5/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..9a8c02c3c9539e8d7715f27f4bb70767824c4133 --- /dev/null +++ b/tasks/agentescape-25-skeleton-248c41a5/environment/puzzle/scenario.json @@ -0,0 +1,1487 @@ +{ + "metadata": { + "total_nodes": 25, + "total_edges": 32, + "win_node_id": "matter_synthesizer", + "win_condition": { + "type": "tool_output", + "node_id": "matter_synthesizer", + "output_port": "output_slot", + "output_type": "Item", + "description": "Execute Matter Synthesizer and get the output from port 'output_slot'" + }, + "source_init": { + "source_nodes": [ + "matter_synthesizer", + "terminal_2", + "num_base_convert", + "calc_gcd_1d8d", + "json_get", + "zip_unzip_file", + "csv_query", + "calc_inv_mod_14bc", + "calc_inv_mod_cd7c", + "hmac_sha256", + "terminal_2_d08a", + "checksum_crc32", + "zip_unzip_item" + ], + "by_node": { + "matter_synthesizer": { + "node_name": "Matter Synthesizer", + "node_type": "Tool", + "template_id": "matter_synthesizer", + "init_inputs": {}, + "init_outputs": { + "output_slot": { + "type": "Item", + "description": "Synthesized Object" + } + } + }, + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": {}, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + }, + "math_token": { + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + } + }, + "num_base_convert": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "s": { + "type": "Big_Int", + "description": "Input integer value" + }, + "from_base": { + "type": "Big_Int", + "description": "From base" + } + }, + "init_outputs": {} + }, + "calc_gcd_1d8d": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First integer" + }, + "b": { + "type": "Big_Int", + "description": "Second integer" + } + }, + "init_outputs": {} + }, + "json_get": { + "node_name": "JSON Getter", + "node_type": "Tool", + "template_id": "json_get", + "init_inputs": {}, + "init_outputs": { + "values": { + "type": "Text_Generic", + "description": "Extracted values" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "csv_query": { + "node_name": "CSV Query", + "node_type": "Tool", + "template_id": "csv_query", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "CSV file ID" + }, + "where": { + "type": "Text_Generic", + "description": "Where clause" + } + }, + "init_outputs": { + "rows": { + "type": "Text_Generic", + "description": "Result rows" + } + } + }, + "calc_inv_mod_14bc": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "Integer a" + } + }, + "init_outputs": {} + }, + "calc_inv_mod_cd7c": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "Integer a" + }, + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "hmac_sha256": { + "node_name": "HMAC-SHA256 Calculator", + "node_type": "Tool", + "template_id": "hmac_sha256", + "init_inputs": { + "hex_key": { + "type": "Hex_String", + "description": "Hex key" + }, + "text": { + "type": "Text_Generic", + "description": "Text message" + } + }, + "init_outputs": {} + }, + "terminal_2_d08a": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": { + "num1": { + "type": "Big_Int", + "description": "First Number" + }, + "num2": { + "type": "Big_Int", + "description": "Second Number" + } + }, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + } + } + }, + "checksum_crc32": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + }, + "zip_unzip_item": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_item", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + }, + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "matter_synthesizer": { + "init_inputs": {}, + "init_outputs": { + "output_slot": "A completely useless chunk of synthetic matter" + } + }, + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Partial text terminal computation result", + "hex_result": "1a2b3c4d5e6f7a8b9c0d1e2f", + "math_token": "Obsolete math token worth nothing" + } + }, + "num_base_convert": { + "init_inputs": { + "s": "9842793847293847293847", + "from_base": "16" + }, + "init_outputs": {} + }, + "calc_gcd_1d8d": { + "init_inputs": { + "a": "1029384756102938475610", + "b": "5847392019384756283948" + }, + "init_outputs": {} + }, + "json_get": { + "init_inputs": {}, + "init_outputs": { + "values": "[\"element_1\", \"element_2\", \"element_3\", \"element_4\"]" + } + }, + "zip_unzip_file": { + "init_inputs": { + "zip_id": "archive_data_77.zip" + }, + "init_outputs": { + "files": "extracted_data_77.json" + } + }, + "csv_query": { + "init_inputs": { + "file_id": "database_dump_82.csv", + "where": "id > 1000 AND status = 'active'" + }, + "init_outputs": { + "rows": "[{\"id\": 1001, \"status\": \"active\"}, {\"id\": 1005, \"status\": \"active\"}, {\"id\": 1009, \"status\": \"active\"}]" + } + }, + "calc_inv_mod_14bc": { + "init_inputs": { + "a": "2837465910283746591028" + }, + "init_outputs": {} + }, + "calc_inv_mod_cd7c": { + "init_inputs": { + "a": "1928374655910293847566", + "mod": "888887" + }, + "init_outputs": {} + }, + "hmac_sha256": { + "init_inputs": { + "hex_key": "deadbeef12345678deadbeef12345678", + "text": "Message to be authenticated by HMAC" + }, + "init_outputs": {} + }, + "terminal_2_d08a": { + "init_inputs": { + "num1": "4738291047382910473829", + "num2": "9988776655443322110099" + }, + "init_outputs": { + "text_result": "Alternative terminal text output produced", + "hex_result": "aabbccddeeff001122334455" + } + }, + "checksum_crc32": { + "init_inputs": { + "hex": "11223344556677889900aabbccddeeff" + }, + "init_outputs": {} + }, + "zip_unzip_item": { + "init_inputs": { + "zip_id": "secret_item_stash.zip", + "password": "Sup3rS3cr3tP4ssw0rd!" + }, + "init_outputs": {} + } + }, + "intro_narrative": "The world ended decades ago, swallowed by nuclear fire and toxic ash. You are a Scrapper, surviving in the crumbling ruins of Sector 7. Disaster has struck your outpost: the central water filtration system has completely failed, and a deadly, suffocating rad-storm is approaching fast. Your settlement's only hope lies deep underground in an abandoned military bunker, rumored to house a legendary artifact known as the Creation Forge—an old-world matter synthesizer capable of fabricating any part from raw data blueprints. The bunker is a graveyard of dead systems, rusted terminals, and fragmented code left behind by the old military. To activate the Forge, you must restart the facility's decaying network, re-route power through forgotten nodes, and bypass heavy biometric security. The storm is howling on the surface, and time is running out. Reactivate the systems, synthesize the replacement part, and save your people before the ash claims you all.", + "narrative_style": "post_apocalyptic" + }, + "nodes": [ + { + "id": "matter_synthesizer", + "name": "Matter Synthesizer", + "description": "Synthesizes physical objects from data blueprints.", + "type": "Tool", + "template_id": "matter_synthesizer", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "blueprint", + "type": "Text_Generic", + "description": "Object Blueprint", + "value": "Partial text terminal computation result" + } + ], + "outputs": [ + { + "name": "output_slot", + "type": "Item", + "description": "Synthesized Object", + "value": "synthesized_item_7e4296c79a73f78a" + } + ], + "init": { + "inputs": {}, + "outputs": { + "output_slot": "A completely useless chunk of synthetic matter" + } + }, + "narrative": "The Creation Forge. A legendary fabrication machine from before the collapse. It requires input from the Main Synthesis Terminal to shape scrap into salvation." + }, + { + "id": "terminal_2", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "469867" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "0" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Partial text terminal computation result" + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "1a2b3c4d5e6f7a8b9c0d1e2f" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "Obsolete math token worth nothing" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "Partial text terminal computation result", + "hex_result": "1a2b3c4d5e6f7a8b9c0d1e2f", + "math_token": "Obsolete math token worth nothing" + } + }, + "narrative": "The Main Synthesis Terminal. A dust-covered mainframe. It requires inputs from both the Quantum Multiplier Unit and the Phase Inverter Delta." + }, + { + "id": "calc_bigmul", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "4921396923646923646924" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "0" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "0" + } + ], + "narrative": "A Quantum Multiplier Unit. A heavy, sparking processing server. It requires inputs from the Energy Exponential Core and the Phase Inverter Beta." + }, + { + "id": "calc_modexp", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "4921396923646923646924" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": 1090510515 + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "4921396923646923646924" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "0" + } + ], + "narrative": "The Energy Exponential Core. A glowing reactor console. It requires inputs from the Phase Inverter Alpha, the Phase Inverter Beta, and the Integrity Scanner." + }, + { + "id": "calc_inv_mod", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "2" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "9842793847293847293847" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "4921396923646923646924" + } + ], + "narrative": "Phase Inverter Alpha. A makeshift reverse-engineering rig. It requires inputs from the Signal Harmonizer and the Data Base Translator." + }, + { + "id": "container_4", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_4", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Text_Generic", + "description": "Fingerprint Hash", + "value": "[\"element_1\", \"element_2\", \"element_3\", \"element_4\"]" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "A Sealed Biometric Vault. A heavy titanium lockbox welded shut by previous scavengers. It requires input from the Blueprint Extractor to bypass its security." + }, + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "19685587694587694587694" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "4921396923646923646924" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "2" + } + ], + "narrative": "The Signal Harmonizer. An acoustic resonance chamber. It requires inputs from the Secondary Multiplier Unit and the Phase Inverter Beta." + }, + { + "id": "num_base_convert", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "9842793847293847293847" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "16" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "294339" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "9842793847293847293847" + } + ], + "init": { + "inputs": { + "s": "9842793847293847293847", + "from_base": "16" + }, + "outputs": {} + }, + "narrative": "The Data Base Translator. A salvaged translation node. It requires input from the Phase Inverter Gamma." + }, + { + "id": "calc_bigmul_02cb", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "2" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "9842793847293847293847" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "19685587694587694587694" + } + ], + "narrative": "The Secondary Multiplier Unit. A scavenged processing relay. It requires inputs from the Primary Signal Harmonizer and the Data Base Translator." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A Data Relic. A jagged piece of high-density glass holding ancient code." + }, + { + "id": "calc_inv_mod_e37a", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "2" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "9842793847293847293847" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "4921396923646923646924" + } + ], + "narrative": "Phase Inverter Beta. A pulsating energy grid router. It requires inputs from the Primary Signal Harmonizer and the Data Base Translator." + }, + { + "id": "calc_gcd_1d8d", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "1029384756102938475610" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "5847392019384756283948" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "2" + } + ], + "init": { + "inputs": { + "a": "1029384756102938475610", + "b": "5847392019384756283948" + }, + "outputs": {} + }, + "narrative": "The Primary Signal Harmonizer. A bulky frequency alignment console covered in heavy metal dials." + }, + { + "id": "json_get", + "name": "JSON Getter", + "description": "Extract values by simple JSONPath.", + "type": "Tool", + "template_id": "json_get", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "JSON file ID", + "value": "extracted_data_77.json" + }, + { + "name": "jsonpath", + "type": "Text_Generic", + "description": "JSONPath expression", + "value": "[{\"id\": 1001, \"status\": \"active\"}, {\"id\": 1005, \"status\": \"active\"}, {\"id\": 1009, \"status\": \"active\"}]" + } + ], + "outputs": [ + { + "name": "values", + "type": "Text_Generic", + "description": "Extracted values", + "value": "[\"element_1\", \"element_2\", \"element_3\", \"element_4\"]" + } + ], + "init": { + "inputs": {}, + "outputs": { + "values": "[\"element_1\", \"element_2\", \"element_3\", \"element_4\"]" + } + }, + "narrative": "The Blueprint Extractor. An automated data-mining server. It requires inputs from both the Archive Decryptor and the Records Database." + }, + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "archive_data_77.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Alternative terminal text output produced" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_data_77.json" + } + ], + "init": { + "inputs": { + "zip_id": "archive_data_77.zip" + }, + "outputs": { + "files": "extracted_data_77.json" + } + }, + "narrative": "The Archive Decryptor. A repurposed military codebreaker. It requires input from the Engineering Terminal." + }, + { + "id": "csv_query", + "name": "CSV Query", + "description": "Query CSV: select columns and simple WHERE.", + "type": "Tool", + "template_id": "csv_query", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "CSV file ID", + "value": "database_dump_82.csv" + }, + { + "name": "select", + "type": "Text_Generic", + "description": "Columns to select", + "value": "Alternative terminal text output produced" + }, + { + "name": "where", + "type": "Text_Generic", + "description": "Where clause", + "value": "id > 1000 AND status = 'active'" + } + ], + "outputs": [ + { + "name": "rows", + "type": "Text_Generic", + "description": "Result rows", + "value": "[{\"id\": 1001, \"status\": \"active\"}, {\"id\": 1005, \"status\": \"active\"}, {\"id\": 1009, \"status\": \"active\"}]" + } + ], + "init": { + "inputs": { + "file_id": "database_dump_82.csv", + "where": "id > 1000 AND status = 'active'" + }, + "outputs": { + "rows": "[{\"id\": 1001, \"status\": \"active\"}, {\"id\": 1005, \"status\": \"active\"}, {\"id\": 1009, \"status\": \"active\"}]" + } + }, + "narrative": "The Records Database. A massive tape-drive memory unit. It requires input from the Engineering Terminal." + }, + { + "id": "calc_inv_mod_14bc", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "2837465910283746591028" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "469867" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "294339" + } + ], + "init": { + "inputs": { + "a": "2837465910283746591028" + }, + "outputs": {} + }, + "narrative": "Phase Inverter Gamma. A scorched circuit board with spliced cables. It requires input from the Phase Inverter Delta." + }, + { + "id": "item_8_819e", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A Scrap Metal Relic. A twisted piece of irradiated metal debris." + }, + { + "id": "calc_inv_mod_cd7c", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "1928374655910293847566" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "888887" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "469867" + } + ], + "init": { + "inputs": { + "a": "1928374655910293847566", + "mod": "888887" + }, + "outputs": {} + }, + "narrative": "Phase Inverter Delta. An underground power routing station with dangerously exposed wiring." + }, + { + "id": "container_1", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_1", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + }, + { + "name": "fingerprint_input", + "type": "Hex_String", + "description": "Fingerprint Hash", + "value": "2d327d6b332e7830deaa013a7255513ed593c7fe94cabc7ea4aa750821b4bf64" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "A Secure Supply Cache. An old airdrop crate marked with faded biohazard symbols. It requires input from the Security Authenticator to unlock." + }, + { + "id": "hmac_sha256", + "name": "HMAC-SHA256 Calculator", + "description": "HMAC-SHA256(text) with hex key.", + "type": "Tool", + "template_id": "hmac_sha256", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "hex_key", + "type": "Hex_String", + "description": "Hex key", + "value": "deadbeef12345678deadbeef12345678" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text message", + "value": "Message to be authenticated by HMAC" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "HMAC Hex digest", + "value": "2d327d6b332e7830deaa013a7255513ed593c7fe94cabc7ea4aa750821b4bf64" + } + ], + "init": { + "inputs": { + "hex_key": "deadbeef12345678deadbeef12345678", + "text": "Message to be authenticated by HMAC" + }, + "outputs": {} + }, + "narrative": "The Security Authenticator. A handheld cryptographic lockpick left behind by an old-world spy." + }, + { + "id": "terminal_2_d08a", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "4738291047382910473829" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "9988776655443322110099" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Alternative terminal text output produced" + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "aabbccddeeff001122334455" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": { + "num1": "4738291047382910473829", + "num2": "9988776655443322110099" + }, + "outputs": { + "text_result": "Alternative terminal text output produced", + "hex_result": "aabbccddeeff001122334455" + } + }, + "narrative": "The Engineering Terminal. A rugged survivor laptop with a cracked display and a heavily modified keyboard." + }, + { + "id": "item_8_9fe7", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A Corrupted Core. A melted-down CPU from a destroyed defense drone." + }, + { + "id": "checksum_crc32", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "11223344556677889900aabbccddeeff" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "40ffdeb3" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 1090510515 + } + ], + "init": { + "inputs": { + "hex": "11223344556677889900aabbccddeeff" + }, + "outputs": {} + }, + "narrative": "The Integrity Scanner. A portable, battered error-checking device." + }, + { + "id": "item_8_defb", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A Rusted Data Chip. An oxidized storage drive buried in the ash." + }, + { + "id": "zip_unzip_item", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_item", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "secret_item_stash.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Sup3rS3cr3tP4ssw0rd!" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip" + } + ], + "init": { + "inputs": { + "zip_id": "secret_item_stash.zip", + "password": "Sup3rS3cr3tP4ssw0rd!" + }, + "outputs": {} + }, + "narrative": "The Salvage Decryptor. A field-ready tablet patched together with duct tape and copper wire." + } + ], + "edges": [ + { + "source_id": "terminal_2", + "target_id": "matter_synthesizer", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "blueprint" + }, + { + "source_id": "calc_bigmul", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "num2" + }, + { + "source_id": "calc_modexp", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "b" + }, + { + "source_id": "calc_inv_mod", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "base" + }, + { + "source_id": "container_4", + "target_id": "calc_inv_mod", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "a" + }, + { + "source_id": "num_base_convert", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "mod" + }, + { + "source_id": "calc_bigmul_02cb", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "a" + }, + { + "source_id": "item_8", + "target_id": "container_4", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "calc_inv_mod_e37a", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "b" + }, + { + "source_id": "calc_inv_mod_e37a", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "mod" + }, + { + "source_id": "calc_gcd_1d8d", + "target_id": "calc_bigmul_02cb", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "a" + }, + { + "source_id": "json_get", + "target_id": "container_4", + "connection_type": "Text_Generic", + "source_port": "values", + "target_port": "fingerprint_input" + }, + { + "source_id": "calc_inv_mod_e37a", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "a" + }, + { + "source_id": "calc_gcd_1d8d", + "target_id": "calc_inv_mod_e37a", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "a" + }, + { + "source_id": "zip_unzip_file", + "target_id": "json_get", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "csv_query", + "target_id": "json_get", + "connection_type": "Text_Generic", + "source_port": "rows", + "target_port": "jsonpath" + }, + { + "source_id": "num_base_convert", + "target_id": "calc_inv_mod_e37a", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "mod" + }, + { + "source_id": "calc_inv_mod_14bc", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "to_base" + }, + { + "source_id": "num_base_convert", + "target_id": "calc_bigmul_02cb", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "b" + }, + { + "source_id": "item_8_819e", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "calc_inv_mod_cd7c", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "num1" + }, + { + "source_id": "container_1", + "target_id": "calc_gcd", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "hmac_sha256", + "target_id": "container_1", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "fingerprint_input" + }, + { + "source_id": "terminal_2_d08a", + "target_id": "container_1", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "source_tool" + }, + { + "source_id": "calc_inv_mod_cd7c", + "target_id": "calc_inv_mod_14bc", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "mod" + }, + { + "source_id": "terminal_2_d08a", + "target_id": "csv_query", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "select" + }, + { + "source_id": "terminal_2_d08a", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "password" + }, + { + "source_id": "item_8_9fe7", + "target_id": "csv_query", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "exp" + }, + { + "source_id": "item_8_defb", + "target_id": "item_8_9fe7", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "zip_unzip_item", + "target_id": "zip_unzip_file", + "connection_type": "Item", + "source_port": "item", + "target_port": "trigger_item" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-248c41a5/environment/puzzle/service.py b/tasks/agentescape-25-skeleton-248c41a5/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-25-skeleton-248c41a5/environment/puzzle/service.py @@ -0,0 +1,212 @@ +"""Restricted facade over the unchanged, pinned upstream puzzle handlers.""" + +import hashlib +import json +import logging +import os +import sys +import threading +import urllib.request +import uuid +from pathlib import Path + +from fastapi import FastAPI, HTTPException +from fastapi.responses import JSONResponse +from pydantic import BaseModel, ConfigDict + +sys.path.insert(0, str(Path(__file__).parent / "upstream")) +import server as upstream # noqa: E402 + +log = logging.getLogger(__name__) + + +def public(value): + """Keep upstream agent-internal template hints out of the public response.""" + if isinstance(value, dict): + return {k: public(v) for k, v in value.items() if not k.startswith("_")} + if isinstance(value, list): + return [public(v) for v in value] + return value + + +class Action(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + action: str + node_id: str | None = None + arguments: dict | None = None + answer: str | None = None + + +class Episode: + def __init__( + self, scenario_path, max_actions=500, evidence_dir=None, worker_url=None + ): + if max_actions < 1: + raise ValueError("max_actions must be positive") + self.lock = threading.Lock() + self.max_actions = max_actions + self.count = 0 + self.won = False + self.reason = None + self.evidence_dir = Path(evidence_dir) if evidence_dir else None + self.scenario_hash = hashlib.sha256( + Path(scenario_path).read_bytes() + ).hexdigest() + self.initial = upstream.reset_case( + case_file_path=str(scenario_path), session_id=uuid.uuid4().hex + ) + self.case_id = self.initial["case_id"] + # Hide source file paths; no upstream reset/stats/routes are mounted. + self.initial.pop("message", None) + simulator = upstream.SIMULATORS[self.case_id] + if worker_url is None: + + def no_worker(_inputs): + self.reason = "infrastructure_error" + raise RuntimeError("isolated Python worker is not configured") + + simulator.tool_map["code_py_exec"] = no_worker + else: + + def execute_python(inputs): + request = urllib.request.Request( + worker_url + "/execute", + data=json.dumps({"code": inputs.get("code", "")}).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=12) as response: + result = json.load(response) + if not isinstance(result.get("stdout"), str): + raise RuntimeError("Invalid Python worker response") + return result + except Exception: + self.reason = "infrastructure_error" + raise + + simulator.tool_map["code_py_exec"] = execute_python + self.save() + if self.evidence_dir is not None: + (self.evidence_dir / "trace.jsonl").touch() + + def state(self): + return { + "scenario_sha256": self.scenario_hash, + "action_count": self.count, + "max_actions": self.max_actions, + "won": self.won, + "termination_reason": self.reason, + } + + def save(self, action=None, result=None): + if self.evidence_dir is None: + return + self.evidence_dir.mkdir(parents=True, exist_ok=True) + target = self.evidence_dir / "outcome.json" + temp = target.with_suffix(".tmp") + temp.write_text(json.dumps(self.state())) + temp.replace(target) + if action is not None: + with (self.evidence_dir / "trace.jsonl").open("a") as handle: + handle.write( + json.dumps( + {"index": self.count, "action": action, "result": result} + ) + + "\n" + ) + + def dispatch(self, payload): + with self.lock: + if self.reason is not None: + return { + "ok": False, + "error": "Episode has ended", + "episode": self.state(), + } + self.count += 1 + try: + action = Action.model_validate(payload) + if action.action == "submit_answer" and action.answer is not None: + result = upstream.submit_answer( + self.case_id, upstream.SubmitAnswerRequest(answer=action.answer) + ) + if result.get("is_win"): + self.won = True + self.reason = "success" + elif action.action == "investigate" and action.node_id is not None: + result = upstream.investigate( + self.case_id, + upstream.InvestigateRequest(node_id=action.node_id), + ) + elif ( + action.action in ("tool_call", "use_item") + and action.node_id is not None + ): + request_type, handler = ( + (upstream.ToolCallRequest, upstream.tool_call) + if action.action == "tool_call" + else (upstream.UseItemRequest, upstream.use_item) + ) + result = handler( + self.case_id, + request_type( + node_id=action.node_id, arguments=action.arguments or {} + ), + ) + else: + result = { + "ok": False, + "error": "Unknown action or missing action parameter", + } + except HTTPException as exc: + result = {"ok": False, "error": exc.detail} + except ValueError: + result = {"ok": False, "error": "Malformed action"} + except Exception: + log.exception("Puzzle service failure") + self.reason = "infrastructure_error" + self.save() + raise + if self.reason is None and self.count >= self.max_actions: + self.reason = "action_budget_exhausted" + result = public(result) + result["episode"] = self.state() + self.save(payload, result) + return result + + +def create_app( + scenario_path=None, max_actions=None, evidence_dir=None, worker_url=None +): + episode = Episode( + scenario_path or os.environ["SCENARIO_PATH"], + max_actions or int(os.environ.get("MAX_ACTIONS", "500")), + evidence_dir if evidence_dir is not None else os.environ.get("EVIDENCE_DIR"), + worker_url if worker_url is not None else os.environ.get("WORKER_URL"), + ) + app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) + app.state.episode = episode + + @app.get("/health") + def health(): + return {"ok": True} + + @app.get("/observation") + def observation(): + return {**public(episode.initial), "episode": episode.state()} + + @app.get("/state") + def state(): + return episode.state() + + @app.post("/action") + def action(payload: dict): + try: + return episode.dispatch(payload) + except Exception: + return JSONResponse( + status_code=503, + content={"ok": False, "error": "Puzzle infrastructure failure"}, + ) + + return app diff --git a/tasks/agentescape-25-skeleton-248c41a5/environment/puzzle/upstream/models.py b/tasks/agentescape-25-skeleton-248c41a5/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-25-skeleton-248c41a5/environment/puzzle/upstream/models.py @@ -0,0 +1,108 @@ +from enum import Enum +from typing import List, Dict, Any, Optional +from pydantic import BaseModel, Field + +# 1. 细粒度接口类型定义 +class InterfaceType(str, Enum): + ''' + BIG_INT + TEXT_GENERIC + HEX_STRING + FILE_ID + HEX_STRING_KEY_AES + HEX_STRING_IV_AES + CODE_PYTHON + HIDDEN_ITEM + ITEM + ''' + # --- 基础类型 --- + TEXT_GENERIC = "Text_Generic" + BIG_INT = "Big_Int" + + # --- 编码/格式化字符串 --- + HEX_STRING = "Hex_String" # 通用 Hex + + # --- 特定用途的 Hex 字符串 (用于精确匹配) --- + HEX_STRING_KEY_AES = "Hex_String_Key_AES" + HEX_STRING_IV_AES = "Hex_String_IV_AES" + + # --- 文件类型 --- + FILE_ID = "File_Id" + + # --- 代码/脚本 --- + CODE_PYTHON = "Code_Python" + + # --- 实体交互类型 (严格命名) --- + ITEM = "Item" # 主动掉落接口 (Tool -> Item) + HIDDEN_ITEM = "Hidden_Item" # 被动掉落接口 (Item -> Item) + +# 3. 端口定义 +class Port(BaseModel): + name: str + type: InterfaceType + description: str + +# 4. 统一节点定义 (融合工具和物品) +class Node(BaseModel): + id: str + name: str + description: str + type: str # "Tool" or "Item" + + # 接口定义 + inputs: List[Port] = [] + outputs: List[Port] = [] + + # 状态字段 + content: Optional[Any] = None # 物品有内容,工具为None + if_success: Optional[bool] = None # 工具初始为False,物品为None + initial_visible: bool = False + + # 运行时状态 (Server维护) + is_revealed: bool = False + + # 标记该 Tool 节点是否有待触发的 HIDDEN_ITEM 掉落 + # 当 Tool 按照 golden_input 正确执行且有 HIDDEN_ITEM 输出边时设为 True + # 在 investigate 该 Tool 时触发掉落并重置为 False + has_hidden_item_ready: bool = False + + # 初始输入值 (metadata.initial_values.init_inputs,用于渐进式暴露判断) + init_input_values: Dict[str, Any] = {} + + # Golden 输入值 (nodes[].inputs[].value,用于评测验证) + golden_input_values: Dict[str, Any] = {} + + # Golden 输出值 (nodes[].outputs[].value,用于评测验证和 Item 节点的 content) + golden_output_values: Dict[str, Any] = {} + + # 实际获得的输出值历史 (工具每次执行后实际返回的输出列表,用于渐进式暴露判断) + # 格式: List[Dict[str, Any]],每个元素是一次执行的输出字典 + actual_outputs_history: List[Dict[str, Any]] = [] + + # 逻辑规则 (用于终端机等复杂物品) + logic_rules: Optional[Dict[str, Any]] = None + + def copy(self, **kwargs): + """Helper to create a copy with updated fields.""" + data = self.dict() + data.update(kwargs) + return Node(**data) + +# 5. 边定义 (拓扑结构) +class Edge(BaseModel): + source_id: str + target_id: str + connection_type: InterfaceType # 直接使用 InterfaceType + # 如果是 Data_Flow,指定端口对应关系 + source_port: Optional[str] = None + target_port: Optional[str] = None + +# 6. 完整图定义 +class GraphScenario(BaseModel): + case_id: str + title: str + intro_narrative: str + nodes: Dict[str, Node] + edges: List[Edge] + difficulty: int + win_node_id: str # 标记哪个节点是最终目标(通常是一个提交工具或最终物品) diff --git a/tasks/agentescape-25-skeleton-248c41a5/environment/puzzle/upstream/server.py b/tasks/agentescape-25-skeleton-248c41a5/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-25-skeleton-248c41a5/environment/puzzle/upstream/server.py @@ -0,0 +1,1490 @@ +import json +import os +import time +import logging +import random +from pathlib import Path +from typing import Dict, Any, List, Optional +from datetime import datetime +from collections import defaultdict +from fastapi import FastAPI, HTTPException, Request +from fastapi.responses import JSONResponse +from fastapi.middleware.cors import CORSMiddleware +from pydantic import BaseModel, Field + +from models import GraphScenario, Node, InterfaceType +# from generator import ScenarioGenerator +from simulator import ToolSimulator +import uvicorn + +# 配置日志 +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler('server.log'), + logging.StreamHandler() + ] +) +logger = logging.getLogger(__name__) + +app = FastAPI( + title="AgentEscapeBench Universal Server", + version="1.0.0", + description="Industrial-grade evaluation server for escape room AI agents" +) + +# 添加 CORS 支持 +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# In-memory State +SCENARIOS: Dict[str, GraphScenario] = {} +SIMULATORS: Dict[str, ToolSimulator] = {} # case_id -> ToolSimulator +RAW_NODES_DATA: Dict[str, Dict[str, Any]] = {} # case_id -> node_id -> raw node data (for template_id) +FILE_METADATA: Dict[str, Dict[str, Any]] = {} # case_id -> metadata (for initial_values access) + +# Performance monitoring +STATS: Dict[str, Any] = { + "total_requests": 0, + "successful_requests": 0, + "failed_requests": 0, + "tool_calls": defaultdict(int), + "investigates": defaultdict(int), + "use_items": defaultdict(int), + "case_loads": 0, + "start_time": datetime.now() +} + +# Request timing middleware +@app.middleware("http") +async def add_process_time_header(request: Request, call_next): + start_time = time.time() + STATS["total_requests"] += 1 + + try: + response = await call_next(request) + STATS["successful_requests"] += 1 + process_time = time.time() - start_time + response.headers["X-Process-Time"] = str(process_time) + logger.info(f"{request.method} {request.url.path} - {response.status_code} - {process_time:.3f}s") + return response + except Exception as e: + STATS["failed_requests"] += 1 + logger.error(f"{request.method} {request.url.path} - Error: {str(e)}") + raise + +# Exception handler +@app.exception_handler(Exception) +async def global_exception_handler(request: Request, exc: Exception): + logger.error(f"Unhandled exception: {exc}", exc_info=True) + return JSONResponse( + status_code=500, + content={ + "ok": False, + "error": "Internal server error", + "detail": str(exc) if os.getenv("DEBUG") else "An error occurred" + } + ) + +# Health check endpoint +@app.get("/health") +def health_check(): + """健康检查端点""" + uptime = (datetime.now() - STATS["start_time"]).total_seconds() + return { + "status": "healthy", + "version": "1.0.0", + "uptime_seconds": uptime, + "loaded_cases": len(SCENARIOS), + "stats": { + "total_requests": STATS["total_requests"], + "successful_requests": STATS["successful_requests"], + "failed_requests": STATS["failed_requests"], + "success_rate": STATS["successful_requests"] / max(STATS["total_requests"], 1) + } + } + +# Statistics endpoint +@app.get("/stats") +def get_stats(): + """获取详细统计信息""" + return { + "stats": STATS, + "loaded_cases": list(SCENARIOS.keys()), + "uptime": str(datetime.now() - STATS["start_time"]) + } + +def _apply_progressive_reveal_at_init(scenario: GraphScenario): + """ + 在初始化时应用渐进式暴露机制(基于ITEM/HIDDEN_ITEM边) + + 新逻辑: + - 如果一个节点没有 ITEM/HIDDEN_ITEM 类型的入边,它就是初始可见的 + - 如果一个节点有 ITEM/HIDDEN_ITEM 类型的入边,它初始不可见,需要等待上游触发 + + Args: + scenario: 场景对象 + """ + # 收集所有有 ITEM/HIDDEN_ITEM 入边的节点 + nodes_with_item_edges = set() + for edge in scenario.edges: + if edge.connection_type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + nodes_with_item_edges.add(edge.target_id) + + logger.info(f"Nodes with ITEM/HIDDEN_ITEM incoming edges: {nodes_with_item_edges}") + + # 设置初始可见性:没有 ITEM/HIDDEN_ITEM 入边的节点初始可见 + initially_visible_count = 0 + for node_id, node in scenario.nodes.items(): + if node_id not in nodes_with_item_edges: + node.is_revealed = True + initially_visible_count += 1 + logger.info(f"Initial visible (no ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + else: + node.is_revealed = False + logger.debug(f"Initial hidden (has ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + + logger.info(f"Progressive reveal initialized: {initially_visible_count}/{len(scenario.nodes)} nodes initially visible") + + +def _check_inputs_match_golden(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> bool: + """ + 检查实际输入参数是否与 golden inputs 完全匹配 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + True 表示所有 golden inputs 都存在且值匹配 + """ + if not golden_inputs: + return True # 如果没有 golden inputs,认为匹配 + + for key, expected_value in golden_inputs.items(): + actual_value = arguments.get(key) + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) != str(expected_value): + logger.debug(f"Input mismatch for '{key}': expected '{expected_value}', got '{actual_value}'") + return False + + return True + + +def _get_parameter_validation_feedback(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> Dict[str, Any]: + """ + 对源头节点的参数进行详细验证,返回验证反馈 + + 注意:不返回期望值(expected),避免泄漏答案 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + 包含验证结果的字典: + - all_correct: bool - 所有参数是否正确 + - correct_params: List[str] - 正确的参数名列表 + - incorrect_params: List[str] - 错误的参数名列表(不包含期望值) + """ + if not golden_inputs: + return { + "all_correct": True, + "correct_params": [], + "incorrect_params": [] + } + + correct_params = [] + incorrect_params = [] + + for key, actual_value in arguments.items(): + # 只对用户实际提交的参数给反馈,未提交的参数不评价 + if key not in golden_inputs: + continue # 该参数不在 golden 中,跳过(如 _golden_inputs 等内部参数) + expected_value = golden_inputs[key] + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) == str(expected_value): + correct_params.append(key) + else: + # 只记录参数名,不包含期望值,避免泄漏答案 + incorrect_params.append(key) + + # all_correct:用户提交的所有参数都正确,且覆盖了全部 golden 参数 + all_provided_correct = len(incorrect_params) == 0 + all_golden_covered = all(k in arguments for k in golden_inputs) + return { + "all_correct": all_provided_correct and all_golden_covered, + "correct_params": correct_params, + "incorrect_params": incorrect_params + } + + +def _is_source_node(node_id: str, scenario: GraphScenario) -> bool: + """ + 判断节点是否是源头节点(完全没有任何入边的节点) + + 源头节点定义: + - 没有任何类型的入边(包括 DATA、ITEM、HIDDEN_ITEM) + - 即没有任何上游节点 + + Args: + node_id: 节点ID + scenario: 场景对象 + + Returns: + True 表示是源头节点 + """ + for edge in scenario.edges: + if edge.target_id == node_id: + # 只要有任何入边,就不是源头节点 + return False + + return True + + +def _check_and_reveal_ready_nodes(scenario: GraphScenario, recent_outputs: Dict[str, Any], source_node_id: str) -> List[Dict[str, Any]]: + """ + 检查并释放参数齐全的隐藏节点(渐进式暴露机制) + + 核心逻辑: + 1. 维护"可见值集合":包含所有被测模型当前可以看到的值 + - init_inputs 的值(初始可见) + - 工具执行后的实际输出值(运行时获得) + - 可见 Item 的输出值 + 2. 检查隐藏节点:该节点的所有 golden_input 值是否都在可见值集合中 + 3. 如果是,则释放该节点 + + Args: + scenario: 场景对象 + recent_outputs: 最近执行的工具的输出 + source_node_id: 刚执行的工具节点ID + + Returns: + 新释放的节点列表 + """ + newly_revealed = [] + + # 构建"可见值集合"(Set of visible values) + # 存储格式:set of values (转为字符串) + visible_values = set() + + # 1. 添加有意义的 init_inputs 值到可见值集合 + # Item 的 init_inputs 不应该加入,因为它们在密室中完全用不到 + for node_id, node in scenario.nodes.items(): + # 跳过源头 Item 节点(没有入边的 Item) + if node.type == "Item": + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,跳过其 init_inputs + continue + + # 添加其他节点的 init_inputs + for port_name, init_value in node.init_input_values.items(): + if init_value: + visible_values.add(str(init_value)) + + # 2. 添加已执行工具的所有历史输出值 + for node_id, node in scenario.nodes.items(): + if node.type == "Tool" and node.if_success and node.actual_outputs_history: + # 遍历所有历史执行记录 + for output_dict in node.actual_outputs_history: + for output_port_name, output_value in output_dict.items(): + if output_value: + visible_values.add(str(output_value)) + + # 3. 添加已被 investigate 的 Item 的 golden 输出值 + # 注意:Item 可见不等于其输出值可见,需要 investigate 后才能获得 + # 这里我们使用 actual_outputs_history 来标记 Item 是否已被 investigate + for node_id, node in scenario.nodes.items(): + if node.type == "Item" and node.is_revealed and node.actual_outputs_history: + # Item 通常只会被 investigate 一次,但为了一致性也使用历史列表 + for output_dict in node.actual_outputs_history: + for port_name, port_value in output_dict.items(): + if port_value: + visible_values.add(str(port_value)) + + # 遍历所有隐藏的节点,检查其 golden_input 是否都在可见值集合中 + for node_id, node in scenario.nodes.items(): + # 跳过已可见的节点 + if node.is_revealed: + continue + + # 只检查工具节点(物品节点由 ITEM 输出触发) + if node.type != "Tool": + continue + + # 检查该节点的所有 golden_input 值是否都在可见值集合中 + all_inputs_ready = True + missing_values = [] + + for input_port_name, golden_input_value in node.golden_input_values.items(): + # 检查这个 golden 值是否在可见值集合中 + if str(golden_input_value) not in visible_values: + all_inputs_ready = False + missing_values.append(f"{input_port_name}={golden_input_value}") + + # 如果所有 golden_input 值都在可见值集合中,释放该节点 + if all_inputs_ready and len(node.golden_input_values) > 0: + logger.info(f"All golden inputs ready for {node_id}: {list(node.golden_input_values.values())}") + + # 如果所有输入都齐全,释放该节点 + if all_inputs_ready: + node.is_revealed = True + + # 构建节点信息返回给模型 + node_info = { + "id": node.id, + "type": node.type, + "can_investigate": True, + "hint": "This tool's input parameters are now complete, you can use investigate to view detailed information" + } + + # if node.name: + # node_info["name"] = node.name + if node.description: + node_info["description"] = node.description + + newly_revealed.append(node_info) + logger.info(f"Progressive reveal: {node_id} is now ready (all inputs satisfied)") + + return newly_revealed + + +def _initialize_node_values(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]): + """ + Initialize node state and load values from port value fields. + 应用渐进式暴露机制:初始时只显示参数齐全的节点(源头节点) + + 重要区分: + 1. input_values: 只加载 metadata.initial_values 中的 init_inputs(真正的初始值) + 2. output_values: 加载 nodes[].outputs[].value(golden 输出,用于验证) + """ + # 第一步:加载所有节点的值,并将所有节点初始设为隐藏 + initial_values = metadata.get('initial_values', {}) + + for node_id, node in scenario.nodes.items(): + # 忽略 initial_visible 字段,初始全部隐藏 + # 由渐进式暴露机制根据参数齐全情况决定是否显示 + node.is_revealed = False + + if node.type == "Tool": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + elif node.type == "Item": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + + # 从 JSON 加载值 + if node_id in raw_nodes_data: + node_data = raw_nodes_data[node_id] # node_data是json文件中nodes中的字典 + + # 【重要】只加载 metadata.initial_values 中的初始输入值 + if node_id in initial_values: + init_data = initial_values[node_id] + # 加载初始输入值(用于渐进式暴露判断) + for port_name, port_value in init_data.get('init_inputs', {}).items(): + node.init_input_values[port_name] = port_value + + # 【评测用】加载 golden 输入值(用于验证模型传入的参数是否正确) + for input_port_data in node_data.get('inputs', []): + if 'value' in input_port_data: + node.golden_input_values[input_port_data['name']] = input_port_data['value'] + + # 【评测用】加载 golden 输出值(用于验证工具调用是否正确,以及 Item 节点的 content) + for output_port_data in node_data.get('outputs', []): + if 'value' in output_port_data: + node.golden_output_values[output_port_data['name']] = output_port_data['value'] + + # For Items, set content from golden_output_values + if node.type == "Item" and node.golden_output_values: + # Item 的 content 是其第一个 golden 输出值 + node.content = list(node.golden_output_values.values())[0] + + # 第二步:应用渐进式暴露机制 + # 检查所有节点,根据参数齐全情况释放源头节点(工具 + Item) + _apply_progressive_reveal_at_init(scenario) + +def _build_node_info(node: Node, raw_nodes_data: Dict[str, Any]) -> Dict[str, Any]: + """ + 构建节点信息(工具或物品) + + Args: + node: 节点对象 + raw_nodes_data: 原始节点数据(用于获取 template_id 等) + + Returns: + 节点信息字典 + """ + if node.type == "Tool": + # 过滤掉输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口) + # 这些端口仅用于控制掉落机制,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + tool_info = { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Tool", + "inputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.inputs if p.type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]], + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id(工具的标准名称) + if node.id in raw_nodes_data: + node_data = raw_nodes_data[node.id] + template_id = node_data.get('template_id') + if template_id: + tool_info['template_id'] = template_id + + return tool_info + + elif node.type == "Item": + return { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Item" + } + + else: + return { + "id": node.id, + # "name": node.name, + "type": node.type + } + +def _get_initial_observation(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]) -> Dict[str, Any]: + """ + Generate initial observation for the agent (what they see when entering the room). + + 策略: + - Tools: 只显示名称和描述,不显示接口定义。需要 investigate 才能获得详细接口信息。 + - Items: 只显示存在,不显示内容。需要 investigate 才能获得内容值。 + - init_inputs: 作为"可用信息"告诉模型,这些是可以用作工具参数的初始值。 + - init_outputs: 不告诉模型(这些是答案,需要模型通过调用工具获得)。 + """ + available_entities = [] # 统一的实体列表(Tools 和 Items) + available_information = [] # 可用的初始信息(来自 init_inputs) + + # 从 metadata.initial_values 提取 init_inputs 作为可用信息 + # 只提供值本身,不透露这些值对应哪个节点的哪个参数,让模型自己推理 + # 注意:跳过源头 Item(没有入边的 Item)的 init_inputs,因为它们在密室中完全用不到 + initial_values = metadata.get('initial_values', {}) + # initial_values字段的格式 + # "initial_values": { + # "terminal_1": { + # "init_inputs": {}, + # "init_outputs": { + # "text_output": "System initialization complete.", + # "hex_output": "48656c6c6f20576f726c64", + # "item_dispenser": "掉落了一张纸条,上面写着“请勿随意触摸终端”" + # } + # } + # } + for node_id, init_data in initial_values.items(): + # 获取节点信息,判断是否为源头 Item + node = scenario.nodes.get(node_id) + if node and node.type == "Item": + # 检查是否为源头 Item(没有入边) + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,检查是否有 init_inputs + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 有 init_inputs,需要暴露这些参数 + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + # 处理完后跳过后续的通用逻辑 + continue + + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 为每个 init_input 值创建一个信息条目(不包含 source_node 和 parameter 信息) + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + + for node in scenario.nodes.values(): + if node.is_revealed: + # Tools: 只显示基本信息,提示可以 investigate 查看详细接口 + if node.type == "Tool": + tool_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Tool", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the tool's detailed interface information for calling" + } + # 只在 name 非空时添加 + # if node.name: + # tool_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_info["description"] = node.description + + available_entities.append(tool_info) + + # Items: 只显示基本信息,提示可以 investigate 查看内容 + elif node.type == "Item": + item_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Item", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the item's content" + } + # 只在 name 非空时添加 + # if node.name: + # item_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + item_info["description"] = node.description + + available_entities.append(item_info) + + return { + "narrative": scenario.intro_narrative, + "available_entities": available_entities, # 使用统一的实体列表 + "available_information": available_information, # 可用的初始信息(只包含 init_inputs) + "win_node_id": scenario.win_node_id # 胜利节点ID,让模型知道需要关注哪个节点 + } + +@app.post("/env/reset") +def reset_case(case_id: str = None, case_file_path: str = None, session_id: str = None): + """Loads a specific case from file and resets it. + + Args: + case_id: Optional case ID for resetting an existing case + case_file_path: Path to case file for loading a new case + session_id: Optional session ID to ensure isolation between concurrent evaluations + """ + logger.info(f"Reset request - case_id: {case_id}, case_file_path: {case_file_path}, session_id: {session_id}") + STATS["case_loads"] += 1 + + if case_file_path: + if not os.path.exists(case_file_path): + logger.error(f"Case file not found: {case_file_path}") + raise HTTPException(status_code=404, detail=f"File not found: {case_file_path}") + try: + with open(case_file_path, "r", encoding="utf-8") as f: + file_data = json.load(f) + + # 转换格式:从 DAG executor 生成的格式转换为 GraphScenario 格式 + # 1. 提取 metadata + metadata = file_data.get('metadata', {}) + + # 2. 生成 case_id, title, intro_narrative + # 【修复】为每个评测会话生成唯一的 case_id,防止并发评测时状态污染 + base_name = os.path.basename(case_file_path).replace('.json', '').replace('_full', '').replace('_full2', '') + + if session_id: + # 如果提供了 session_id,使用它来确保唯一性 + case_id = f"{base_name}_{session_id}" + else: + # 否则使用时间戳和随机数确保唯一性 + unique_suffix = f"{int(time.time() * 1000)}_{random.randint(1000, 9999)}" + case_id = f"{base_name}_{unique_suffix}" + + file_data['case_id'] = case_id + logger.info(f"Generated unique case_id: {case_id} (base: {base_name}, session: {session_id})") + + if 'title' not in file_data: + file_data['title'] = f"Escape Room: {file_data['case_id']}" + + if 'intro_narrative' not in file_data: # 目前的json文件中已经有了intro_narrative字段,不会使用下面一行的内容,而是使用每个评测问题的json文件中的对应字段 + 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]".' + + # 3. 转换 nodes 列表为字典(DAG executor 生成的文件中 nodes 是列表格式) + nodes_dict = {} + for node_data in file_data['nodes']: + nodes_dict[node_data['id']] = node_data # 这里的id是template_id之后可能添加一个后缀 + file_data['nodes'] = nodes_dict # 把列表转成一个字典 + + # 4. 添加缺失的字段 + if 'difficulty' not in file_data: + file_data['difficulty'] = metadata.get('total_nodes', 5) + + if 'win_node_id' not in file_data: + file_data['win_node_id'] = metadata.get('win_node_id', '') + + scenario = GraphScenario(**file_data) + + # Extract raw nodes data for template_id access + # nodes 已经在上面转换为字典格式 + raw_nodes_data = file_data.get('nodes', {}) + RAW_NODES_DATA[scenario.case_id] = raw_nodes_data + + # Store metadata for initial values access + FILE_METADATA[scenario.case_id] = metadata + + logger.info(f"Successfully parsed case file: {scenario.case_id}, nodes: {len(scenario.nodes)}, edges: {len(scenario.edges)}") + except Exception as e: + logger.error(f"Failed to load case file: {str(e)}", exc_info=True) + raise HTTPException(status_code=500, detail=f"Failed to load case file: {str(e)}") + + # Initialize node state and load values + _initialize_node_values(scenario, raw_nodes_data, metadata) + + SCENARIOS[scenario.case_id] = scenario + simulator = ToolSimulator() + SIMULATORS[scenario.case_id] = simulator + + 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'])}") + + # 生成初始观察信息(进入密室后看到的环境) + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + ''' + initial_observation的格式: + { + "narrative": scenario.intro_narrative, + "available_entities": available_entities # 使用统一的实体列表 + "available_information": available_information # 可用的初始信息(只包含 init_inputs) + } + ''' + + return { + "ok": True, + "message": f"Case loaded from {case_file_path}", + "case_id": scenario.case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果没有提供 case_file_path,但提供了 case_id,则尝试从内存重置 + if case_id and case_id in SCENARIOS: + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + metadata = FILE_METADATA.get(case_id, {}) + + # Reset dynamic fields and re-apply progressive reveal + # 重新初始化节点状态(包括渐进式暴露) + _initialize_node_values(scenario, raw_nodes_data, metadata) + + 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'])}") + + # 生成初始观察信息 + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + + return { + "ok": True, + "message": f"Case {case_id} reset.", + "case_id": case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果既没有 case_file_path,也没有在内存中找到,返回错误 + raise HTTPException( + status_code=400, + detail="Must provide case_file_path to load a new case, or use case_id to reset an existing case." + ) + +class InvestigateRequest(BaseModel): + node_id: str + +@app.post("/env/{case_id}/investigate") +def investigate(case_id: str, req: InvestigateRequest): + """ + Investigates a Tool or Item to reveal detailed information. + + - For Tools: Returns detailed interface information (inputs/outputs) needed to call the tool + - For Items: Returns content value and triggers hidden item drops + """ + logger.info(f"Investigate request - case_id: {case_id}, node_id: {req.node_id}") + STATS["investigates"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + node = scenario.nodes[req.node_id] + + if not node.is_revealed: + logger.warning(f"Attempt to investigate hidden node: {req.node_id}") + return {"ok": False, "error": "Node is not visible yet."} + + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + newly_revealed = [] + + # 处理 Tool 的 investigate + if node.type == "Tool": + logger.info(f"Investigating tool: {req.node_id}") + + # 返回工具的详细接口信息 + # id 字段使用 node.id(节点唯一标识),agent 用这个字段识别和调用具体的节点 + # template_id 是工具类型标识符,Agent 内部用于判断工具特性(如 terminal 类工具参数可选) + # 注意:只过滤输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口),这些端口仅用于控制掉落,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + # 【端口上游依赖提示 & 初始值直接给出】 + # 针对参数语义模糊(全为数字类型)的工具,在 investigate 返回信息中标注 + # 哪个输入端口来自哪个上游节点(upstream_from)。 + # 对于所有工具:若该节点不是纯源头节点(有任意数据流入边), + # 且某个端口没有上游入边(值来自初始可见参数),则直接给出该端口的 golden input 值。 + AMBIGUOUS_TOOLS = { + "num_base_convert", "calc_modexp", "calc_modexp_int", + "calc_inv_mod", "calc_inv_mod_int", "crypto_rsa_decrypt_hex", "geo_haversine" + } + # Terminal 类工具自带参数对错反馈机制,玩家/模型可自行试错, + # 无需在 investigate 时直接暴露 init_value + SELF_FEEDBACK_TOOLS = { + "terminal_1", "terminal_2", + "Logic Terminal", "Math Terminal", "Encryption Terminal", "Sequence Terminal" + } + _template_id_for_hint = raw_nodes_data.get(node.id, {}).get("template_id", "") + # 构建数据流入边映射(对所有工具):{target_port -> (source_node_id, source_port)} + _upstream_map = {} + for _edge in scenario.edges: + if (_edge.target_id == node.id + and _edge.connection_type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM] + and _edge.target_port is not None): + _upstream_map[_edge.target_port] = (_edge.source_id, _edge.source_port) + # 判断该节点是否有任意数据流入边(即不是纯源头节点) + _has_any_upstream = len(_upstream_map) > 0 + # 判断该节点是否有任意入边(包括 ITEM/HIDDEN_ITEM 掉落边) + # 有任意入边(含掉落边)但无数据流入边的节点,其输入来自初始可见参数,应直接给出 + _has_any_edge = any(_edge.target_id == node.id for _edge in scenario.edges) + # 构建 inputs 列表 + _inputs_list = [] + for p in node.inputs: + if p.type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + continue + port_dict = {"name": p.name, "type": p.type, "description": p.description} + if p.name in _upstream_map: + # 该端口有上游数据流依赖,且属于语义模糊工具 → 标注来源 + if _template_id_for_hint in AMBIGUOUS_TOOLS: + src_node_id, src_port = _upstream_map[p.name] + port_dict["upstream_from"] = f"{src_node_id}.{src_port}" if src_port else src_node_id + elif _has_any_edge and _template_id_for_hint not in SELF_FEEDBACK_TOOLS: + # 该节点有任意入边,但此端口没有数据流入边 → 值来自初始可见参数,直接给出 + # 排除自带反馈机制的 terminal 类工具(它们通过执行结果反馈对错,无需提前暴露参数值) + golden_val = node.golden_input_values.get(p.name) + if golden_val is not None: + port_dict["init_value"] = golden_val + _inputs_list.append(port_dict) + + tool_details = { + "id": node.id, # 节点 ID,用于唯一标识和调用这个具体节点 + "type": "Tool", + "inputs": _inputs_list, + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id 用于 Agent 内部判断工具类型(不会展示给被测模型) + if node.id in raw_nodes_data: + template_id = raw_nodes_data[node.id].get('template_id') + if template_id: + tool_details["_template_id"] = template_id # 使用下划线前缀标记为内部字段 + + # 只在 name 非空时添加 + # if node.name: + # tool_details["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_details["description"] = node.description + + # 添加 narrative 字段(如果存在) + if node.id in raw_nodes_data: + narrative = raw_nodes_data[node.id].get('narrative') + if narrative: + tool_details['narrative'] = narrative + + # 不再返回 init_values,避免泄漏答案 + # investigate 只应该返回工具的接口定义,不应该暴露初始值 + + # 【新增】检查该 Tool 是否有待触发的 HIDDEN_ITEM 掉落 + # 如果该工具已按照 golden_input 正确执行,且有 HIDDEN_ITEM 输出边,则触发掉落 + if node.has_hidden_item_ready: + logger.info(f"Tool has HIDDEN_ITEM ready - triggering passive drop for: {req.node_id}") + + # 遍历该工具的所有 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + # 重置标志,已经触发过了,避免重复 + node.has_hidden_item_ready = False + + logger.info(f"Tool investigation successful - node: {req.node_id}, revealed: {len(newly_revealed)}") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Tool", + "details": tool_details + } + + # 如果有新掉落的节点,添加到响应中 + if newly_revealed: + result["newly_revealed"] = newly_revealed + + return result + + # 处理 Item 的 investigate + elif node.type == "Item": + logger.info(f"Investigating item: {req.node_id}") + + # 【第一步】检查该 Item 是否有需要参数的输入端口 + # 如果有,且尚未通过 use_item 验证,则不返回内容,只返回参数要求 + required_inputs = [] + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + inputs_info = raw_node.get('inputs', []) + required_inputs = [ + { + "name": inp.get("name"), + "type": inp.get("type"), + "description": inp.get("description", "") + } + for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + # 如果有 required_inputs 且尚未通过 use_item 验证(if_success == False) + # 则不返回内容,只返回参数要求提示 + if required_inputs and not node.if_success: + logger.info(f"Item has required inputs and not yet unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "required_inputs": required_inputs + } + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + param_names = ', '.join([inp['name'] for inp in required_inputs]) + 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}" + + return result + + # 【新增】如果有 required_inputs 且已经通过 use_item 验证(if_success == True) + # 则返回提示:该节点已经被成功解决 + if required_inputs and node.if_success: + logger.info(f"Item has required inputs and already unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "message": "This item has already been successfully unlocked by you." + } + return result + + # 【第二步】该 Item 没有 required_inputs 或已通过验证,返回内容 + # 1. 返回 Item 的 golden_output_values(即 Item 的内容) + # 注意:某些 Item 仅用于触发 HIDDEN_ITEM 掉落,没有实际内容 + has_actual_content = bool(node.golden_output_values) or node.content is not None + content = node.golden_output_values if node.golden_output_values else node.content + + # 【关键】将 golden_output_values 追加到 actual_outputs_history,标记该 Item 已被 investigate + # 这样在渐进式暴露时,这些值才会被加入可见值集合 + # 即使是空字典(仅触发 HIDDEN_ITEM 的 Item),也要记录,以便渐进式暴露逻辑知道该 Item 已被调查 + if node.golden_output_values is not None: + node.actual_outputs_history.append(dict(node.golden_output_values)) + + # 2. Trigger Hidden Item Drops (Passive Drop) + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + logger.info(f"Item investigation successful - node: {req.node_id}, has_content: {has_actual_content}, revealed: {len(newly_revealed)}") + + # 【渐进式暴露】旧机制(基于 golden_input)已禁用 + # 现在完全由 ITEM/HIDDEN_ITEM 边触发控制节点可见性 + # 上面的 HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, node.golden_output_values or {}, node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # logger.info(f"Progressive reveal after Item investigate: {len(progressive_revealed)} nodes now ready") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Item" + } + + # 只在有实际内容时才添加 content 字段 + # 对于仅触发 HIDDEN_ITEM 掉落的 Item,不返回 content 字段,避免返回 None 或空字典让模型困惑 + if has_actual_content: + result["content"] = content + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型通过 investigate 获得内容后,需要自己识别这是否是胜利字符串 + + return result + + else: + logger.warning(f"Attempt to investigate unknown node type: {req.node_id} (type: {node.type})") + return {"ok": False, "error": f"Cannot investigate node type: {node.type}"} + +class ToolCallRequest(BaseModel): + node_id: str # 使用 node_id 精确指定要调用的节点 + arguments: Dict[str, Any] + +@app.post("/env/{case_id}/tool_call") +def tool_call(case_id: str, req: ToolCallRequest): + """Executes a tool and triggers item drops.""" + logger.info(f"Tool call request - case_id: {case_id}, node_id: {req.node_id}, args: {list(req.arguments.keys())}") + STATS["tool_calls"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + + # 通过 node_id 精确查找节点 + node_id = req.node_id + if node_id not in scenario.nodes: + logger.error(f"Node not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + tool_node = scenario.nodes[node_id] + + if not tool_node: + logger.error(f"Tool not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Tool not found") + + if not tool_node.is_revealed: + logger.warning(f"Attempt to call hidden tool: {node_id}") + return {"ok": False, "error": "Tool is not visible yet."} + + if tool_node.type != "Tool": + logger.warning(f"Attempt to call non-tool node: {node_id} (type: {tool_node.type})") + return {"ok": False, "error": "Only tools can be called."} + + # 1. Execute Tool (Real Execution via Simulator) + simulator = SIMULATORS[case_id] + + # Get tool name from template_id if available, otherwise use node name + tool_name = tool_node.name + if case_id in RAW_NODES_DATA and node_id in RAW_NODES_DATA[case_id]: + template_id = RAW_NODES_DATA[case_id][node_id].get('template_id') + if template_id: + tool_name = template_id + + # 文件处理工具和 Terminal 需要验证输入并返回预先计算的输出 + # 传递节点的实际输入输出值(从 DAG 执行后填充的数据) + tool_arguments = dict(req.arguments) # Make a copy + + # 传递节点的 golden values(从 JSON 的 inputs[].value 和 outputs[].value 加载) + # 用于在评测阶段验证被测模型传入的参数是否正确 + if tool_node.golden_input_values: + tool_arguments['_golden_inputs'] = tool_node.golden_input_values + if tool_node.golden_output_values: + tool_arguments['_golden_outputs'] = tool_node.golden_output_values + + logger.debug(f"Executing tool {tool_name} (node: {tool_node.name}) with args {tool_arguments}") + + try: + output_values = simulator.execute(tool_name, tool_arguments) + logger.info(f"Tool invoked - {tool_name}: {list(output_values.keys())}") + except Exception as e: + logger.error(f"Tool execution failed - {tool_name}: {str(e)}", exc_info=True) + return {"ok": False, "error": f"Tool execution failed: {str(e)}"} + + # 检查验证结果(精细化错误反馈) + validation = output_values.pop("_validation", {"valid": True}) + + if not validation["valid"]: + # 根据错误类型构造友好的错误消息 + error_type = validation.get("error_type") + + if error_type == "missing_required": + missing = validation.get("missing_params", []) + error_msg = f"Error: Missing required parameters {', '.join(missing)}" + + elif error_type == "type_error": + param = validation.get("param_name") + message = validation.get("message", "Parameter type error") + error_msg = f"Error: {message}" + + elif error_type == "incomplete_optional": + provided = validation.get("provided_params", []) + missing = validation.get("missing_params", []) + error_msg = ( + f"Hint: You provided some parameters ({', '.join(provided)}), " + f"but may also need: {', '.join(missing)}.\n" + f"Trying to provide these parameters together might yield better results." + ) + + elif error_type == "value_mismatch": + param = validation.get("param_name") + hint = validation.get("hint", "Parameter value may be incorrect") + error_msg = f"Hint: {hint}.\nPlease check if this parameter value meets the requirements." + + else: + error_msg = validation.get("hint") or validation.get("message", "Parameter validation failed") + + logger.info(f"Tool validation failed - {tool_name}: {error_type}") + return { + "ok": False, + "error": error_msg, + "error_type": error_type + } + + # Simulate success + tool_node.if_success = True + + # 【关键】将本次执行的输出值追加到历史列表(用于渐进式暴露判断) + # 每次调用都会记录,不会覆盖之前的执行结果 + tool_node.actual_outputs_history.append(dict(output_values)) + + # 2. 检查是否应该触发掉落(只有输入参数正确时才掉落) + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, tool_node.golden_input_values) + + newly_revealed = [] + investigate_hints = [] # 提示模型哪些节点可以 investigate 来发现隐藏内容 + + if inputs_match_golden: + logger.info(f"✓ Tool inputs match golden - node: {node_id}, triggering drops") + + # 检查该工具是否有 ITEM 或 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == tool_node.id: + target_node = scenario.nodes[edge.target_id] + + # ITEM 边:立即掉落(主动掉落) + if edge.connection_type == InterfaceType.ITEM: + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from {node_id})") + + # HIDDEN_ITEM 边:不立即掉落,标记并提示(被动掉落) + elif edge.connection_type == InterfaceType.HIDDEN_ITEM: + # 标记该工具有待触发的 HIDDEN_ITEM 掉落 + tool_node.has_hidden_item_ready = True + + # 提示模型可以 investigate 这个工具来发现隐藏内容 + hint_info = { + "tool_id": tool_node.id, + "hint": f"Tool '{tool_node.id}' seems to hide something, try investigating it to discover more information" + } + # if tool_node.name: + # hint_info["tool_name"] = tool_node.name + + investigate_hints.append(hint_info) + logger.info(f"HIDDEN_ITEM ready: {tool_node.id} -> {target_node.id} (will drop on investigate)") + else: + logger.info(f"✗ Tool inputs do NOT match golden - node: {node_id}, no drops triggered") + + response = { + "ok": True, + "message": "Tool invoked", + "output_values": output_values # Return raw outputs to Agent + } + + # 【新增】对源头节点进行参数验证反馈 + # 源头节点:没有数据流入边的节点,这些节点的参数需要模型自己推理 + # 验证模型使用的参数是否正确,并提供明确的反馈 + if _is_source_node(node_id, scenario) and tool_node.golden_input_values: + validation_feedback = _get_parameter_validation_feedback(req.arguments, tool_node.golden_input_values) + + if validation_feedback["all_correct"]: + # 用户提交了全部 golden 参数且全部正确 + response["parameter_feedback"] = { + "status": "correct", + "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." + } + logger.info(f"✓ Source node parameters all correct - node: {node_id}") + elif validation_feedback["incorrect_params"]: + # 有提交了但值错误的参数,只对这些参数给出反馈 + incorrect_list = [] + for param_name in validation_feedback["incorrect_params"]: + incorrect_list.append(f" - Parameter '{param_name}' is incorrect") + + correct_info = "" + if validation_feedback["correct_params"]: + correct_info = f"\n✓ Correct parameters: {', '.join(validation_feedback['correct_params'])}" + + response["parameter_feedback"] = { + "status": "incorrect", + "message": ( + f"⚠️ Some parameters are incorrect:\n" + + "\n".join(incorrect_list) + + correct_info + + 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." + ), + "incorrect_params": validation_feedback["incorrect_params"], + "correct_params": validation_feedback["correct_params"] + } + logger.info(f"✗ Source node parameters incorrect - node: {node_id}, incorrect: {validation_feedback['incorrect_params']}") + # else: 部分提交且全部正确 → 不给任何 parameter_feedback,避免对未提交的参数发表意见 + + # 检查工具调用是否完全正确(输出与 golden outputs 匹配) + # 用于给模型正向反馈,让它知道这个工具已经正确调用过,避免重复调用 + # 注意:只有当输出完全匹配时才标记为 correct,不会在错误时提供具体错误信息 + # if tool_node.golden_output_values and output_values: + # is_correct = True + # for port_name, expected_value in tool_node.golden_output_values.items(): + # actual_value = output_values.get(port_name) + # if str(actual_value) != str(expected_value): + # is_correct = False + # break + + # if is_correct: + # response["tool_call_correct"] = True + # logger.info(f"✓ Tool called with correct result - node: {node_id}") + + # 只在有新内容掉落时才返回 newly_revealed + if newly_revealed: + response["newly_revealed"] = newly_revealed + + # 添加 investigate 提示(对于有待触发 HIDDEN_ITEM 掉落的工具) + if investigate_hints: + response["investigate_hints"] = investigate_hints + + # 3. 渐进式暴露机制 - 现在完全由 ITEM/HIDDEN_ITEM 边控制 + # 旧机制(基于 golden_input 检查)已被禁用 + # 新机制中,节点的可见性只由 ITEM/HIDDEN_ITEM 边触发决定 + # 上面的 ITEM/HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, output_values, tool_node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # response["newly_revealed"] = newly_revealed + # logger.info(f"Progressive reveal: {len(progressive_revealed)} nodes now ready") + + # Check if this is the win node + if node_id == scenario.win_node_id: + # 验证输出值是否等于预期的胜利值 + # 从节点的 golden_output_values 中获取预期值(在 _initialize_node_values 时从 JSON 加载) + expected_outputs = tool_node.golden_output_values + + # 检查实际输出是否与预期输出匹配 + is_correct = False + victory_string = None + mismatch_info = [] + + if expected_outputs and output_values: + # 检查每个预期输出端口的值是否匹配 + is_correct = True + for port_name, expected_value in expected_outputs.items(): + actual_value = output_values.get(port_name) + if actual_value != expected_value: + is_correct = False + mismatch_info.append(f"Port '{port_name}': expected '{expected_value}', actual '{actual_value}'") + logger.warning(f"Win node output mismatch - port: {port_name}, expected: {expected_value}, actual: {actual_value}") + + # 如果所有输出都匹配,使用第一个输出作为胜利字符串 + if is_correct and output_values: + victory_string = list(output_values.values())[0] + else: + logger.warning(f"Win node called but missing output values - expected: {expected_outputs}, actual: {output_values}") + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型调用工具获得输出后,需要自己识别这是否是胜利字符串并提交 + if is_correct: + logger.info(f"🎯 Win node called with correct output - case: {case_id}, node: {node_id}, victory: {victory_string}") + else: + logger.info(f"❌ Win node called with incorrect output - case: {case_id}, node: {node_id}") + + return response + +class UseItemRequest(BaseModel): + node_id: str = Field(..., description="The ID of the Item node to use (must be Item type)") + arguments: Dict[str, Any] = Field(default_factory=dict, description="Input arguments to provide to the item") + +@app.post("/env/{case_id}/use_item") +def use_item(case_id: str, req: UseItemRequest): + """ + Use an Item node by providing input arguments. + + This is specifically for Item nodes that require parameters to be "unlocked" or "activated", + such as containers that need a password/fingerprint. + + - Validates that the node is of type Item + - Checks if provided arguments match the item's golden_input_values + - If match: triggers ITEM-type edge drops and returns the item's content + - If not match: returns error message + """ + logger.info(f"Use item request - case_id: {case_id}, node_id: {req.node_id}, args: {req.arguments}") + STATS["use_items"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + item_node = scenario.nodes[req.node_id] + + if not item_node.is_revealed: + logger.warning(f"Attempt to use hidden item: {req.node_id}") + return {"ok": False, "error": "Item is not visible yet."} + + if item_node.type != "Item": + logger.warning(f"Attempt to use non-item node: {req.node_id} (type: {item_node.type})") + return {"ok": False, "error": "Only Item nodes can be used with use_item. Tools should be called with tool_call."} + + # 【新增】检查该 Item 是否已经被成功解锁 + # 如果已经被正确使用过,直接返回成功提示 + if item_node.if_success: + logger.info(f"Item already unlocked, returning success message: {req.node_id}") + return { + "ok": True, + "message": "This item has already been successfully unlocked by you." + } + + # 检查该 Item 是否真的需要通过 use_item 提供参数 + # 只有当 Item 有非 Item/Hidden_Item 类型的输入时,才应该使用 use_item + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + non_hidden_inputs = [ + inp for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + if not non_hidden_inputs: + # 该 Item 不需要参数,应该只使用 investigate + logger.warning(f"Attempt to use_item on a node that doesn't require parameters: {req.node_id}") + return { + "ok": False, + "error": "This item does not require parameters. Please use investigate to examine the item directly." + } + + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, item_node.golden_input_values) + + if not inputs_match_golden: + logger.info(f"✗ Item inputs do NOT match golden - node: {req.node_id}") + # 提供更详细的错误信息,帮助 Agent 理解问题 + # 只显示非 Item/Hidden_Item 类型的参数(Hidden_Item 由系统自动处理) + expected_params = [] + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + expected_params = [ + inp.get("name") for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + provided_params = list(req.arguments.keys()) if req.arguments else [] + + # 检查参数名是否匹配 + if set(expected_params) == set(provided_params): + # 参数名正确但值不匹配 - 不泄漏正确的值 + error_msg = f"Parameter names are correct, but the parameter values are incorrect. Please try using different parameter values." + else: + error_msg = f"Parameter names do not match. Expected parameter names: {expected_params}, you provided: {provided_params}." + + return { + "ok": False, + "error": error_msg + } + + logger.info(f"✓ Item inputs match golden - node: {req.node_id}, activating item") + + # 标记该 Item 已被正确使用 + item_node.if_success = True + + # 将 golden_output_values 追加到 actual_outputs_history + if item_node.golden_output_values: + item_node.actual_outputs_history.append(dict(item_node.golden_output_values)) + + # 触发 ITEM 类型边的掉落 + newly_revealed = [] + for edge in scenario.edges: + if edge.source_id == item_node.id and edge.connection_type == InterfaceType.ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from use_item on {req.node_id})") + + # 检查是否为 Win Node + win_node_id = scenario.win_node_id + is_win_node = (req.node_id == win_node_id) + + # 构建返回结果 + result = { + "ok": True, + "message": "Item used successfully.", + "content": item_node.golden_output_values if item_node.golden_output_values else None + } + + # 获取 narrative(如果存在) + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + narrative = raw_nodes_data[req.node_id].get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 如果是 Win Node,只记录日志 + if is_win_node: + logger.info(f"Win node (Item) unlocked via use_item - case: {case_id}, node: {req.node_id}") + + return result + + +class SubmitAnswerRequest(BaseModel): + answer: str = Field(..., description="The victory string to submit") + +@app.post("/env/{case_id}/submit_answer") +def submit_answer(case_id: str, req: SubmitAnswerRequest): + """ + 提交答案接口 + 被测模型在获得胜利字符串提示后,需要调用此接口提交答案 + """ + logger.info(f"Submit answer request - case_id: {case_id}, answer: {req.answer}") + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + + # 获取 win_node 的 golden_output_values + if not scenario.win_node_id: + logger.error(f"No win node defined for case: {case_id}") + return { + "ok": False, + "error": "This case has no victory node defined" + } + + win_node = scenario.nodes.get(scenario.win_node_id) + if not win_node: + logger.error(f"Win node not found: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node does not exist" + } + + # 获取正确的胜利字符串(取第一个 golden_output_value) + if win_node.golden_output_values: + correct_answer = list(win_node.golden_output_values.values())[0] + else: + logger.error(f"Win node has no golden_output_values: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node has no correct answer" + } + + # 验证提交的答案 + if req.answer == correct_answer: + logger.info(f"🎉 CORRECT ANSWER SUBMITTED - case: {case_id}, answer: {req.answer}") + return { + "ok": True, + "is_win": True, + "victory_message": f"🎉 Congratulations on successfully escaping the room! Your answer is correct: {req.answer}" + } + else: + logger.info(f"❌ INCORRECT ANSWER SUBMITTED - case: {case_id}, submitted: {req.answer}, correct: {correct_answer}") + return { + "ok": True, + "is_win": False, + "error": f"The submitted answer is incorrect. You submitted: {req.answer}" + } + +if __name__ == "__main__": + + uvicorn.run(app, host="0.0.0.0", port=8000) \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-248c41a5/environment/puzzle/upstream/simulator.py b/tasks/agentescape-25-skeleton-248c41a5/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-25-skeleton-248c41a5/environment/puzzle/upstream/simulator.py @@ -0,0 +1,2911 @@ +import hashlib +import hmac +import base64 +import binascii +import zlib +import json +import uuid +import math +import re +from typing import Dict, Any, List + +class ToolSimulator: + def __init__(self): + """工具模拟器 + + 文件处理工具(zip_unzip, zip_unzip_file, zip_unzip_item, json_get, csv_query, + regex_search, graph_shortest_path)不需要真实文件系统。 + 这些工具只验证输入参数,然后返回预先初始化好的 golden_outputs。 + """ + self.tool_map = { + # 数论 + "calc_bigmul": self.calc_bigmul, + "calc_modexp": self.calc_modexp, + "calc_modexp_int": self.calc_modexp_int, + "calc_gcd": self.calc_gcd, + "calc_gcd_int": self.calc_gcd_int, + "calc_inv_mod": self.calc_inv_mod, + "calc_inv_mod_int": self.calc_inv_mod_int, + + # 哈希 + "hash_sha256": self.hash_sha256, + "hash_md5": self.hash_md5, + "hmac_sha256": self.hmac_sha256, + + # 编码 + "base64_decode": self.base64_decode, + "base64_encode": self.base64_encode, + "hex_decode": self.hex_decode, + "hex_encode": self.hex_encode, + "zlib_inflate": self.zlib_inflate, + "zlib_deflate": self.zlib_deflate, + + # 文件 + "zip_unzip": self.zip_unzip, + "zip_unzip_file": self.zip_unzip_file, + "zip_unzip_item": self.zip_unzip_item, + "regex_search": self.regex_search, + "json_get": self.json_get, + "csv_query": self.csv_query, + "code_py_exec": self.code_py_exec, + + # 图 + "graph_shortest_path": self.graph_shortest_path, + + # 加解密 (简化模拟) + "crypto_aes_cbc_decrypt": self.crypto_aes_cbc_decrypt, + "crypto_rsa_decrypt_hex": self.crypto_rsa_decrypt_hex, + + # 其他 + "num_base_convert": self.num_base_convert, + "time_convert": self.time_convert, + "checksum_crc32": self.checksum_crc32, + "geo_haversine": self.geo_haversine, + "otp_totp_generate": self.otp_totp_generate, + "unicode_norm": self.unicode_norm, + "text_bidi_sanitize": self.text_bidi_sanitize, + "text_xor_hex": self.text_xor_hex, + "text_rotN": self.text_rotN, + "luhn_check": self.luhn_check, + "iban_validate": self.iban_validate, + + # 物理 + "matter_synthesizer": self.matter_synthesizer, + + # 终端机 + "terminal_1": self.terminal_1, + "terminal_2": self.terminal_2, + "Logic Terminal": self.logic_terminal, + "Math Terminal": self.math_terminal, + "Encryption Terminal": self.crypt_terminal, + "Sequence Terminal": self.sequence_terminal + } + + def execute(self, tool_name: str, inputs: Dict[str, Any]) -> Dict[str, Any]: + if tool_name not in self.tool_map: + # Fallback for unknown tools: return dummy outputs based on expected output types + # This should ideally not happen if all tools are implemented + return {} + + try: + return self.tool_map[tool_name](inputs) + except Exception as e: + print(f"Error executing {tool_name}: {e}") + # Return empty or error indication? For generation, we might want to fail hard or return dummy. + # For now, return dummy to keep flow going, but log error. + return {} + + # --- Implementations --- + + def calc_bigmul(self, inputs): + # Check if required parameters are present + if "a" not in inputs or "b" not in inputs: + raise ValueError("Missing required parameters 'a' and/or 'b'") + + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + return {"product": str(a * b)} + except (ValueError, TypeError) as e: + raise ValueError(f"Failed to convert parameters to integers: {str(e)}") + + def calc_modexp(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + try: + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if isinstance(base, str): + base = int(base) + elif not isinstance(base, int): + raise ValueError("Parameter 'base' must be a string or integer") + + if isinstance(exp, str): + exp = int(exp) + elif not isinstance(exp, int): + raise ValueError("Parameter 'exp' must be a string or integer") + + if isinstance(mod, str): + mod = int(mod) + elif not isinstance(mod, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": str(pow(base, exp, mod))} + + def calc_modexp_int(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["base"], int): + raise ValueError("Parameter 'base' must be an integer") + if not isinstance(inputs["exp"], int): + raise ValueError("Parameter 'exp' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": pow(base, exp, mod)} + + def calc_gcd(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + # 计算 GCD 并返回字符串格式(符合 Big_Int 输出类型) + result = math.gcd(a, b) + return {"gcd": str(result)} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def calc_gcd_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["b"], int): + raise ValueError("Parameter 'b' must be an integer") + + # 获取参数 + a = inputs["a"] + b = inputs["b"] + + return {"gcd": math.gcd(a, b)} + + def calc_inv_mod(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + m = inputs["mod"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(m, str): + m = int(m) + elif not isinstance(m, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": str(pow(a, -1, m))} + except ValueError as e: + # 模逆不存在时,返回一个特殊值(用于数据传递) + # 在 DAG 生成阶段,这允许数据流继续 + return {"inv": str(a)} + + def calc_inv_mod_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + a = inputs["a"] + m = inputs["mod"] + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": pow(a, -1, m)} + except ValueError as e: + raise ValueError(f"Modular inverse does not exist: {str(e)}") + + def hash_sha256(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.sha256(text.encode()).hexdigest()} + + def hash_md5(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.md5(text.encode()).hexdigest()} + + def hmac_sha256(self, inputs): + # 参数检查 + if "hex_key" not in inputs: + raise ValueError("Missing required parameter: hex_key") + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["hex_key"], str): + raise ValueError("Parameter 'hex_key' must be a string") + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + try: + key = bytes.fromhex(inputs["hex_key"]) + text = inputs["text"].encode() + return {"hex": hmac.new(key, text, hashlib.sha256).hexdigest()} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def base64_decode(self, inputs): + # 参数检查 + if "data" not in inputs: + raise ValueError("Missing required parameter: data") + + # 类型检查 + if not isinstance(inputs["data"], str): + raise ValueError("Parameter 'data' must be a string") + + data = inputs["data"] + try: + return {"bytes_hex": binascii.hexlify(base64.b64decode(data)).decode()} + except Exception as e: + raise ValueError(f"Base64 decode error: {str(e)}") + + def base64_encode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"b64": base64.b64encode(bytes.fromhex(hex_data)).decode()} + except Exception as e: + raise ValueError(f"Base64 encode error: {str(e)}") + + def hex_decode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"text": bytes.fromhex(hex_data).decode('utf-8', errors='ignore')} + except Exception as e: + raise ValueError(f"Hex decode error: {str(e)}") + + def hex_encode(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + try: + return {"hex": text.encode().hex()} + except Exception as e: + raise ValueError(f"Hex encode error: {str(e)}") + + + # 到此处实现已经更新 + + def zlib_inflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("Parameter 'hex' must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("Missing required parameter: hex") + + try: + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空字符串 + if not hex_data: + raise ValueError("Empty hex string provided") + + # 检查十六进制字符串的有效性 + if len(hex_data) % 2 != 0: + raise ValueError("Hex string must have even length") + + # 检查是否只包含有效的十六进制字符 + if not all(c in '0123456789abcdefABCDEF' for c in hex_data): + raise ValueError("Invalid hex string provided") + + # 尝试解压缩 + return {"text": zlib.decompress(bytes.fromhex(hex_data)).decode('utf-8')} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hex string provided") from e + raise ValueError(f"Invalid zlib data: {e}") from e + except Exception as e: + raise RuntimeError(f"Failed to inflate data: {e}") from e + + def zlib_deflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("Parameter 'text' must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("Missing required parameter: text") + + try: + # 压缩文本 + return {"hex": zlib.compress(text.encode('utf-8')).hex()} + except Exception as e: + raise RuntimeError(f"Failed to deflate data: {e}") from e + + # --- File Operations --- + + def zip_unzip(self, inputs): + """ZIP 解压工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"files": golden_outputs.get("files", "")} + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return {"files": golden_outputs.get("files", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "files" in golden_outputs: + # 验证必需参数 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 检查类型 + if has_zip_id and not isinstance(zip_id, str): + return {"error": "Parameter 'zip_id' must be a string type"} + if has_password and not isinstance(password, str): + return {"error": "Parameter 'password' must be a string type"} + + # 验证输入是否与预期匹配 + if golden_inputs: + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return {"files": golden_outputs["files"]} + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + # 没有golden_inputs但有golden_outputs,直接返回输出 + return {"files": golden_outputs["files"]} + + # 如果没有预期输出,返回空结果 + return {"files": ""} + + def regex_search(self, inputs): + """正则搜索工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"matches": golden_outputs.get("matches", "[]")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "matches" in golden_outputs: + # 提取实际参数 + pattern = inputs.get("pattern") + file_id = inputs.get("file_id") + text = inputs.get("text") + + # 1. 检查必需参数 + if pattern is None: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["pattern"], + "message": "Missing required parameter 'pattern'" + } + } + + # 类型检查 + if not isinstance(pattern, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "pattern", + "message": "Parameter 'pattern' must be a string type" + } + } + if file_id is not None and not isinstance(file_id, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if text is not None and not isinstance(text, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "text", + "message": "Parameter 'text' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合 + provided_params = {} + if pattern is not None: + provided_params["pattern"] = pattern + if file_id is not None: + provided_params["file_id"] = file_id + if text is not None: + provided_params["text"] = text + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数(关键改进) + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_pattern = golden_inputs.get("pattern") + expected_file_id = golden_inputs.get("file_id") + expected_text = golden_inputs.get("text") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_pattern is not None: + if str(pattern) != str(expected_pattern): + incorrect_params.append("pattern") + else: + correct_params.append("pattern") + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_text is not None: + if str(text) != str(expected_text): + incorrect_params.append("text") + else: + correct_params.append("text") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "matches": "[]", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "matches": golden_outputs["matches"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空列表 + return {"matches": "[]"} + + def json_get(self, inputs): + """JSON 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"values": golden_outputs.get("values", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "values" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + jsonpath = inputs.get("jsonpath", "") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if jsonpath is not None and not isinstance(jsonpath, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "jsonpath", + "message": "Parameter 'jsonpath' must be a string type" + } + } + + # 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:jsonpath有默认值"") + provided_params = {} + if file_id is not None: + provided_params["file_id"] = file_id + if jsonpath != "": + provided_params["jsonpath"] = jsonpath + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_jsonpath = golden_inputs.get("jsonpath") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_jsonpath is not None: + if str(jsonpath) != str(expected_jsonpath): + incorrect_params.append("jsonpath") + else: + correct_params.append("jsonpath") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "values": "", + "_validation": validation_info + } + + # 所有验证通过,返回正确输出 + return { + "values": golden_outputs["values"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"values": ""} + + def csv_query(self, inputs): + """CSV 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"rows": golden_outputs.get("rows", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "rows" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + select_columns = inputs.get("select", "") + where_clause = inputs.get("where", "") + + # 1. 检查必需参数 + if file_id is None: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["file_id"], + "message": "Missing required parameter 'file_id'" + } + } + + # 类型检查 + if not isinstance(file_id, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if not isinstance(select_columns, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "select", + "message": "Parameter 'select' must be a string type" + } + } + if not isinstance(where_clause, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "where", + "message": "Parameter 'where' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:select和where有默认值"") + provided_params = {"file_id": file_id} + if select_columns != "": + provided_params["select"] = select_columns + if where_clause != "": + provided_params["where"] = where_clause + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_select = golden_inputs.get("select") + expected_where = golden_inputs.get("where") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_select is not None: + if str(select_columns) != str(expected_select): + incorrect_params.append("select") + else: + correct_params.append("select") + + if expected_where is not None: + if str(where_clause) != str(expected_where): + incorrect_params.append("where") + else: + correct_params.append("where") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "rows": "", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "rows": golden_outputs["rows"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"rows": ""} + + def graph_shortest_path(self, inputs): + """图最短路径工具 + + 如果有 _golden_outputs 或 _init_outputs,验证输入并返回预设输出。 + 否则执行真实的 Dijkstra 算法。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 检查是否在预设模式中(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + if golden_outputs and "path" in golden_outputs: + # 评测阶段但没有 golden_inputs,直接返回 outputs + if not golden_inputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 评测模式:验证输入参数是否匹配 golden 值 + src = inputs.get("src") + dst = inputs.get("dst") + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + + has_src = src is not None and src != "" + has_dst = dst is not None and dst != "" + + # 验证必需参数 + if not has_src or not has_dst: + missing = [] + if not has_src: + missing.append("src") + if not has_dst: + missing.append("dst") + return {"error": "Missing required parameters: " + ", ".join(missing)} + + # 类型检查 + if not isinstance(src, str): + return {"error": "Parameter 'src' must be a string"} + if not isinstance(dst, str): + return {"error": "Parameter 'dst' must be a string"} + + # 验证输入是否匹配期望值 + if golden_inputs: + expected_src = golden_inputs.get("src") + expected_dst = golden_inputs.get("dst") + expected_file_id = golden_inputs.get("file_id") + expected_graph_data = golden_inputs.get("graph_data") + + # 收集验证结果 + incorrect_params = [] + correct_params = [] + + # 检查必需参数是否匹配 + if expected_src is not None: + if str(src) != str(expected_src): + incorrect_params.append("src") + else: + correct_params.append("src") + + if expected_dst is not None: + if str(dst) != str(expected_dst): + incorrect_params.append("dst") + else: + correct_params.append("dst") + + # 检查可选参数(如果在 expected_inputs 中定义了) + if expected_file_id is not None: + if file_id != expected_file_id: + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_graph_data is not None: + if graph_data != expected_graph_data: + incorrect_params.append("graph_data") + else: + correct_params.append("graph_data") + + # 如果有参数不正确,返回详细的反馈 + if incorrect_params: + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 验证通过,返回预设的输出 + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 获取参数(真实执行路径) + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + # Support both src/dst (interface definition) and start/end (original implementation) + start = inputs.get("src") + end = inputs.get("dst") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + raise TypeError("file_id must be a string") + + if graph_data is not None and not isinstance(graph_data, str): + raise TypeError("graph_data must be a string") + + if start is not None and not isinstance(start, str): + raise TypeError("src/start must be a string") + + if end is not None and not isinstance(end, str): + raise TypeError("dst/end must be a string") + + # 检查必需参数 + if file_id is None and graph_data is None: + raise ValueError("Either file_id or graph_data must be provided") + + if start is None: + raise ValueError("src/start parameter is required") + + if end is None: + raise ValueError("dst/end parameter is required") + + # Get graph content + content = None + if file_id is not None: + # 尝试从 VFS 获取(如果存在) + if hasattr(self, 'vfs') and file_id in self.vfs: + content = self.vfs[file_id] + else: + # VFS 不存在或文件不在 VFS 中 + # 返回一个默认的空图结果,或者抛出错误提示需要 init_outputs + raise ValueError( + f"File '{file_id}' not found. For tools that require files, " + f"please provide init_outputs in the initial_values." + ) + elif graph_data is not None: + content = graph_data + + if content is None: + content = "{}" + + try: + # Parse graph data + graph = json.loads(content) + + # 类型检查 + if not isinstance(graph, dict): + raise TypeError("Graph data must be a dictionary") + + # If graph is not in the expected format, try to extract adjacency list + if "nodes" in graph and "edges" in graph: + # 验证nodes和edges的类型 + if not isinstance(graph["nodes"], list): + raise TypeError("Nodes must be a list") + + if not isinstance(graph["edges"], list): + raise TypeError("Edges must be a list") + + # Convert from nodes/edges format to adjacency list + adjacency_list = {} + for node in graph["nodes"]: + # 验证node类型 + if not isinstance(node, dict): + raise TypeError("Each node must be a dictionary") + + # Use node ID as key, not the entire node dictionary + node_id = node.get("id", "") + if node_id: + adjacency_list[node_id] = {} + + for edge in graph["edges"]: + # 验证edge类型 + if not isinstance(edge, dict): + raise TypeError("Each edge must be a dictionary") + + u = edge["from"] + v = edge["to"] + weight = edge.get("weight", 1) # Default to unweighted + + # 类型检查 + if not isinstance(u, str): + raise TypeError("Edge 'from' must be a string") + + if not isinstance(v, str): + raise TypeError("Edge 'to' must be a string") + + if not isinstance(weight, (int, float)): + raise TypeError("Edge weight must be a number") + + if u not in adjacency_list: + adjacency_list[u] = {} + if v not in adjacency_list: + adjacency_list[v] = {} + + adjacency_list[u][v] = weight + # If undirected, add reverse edge + if not edge.get("directed", False): + adjacency_list[v][u] = weight + elif isinstance(graph, dict): + # Already in adjacency list format + adjacency_list = graph + + # 验证邻接表结构 + for node, neighbors in adjacency_list.items(): + if not isinstance(neighbors, dict): + raise TypeError("Adjacency list must be a dictionary of dictionaries") + + for neighbor, weight in neighbors.items(): + if not isinstance(weight, (int, float)): + raise TypeError("Edge weights must be numbers") + else: + raise TypeError("Graph data must be a dictionary") + + # 检查起点和终点是否为空 + if not start: + raise ValueError("Start node cannot be empty") + + if not end: + raise ValueError("End node cannot be empty") + + # 检查起点和终点是否在图中 + if start not in adjacency_list: + raise ValueError(f"Start node '{start}' not found in graph") + + if end not in adjacency_list: + raise ValueError(f"End node '{end}' not found in graph") + + # Dijkstra's algorithm implementation + import heapq + + # Initialize distances and previous nodes + distances = {node: float('infinity') for node in adjacency_list} + previous = {node: None for node in adjacency_list} + distances[start] = 0 + + # Priority queue + pq = [(0, start)] + heapq.heapify(pq) + + while pq: + current_dist, current_node = heapq.heappop(pq) + + # If we've reached the end node, we can break early + if current_node == end: + break + + # Nodes can be added multiple times to the priority queue, but we only process them once + if current_dist > distances[current_node]: + continue + + # Explore neighbors + for neighbor, weight in adjacency_list[current_node].items(): + distance = current_dist + weight + + # If a shorter path is found + if distance < distances[neighbor]: + distances[neighbor] = distance + previous[neighbor] = current_node + heapq.heappush(pq, (distance, neighbor)) + + # Reconstruct the shortest path + path = [] + current = end + while current is not None: + path.append(current) + current = previous[current] + path.reverse() # Reverse to get from start to end + + # Check if path exists + if not path or path[0] != start: + return {"path": "[]", "cost": 0} + + return { + "path": json.dumps(path), + "cost": distances[end] + } + except json.JSONDecodeError as e: + raise ValueError(f"Invalid JSON in graph data: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in graph_shortest_path: {str(e)}") + + # --- Crypto (Simplified) --- + def crypto_aes_cbc_decrypt(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 (使用模板中定义的参数名) + hex_cipher = inputs.get("hex_cipher") + hex_key = inputs.get("hex_key") + hex_iv = inputs.get("hex_iv") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + + if hex_key is not None and not isinstance(hex_key, str): + raise TypeError("hex_key must be a string") + + if hex_iv is not None and not isinstance(hex_iv, str): + raise TypeError("hex_iv must be a string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + + if hex_key is None: + raise ValueError("hex_key parameter is required") + + if hex_iv is None: + raise ValueError("hex_iv parameter is required") + + from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes + from cryptography.hazmat.backends import default_backend + from cryptography.hazmat.primitives import padding + + try: + # Convert hex strings to bytes + ciphertext = bytes.fromhex(hex_cipher) + key = bytes.fromhex(hex_key) + iv = bytes.fromhex(hex_iv) + + # Validate key length (AES-128, AES-192, AES-256) + if len(key) not in [16, 24, 32]: + raise ValueError("Invalid key length. Must be 16, 24, or 32 bytes.") + + if len(iv) != 16: + raise ValueError("Invalid IV length. Must be 16 bytes.") + + # Create cipher object + cipher = Cipher( + algorithms.AES(key), + modes.CBC(iv), + backend=default_backend() + ) + + decryptor = cipher.decryptor() + + # Decrypt the ciphertext + padded_plaintext = decryptor.update(ciphertext) + decryptor.finalize() + + # Remove PKCS7 padding + unpadder = padding.PKCS7(128).unpadder() + plaintext = unpadder.update(padded_plaintext) + unpadder.finalize() + + # Return decrypted text + return {"text": plaintext.decode('utf-8', errors='ignore')} + except ValueError as e: + if "non-hexadecimal number found in fromhex()" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher, hex_key, or hex_iv") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in crypto_aes_cbc_decrypt: {str(e)}") + + def crypto_rsa_decrypt_hex(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_cipher = inputs.get("hex_cipher") + n = inputs.get("n") + d = inputs.get("d") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + if n is not None and not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + if d is not None and not isinstance(d, (int, str)): + raise TypeError("d must be an integer or string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + if n is None: + raise ValueError("n parameter is required") + if d is None: + raise ValueError("d parameter is required") + + try: + # Convert parameters to appropriate types + cipher_int = int(hex_cipher, 16) + n_int = int(n) if isinstance(n, str) else n + d_int = int(d) if isinstance(d, str) else d + + # RSA decryption: plaintext = ciphertext^d mod n + plaintext_int = pow(cipher_int, d_int, n_int) + + # Convert result to hex and then to text + plaintext_hex = hex(plaintext_int)[2:] + + # Pad with leading zero if odd length + if len(plaintext_hex) % 2 != 0: + plaintext_hex = '0' + plaintext_hex + + # Convert hex to bytes and then to text + try: + plaintext_bytes = bytes.fromhex(plaintext_hex) + plaintext_text = plaintext_bytes.decode('utf-8', errors='ignore') + except: + # If decoding fails, return hex representation + plaintext_text = plaintext_hex + + return {"text": plaintext_text} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in crypto_rsa_decrypt_hex: {str(e)}") + + # --- Others --- + def num_base_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + s = inputs.get("s") + from_base = inputs.get("from_base") + to_base = inputs.get("to_base") + + # 类型检查 - 接受 str 或 int + if s is not None and not isinstance(s, (str, int)): + raise TypeError("s must be a string or integer") + + if from_base is not None and not isinstance(from_base, (int, str)): + raise TypeError("from_base must be an integer") + + if to_base is not None and not isinstance(to_base, (int, str)): + raise TypeError("to_base must be an integer") + + # 检查必需参数 + if s is None: + raise ValueError("s parameter is required") + + if from_base is None: + raise ValueError("from_base parameter is required") + + if to_base is None: + raise ValueError("to_base parameter is required") + + try: + # Convert to int if needed + from_base = int(from_base) if isinstance(from_base, str) else from_base + to_base = int(to_base) if isinstance(to_base, str) else to_base + s_str = str(s) + + # 验证基数范围 + if from_base < 2 or from_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + if to_base < 2 or to_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + # Convert from source base to decimal + val = int(s_str, from_base) + + # Convert from decimal to target base + if to_base == 10: + result = str(val) + elif to_base == 16: + result = hex(val)[2:] + elif to_base == 8: + result = oct(val)[2:] + elif to_base == 2: + result = bin(val)[2:] + else: + # Generic base conversion for other bases + if val == 0: + result = "0" + else: + digits = "0123456789abcdefghijklmnopqrstuvwxyz" + result = "" + n = abs(val) + while n: + result = digits[n % to_base] + result + n //= to_base + if val < 0: + result = "-" + result + + return {"str": result} + except ValueError as e: + raise ValueError(f"Invalid number format: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in num_base_convert: {str(e)}") + + def time_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iso = inputs.get("iso") + timestamp = inputs.get("timestamp") + datetime_str = inputs.get("datetime") + from_tz = inputs.get("from_tz") + to_tz = inputs.get("to_tz") + format_str = inputs.get("format") + + # 类型检查 + if iso is not None and not isinstance(iso, str): + raise TypeError("iso must be a string") + + if timestamp is not None and not isinstance(timestamp, (str, int, float)): + raise TypeError("timestamp must be a string, integer, or float") + + if datetime_str is not None and not isinstance(datetime_str, str): + raise TypeError("datetime must be a string") + + if from_tz is not None and not isinstance(from_tz, str): + raise TypeError("from_tz must be a string") + + if to_tz is not None and not isinstance(to_tz, str): + raise TypeError("to_tz must be a string") + + if format_str is not None and not isinstance(format_str, str): + raise TypeError("format must be a string") + + # 设置默认值 + if from_tz is None: + from_tz = "UTC" + + if to_tz is None: + to_tz = "UTC" + + import datetime + import pytz + + # 验证时区参数 + try: + if from_tz: + pytz.timezone(from_tz) + if to_tz: + pytz.timezone(to_tz) + except Exception: + raise ValueError("Invalid timezone provided") + + try: + # Parse input time + dt = None + + if iso is not None: + # Parse ISO 8601 format + dt = datetime.datetime.fromisoformat(iso.replace('Z', '+00:00')) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=pytz.UTC) + elif timestamp is not None: + # Parse Unix timestamp + timestamp = float(timestamp) + dt = datetime.datetime.fromtimestamp(timestamp, pytz.UTC) + elif datetime_str is not None: + # Parse datetime string + # Try common formats + formats_to_try = [ + "%Y-%m-%d %H:%M:%S", + "%Y-%m-%d %H:%M:%S.%f", + "%Y-%m-%d", + "%m/%d/%Y %H:%M:%S", + "%m/%d/%Y" + ] + + parse_success = False + for fmt in formats_to_try: + try: + dt = datetime.datetime.strptime(datetime_str, fmt) + dt = pytz.timezone(from_tz).localize(dt) + parse_success = True + break + except ValueError: + continue + + if not parse_success: + raise ValueError("Unable to parse datetime string with common formats") + else: + # 如果没有提供任何时间参数,则使用当前时间 + dt = datetime.datetime.now(pytz.UTC) + except ValueError as e: + raise ValueError(f"Error parsing time input: {str(e)}") + except Exception as e: + raise RuntimeError(f"Unexpected error parsing time input: {str(e)}") + + try: + # Convert timezone + if from_tz != to_tz: + dt = dt.astimezone(pytz.timezone(to_tz)) + + # Format outputs + result = { + "iso": dt.isoformat(), + "timestamp": str(dt.timestamp()), + "datetime": dt.strftime("%Y-%m-%d %H:%M:%S"), + "date": dt.strftime("%Y-%m-%d"), + "time": dt.strftime("%H:%M:%S"), + "timezone": to_tz + } + + # Add custom format if requested + if format_str: + try: + result["formatted"] = dt.strftime(format_str) + except ValueError as e: + raise ValueError(f"Invalid format string: {str(e)}") + + return result + except Exception as e: + raise RuntimeError(f"Error in time_convert: {str(e)}") + + def checksum_crc32(self, inputs): + import zlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("hex must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("hex parameter is required") + + try: + # 验证十六进制字符串 + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空 + if not hex_data: + raise ValueError("hex data cannot be empty") + + # 检查是否为有效的十六进制字符串 + if not all(c in "0123456789abcdefABCDEF" for c in hex_data): + raise ValueError("hex must be a valid hexadecimal string") + + # 检查长度是否为偶数 + if len(hex_data) % 2 != 0: + raise ValueError("hex must have even number of characters") + + val = zlib.crc32(bytes.fromhex(hex_data)) + # 确保 hex 输出是 8 位,前导补 0 + return {"hex": f"{val:08x}", "int": val} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in checksum_crc32: {str(e)}") + + def geo_haversine(self, inputs): + import math + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + lat1 = inputs.get("lat1") + lon1 = inputs.get("lon1") + lat2 = inputs.get("lat2") + lon2 = inputs.get("lon2") + + # 类型检查 + if lat1 is not None and not isinstance(lat1, (int, float, str)): + raise TypeError("lat1 must be a number or string") + if lon1 is not None and not isinstance(lon1, (int, float, str)): + raise TypeError("lon1 must be a number or string") + if lat2 is not None and not isinstance(lat2, (int, float, str)): + raise TypeError("lat2 must be a number or string") + if lon2 is not None and not isinstance(lon2, (int, float, str)): + raise TypeError("lon2 must be a number or string") + + # 检查必需参数 + if lat1 is None: + raise ValueError("lat1 parameter is required") + if lon1 is None: + raise ValueError("lon1 parameter is required") + if lat2 is None: + raise ValueError("lat2 parameter is required") + if lon2 is None: + raise ValueError("lon2 parameter is required") + + try: + # 转换为浮点数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(lat1, str): + lat1 = float(lat1) + elif not isinstance(lat1, (int, float)): + raise TypeError("lat1 must be a number or string") + else: + lat1 = float(lat1) + + if isinstance(lon1, str): + lon1 = float(lon1) + elif not isinstance(lon1, (int, float)): + raise TypeError("lon1 must be a number or string") + else: + lon1 = float(lon1) + + if isinstance(lat2, str): + lat2 = float(lat2) + elif not isinstance(lat2, (int, float)): + raise TypeError("lat2 must be a number or string") + else: + lat2 = float(lat2) + + if isinstance(lon2, str): + lon2 = float(lon2) + elif not isinstance(lon2, (int, float)): + raise TypeError("lon2 must be a number or string") + else: + lon2 = float(lon2) + + # Validate coordinates (approximate range check) + if not (-90 <= lat1 <= 90): + raise ValueError("lat1 must be between -90 and 90") + if not (-90 <= lat2 <= 90): + raise ValueError("lat2 must be between -90 and 90") + if not (-180 <= lon1 <= 180): + raise ValueError("lon1 must be between -180 and 180") + if not (-180 <= lon2 <= 180): + raise ValueError("lon2 must be between -180 and 180") + + # Earth radius in meters + R = 6371000 # Approximate radius of Earth + + # Convert degrees to radians + lat1_rad = math.radians(lat1) + lon1_rad = math.radians(lon1) + lat2_rad = math.radians(lat2) + lon2_rad = math.radians(lon2) + + # Calculate differences + delta_lat = lat2_rad - lat1_rad + delta_lon = lon2_rad - lon1_rad + + # Haversine formula + a = math.sin(delta_lat / 2) ** 2 + \ + math.cos(lat1_rad) * math.cos(lat2_rad) * \ + math.sin(delta_lon / 2) ** 2 + c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) + distance_m = R * c + + # Return distance in meters + return {"meters": round(distance_m, 2)} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in geo_haversine: {str(e)}") + + def otp_totp_generate(self, inputs): + import hmac + import hashlib + import base64 + import time + import struct + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + base32_secret = inputs.get("base32_secret") + step = inputs.get("step", 30) # Default to 30 seconds + digits = inputs.get("digits", 6) # Default to 6 digits + timestamp_iso = inputs.get("timestamp_iso", "") + algo = inputs.get("algo", "sha1") # Default to sha1 as current implementation only supports this + + # 类型检查 + if base32_secret is not None and not isinstance(base32_secret, str): + raise TypeError("base32_secret must be a string") + if not isinstance(step, (int, str)): + raise TypeError("step must be an integer or string") + if not isinstance(digits, (int, str)): + raise TypeError("digits must be an integer or string") + if not isinstance(timestamp_iso, str): + raise TypeError("timestamp_iso must be a string") + if not isinstance(algo, str): + raise TypeError("algo must be a string") + + # 检查必需参数 + if base32_secret is None: + raise ValueError("base32_secret parameter is required") + + try: + # Convert step and digits to appropriate types + step = int(step) + digits = int(digits) + if digits < 6 or digits > 8: + raise ValueError("Digits must be between 6 and 8") + + # Convert timestamp_iso to integer timestamp + if timestamp_iso: + import datetime + dt = datetime.datetime.fromisoformat(timestamp_iso.replace('Z', '+00:00')) + timestamp = int(dt.timestamp()) + else: + timestamp = int(time.time()) + + # Calculate counter value (T = floor(timestamp / step)) + counter = timestamp // step + + # Decode the base32 secret + # Add padding if necessary (base64 requires padding to be multiple of 8) + base32_secret = base32_secret.upper().replace(' ', '') + if len(base32_secret) % 8 != 0: + base32_secret += '=' * (8 - (len(base32_secret) % 8)) + key = base64.b32decode(base32_secret, casefold=True) + + # Calculate HMAC-SHA1 + counter_bytes = struct.pack('>Q', counter) # Big-endian 8-byte integer + hmac_hash = hmac.new(key, counter_bytes, hashlib.sha1).digest() + + # Dynamic truncation + offset = hmac_hash[-1] & 0xF + code = struct.unpack('>I', hmac_hash[offset:offset+4])[0] & 0x7FFFFFFF + + # Generate the OTP + otp = str(code % (10 ** digits)).zfill(digits) + + # Calculate remaining time until next OTP change + remaining_time = step - (timestamp % step) + + return {"totp": otp, "remaining_time": remaining_time, "time_step": step} + except ValueError as e: + if "invalid literal for int()" in str(e): + raise ValueError("step and digits must be valid integers") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in otp_totp_generate: {str(e)}") + + def unicode_norm(self, inputs): + import unicodedata + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + form = inputs.get("form", "NFC") # Default to NFC + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if form is not None and not isinstance(form, str): + raise TypeError("form must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Normalize form (NFC, NFD, NFKC, NFKD) + form = form.upper().strip() + + if form not in ['NFC', 'NFD', 'NFKC', 'NFKD']: + raise ValueError(f"Invalid normalization form: {form}. Must be one of: NFC, NFD, NFKC, NFKD") + + # Apply Unicode normalization + normalized_text = unicodedata.normalize(form, text) + + return {"text": normalized_text} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in unicode_norm: {str(e)}") + + def text_bidi_sanitize(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Bidi control characters to remove + bidi_controls = [ + '\u200E', # LEFT-TO-RIGHT MARK + '\u200F', # RIGHT-TO-LEFT MARK + '\u202A', # LEFT-TO-RIGHT EMBEDDING + '\u202B', # RIGHT-TO-LEFT EMBEDDING + '\u202C', # POP DIRECTIONAL FORMATTING + '\u202D', # LEFT-TO-RIGHT OVERRIDE + '\u202E', # RIGHT-TO-LEFT OVERRIDE + '\u2066', # LEFT-TO-RIGHT ISOLATE + '\u2067', # RIGHT-TO-LEFT ISOLATE + '\u2068', # FIRST STRONG ISOLATE + '\u2069', # POP DIRECTIONAL ISOLATE + ] + + # Remove all Bidi control characters + sanitized_text = text + for control_char in bidi_controls: + sanitized_text = sanitized_text.replace(control_char, '') + + return {"text": sanitized_text} + except Exception as e: + raise RuntimeError(f"Error in text_bidi_sanitize: {str(e)}") + + def text_xor_hex(self, inputs): + import binascii + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_a = inputs.get("hex_a") + hex_b = inputs.get("hex_b") + + # 类型检查 + if hex_a is not None and not isinstance(hex_a, str): + raise TypeError("hex_a must be a string") + if hex_b is not None and not isinstance(hex_b, str): + raise TypeError("hex_b must be a string") + + # 检查必需参数 + if hex_a is None: + raise ValueError("hex_a parameter is required") + if hex_b is None: + raise ValueError("hex_b parameter is required") + + try: + # Remove any whitespace + hex_a = hex_a.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + hex_b = hex_b.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + + # Validate hex strings + if not (all(c in "0123456789abcdefABCDEF" for c in hex_a) and len(hex_a) % 2 == 0): + raise ValueError("hex_a must be a valid hexadecimal string with even length") + if not (all(c in "0123456789abcdefABCDEF" for c in hex_b) and len(hex_b) % 2 == 0): + raise ValueError("hex_b must be a valid hexadecimal string with even length") + + # Convert hex strings to bytes + bytes_a = binascii.unhexlify(hex_a) + bytes_b = binascii.unhexlify(hex_b) + + # Make the byte arrays the same length by padding the shorter one with zeros + max_len = max(len(bytes_a), len(bytes_b)) + bytes_a = bytes_a.ljust(max_len, b'\x00') + bytes_b = bytes_b.ljust(max_len, b'\x00') + + # Perform XOR operation + result_bytes = bytes(a ^ b for a, b in zip(bytes_a, bytes_b)) + + # Convert result back to hex + result_hex = binascii.hexlify(result_bytes).decode('utf-8') + + return {"hex": result_hex} + except ValueError as e: + if "Non-hexadecimal digit found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in text_xor_hex: {str(e)}") + + def text_rotN(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + n = inputs.get("n", 0) + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + n = int(n) + except ValueError: + raise ValueError("n must be a valid integer") + + result = [] + for char in text: + if char.isupper(): + # Rotate uppercase letters + result_char = chr((ord(char) - ord('A') + n) % 26 + ord('A')) + result.append(result_char) + elif char.islower(): + # Rotate lowercase letters + result_char = chr((ord(char) - ord('a') + n) % 26 + ord('a')) + result.append(result_char) + else: + # Keep non-alphabetic characters unchanged + result.append(char) + + return {"text": ''.join(result)} + + def luhn_check(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数(支持 card_number 和 number 两个参数名) + card_number = inputs.get("number") or inputs.get("card_number") + + # 类型检查 + if card_number is not None and not isinstance(card_number, str): + raise TypeError("number must be a string") + + # 检查必需参数 + if card_number is None: + raise ValueError("number parameter is required") + + try: + # 如果输入是JSON数组或其他非数字字符串,返回该字符串本身(用于数据传递) + # 这种情况发生在DAG设计中类型不匹配时 + if card_number.startswith('[') or card_number.startswith('{'): + # 输入是JSON,直接返回原值(用于传递) + return {"valid": card_number} + + # Remove whitespace from card number + card_number = card_number.replace(" ", "").replace("-", "") + + # Check if card number is all digits + if not card_number.isdigit() or len(card_number) < 13: + return {"valid": "false"} + + # Implement Luhn algorithm + total = 0 + reverse_digits = card_number[::-1] # Reverse the number for easier processing + + for i, digit in enumerate(reverse_digits): + num = int(digit) + if i % 2 == 1: # Every second digit starting from the right (which is first in reversed string) + num *= 2 + if num > 9: + num -= 9 # Equivalent to sum of digits for 2-digit numbers + total += num + + # Check if total is divisible by 10 + is_valid = total % 10 == 0 + return {"valid": "true" if is_valid else "false"} + except Exception as e: + raise RuntimeError(f"Error in luhn_check: {str(e)}") + + def iban_validate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iban = inputs.get("iban") + + # 类型检查 + if iban is not None and not isinstance(iban, str): + raise TypeError("iban must be a string") + + # 检查必需参数 + if iban is None: + raise ValueError("iban parameter is required") + + try: + # Remove whitespace from IBAN + iban = iban.replace(" ", "") + + # Basic length and format check + if not (len(iban) >= 15 and len(iban) <= 34): + return {"valid": "False"} + + if not (iban[:2].isalpha() and iban[2:].isdigit()): + return {"valid": "False"} + + # Move first four characters to the end + rearranged = iban[4:] + iban[:4] + + # Replace letters with numbers (A=10, B=11, ..., Z=35) + numeric_iban = '' + for char in rearranged: + if char.isdigit(): + numeric_iban += char + else: + numeric_iban += str(ord(char.upper()) - ord('A') + 10) + + # Perform modulo 97 check + # Use step-by-step approach for very large numbers + remainder = 0 + for char in numeric_iban: + remainder = (remainder * 10 + int(char)) % 97 + + is_valid = remainder == 1 + return {"valid": "True" if is_valid else "False"} + except Exception as e: + raise RuntimeError(f"Error in iban_validate: {str(e)}") + + def matter_synthesizer(self, inputs): + import hashlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + blueprint = inputs.get("blueprint") + + # 类型检查 + if blueprint is not None and not isinstance(blueprint, str): + raise TypeError("blueprint must be a string") + + try: + # Get blueprint parameter as defined in interface + if blueprint is None: + blueprint = "" + + # Generate a unique item ID based on the blueprint + # This ensures the same blueprint always produces the same item + blueprint_hash = hashlib.sha256(blueprint.encode()).hexdigest()[:16] + + # Create a synthesized item with a deterministic ID based on blueprint + synthesized_item = f"synthesized_item_{blueprint_hash}" + + return {"output_slot": synthesized_item} + except Exception as e: + raise RuntimeError(f"Error in matter_synthesizer: {str(e)}") + + # --- Terminal Implementations --- + def terminal_1(self, inputs): + """ + terminal_1: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 只返回 text_output + - 只输入正确的 slot_b → 只返回 hex_output + - 同时输入正确的 slot_a 和 slot_b → 返回 item_dispenser(物品掉落) + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + # 检查哪些输入被提供了 + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值是否正确(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + expected_a = golden_inputs["slot_a"] + a_valid = str(slot_a) == str(expected_a) + + if has_b and "slot_b" in golden_inputs: + expected_b = golden_inputs["slot_b"] + b_valid = str(slot_b) == str(expected_b) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 item_dispenser + if has_a and has_b: + if a_valid and b_valid: + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 text_output + if has_a and not has_b: + if a_valid: + if "text_output" in golden_outputs: + result["text_output"] = golden_outputs["text_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 hex_output + if has_b and not has_a: + if b_valid: + if "hex_output" in golden_outputs: + result["hex_output"] = golden_outputs["hex_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def terminal_2(self, inputs): + """ + terminal_2: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 text_result + - 同时输入正确的 num1 和 num2 → 返回 hex_result 和 math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + # 检查哪些输入被提供了 + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值是否正确(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + expected_num1 = golden_inputs["num1"] + num1_valid = str(num1) == str(expected_num1) + + if has_num2 and "num2" in golden_inputs: + expected_num2 = golden_inputs["num2"] + num2_valid = str(num2) == str(expected_num2) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 hex_result 和 math_token + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 text_result + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "text_result" in golden_outputs: + result["text_result"] = golden_outputs["text_result"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def logic_terminal(self, inputs): + """ + Logic Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 返回 screen(部分输出) + - 只输入正确的 slot_b → 返回 screen 和 secondary_output + - 同时输入正确的 slot_a 和 slot_b → 返回 screen, secondary_output, item_dispenser + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + a_valid = str(slot_a) == str(golden_inputs["slot_a"]) + + if has_b and "slot_b" in golden_inputs: + b_valid = str(slot_b) == str(golden_inputs["slot_b"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出(包括 item_dispenser) + if has_a and has_b: + if a_valid and b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 screen(部分输出) + if has_a and not has_b: + if a_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 screen 和 secondary_output + if has_b and not has_a: + if b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def math_terminal(self, inputs): + """ + Math Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 result_display + - 同时输入正确的 num1 和 num2 → 返回 result_display, hex_result, math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + num1_valid = str(num1) == str(golden_inputs["num1"]) + + if has_num2 and "num2" in golden_inputs: + num2_valid = str(num2) == str(golden_inputs["num2"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 result_display + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def crypt_terminal(self, inputs): + """ + Encryption Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 plaintext → 返回 status(部分输出) + - 同时输入正确的 plaintext 和 key → 返回 status, encrypted_hex, encryption_chip + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + plaintext = inputs.get("plaintext") + key = inputs.get("key") + + has_plaintext = plaintext is not None and plaintext != "" + has_key = key is not None and key != "" + + # 验证输入值(与 golden values 比较) + plaintext_valid = False + key_valid = False + + if has_plaintext and "plaintext" in golden_inputs: + plaintext_valid = str(plaintext) == str(golden_inputs["plaintext"]) + + if has_key and "key" in golden_inputs: + key_valid = str(key) == str(golden_inputs["key"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_plaintext and has_key: + if plaintext_valid and key_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + if "encrypted_hex" in golden_outputs: + result["encrypted_hex"] = golden_outputs["encrypted_hex"] + if "encryption_chip" in golden_outputs: + result["encryption_chip"] = golden_outputs["encryption_chip"] + return result + else: + incorrect_params = [] + correct_params = [] + if not plaintext_valid: + incorrect_params.append("plaintext") + else: + correct_params.append("plaintext") + if not key_valid: + incorrect_params.append("key") + else: + correct_params.append("key") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 plaintext 且正确 → 返回 status(部分输出) + if has_plaintext and not has_key: + if plaintext_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: plaintext"} + + # 只提供 key 但没有 plaintext + if has_key and not has_plaintext: + return {"error": "plaintext required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + def sequence_terminal(self, inputs): + """ + Sequence Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 sequence → 返回 verification(部分输出) + - 同时输入正确的 sequence 和 checksum → 返回 verification, auth_code, access_card + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + sequence = inputs.get("sequence") + checksum = inputs.get("checksum") + + has_sequence = sequence is not None and sequence != "" + has_checksum = checksum is not None and checksum != "" + + # 验证输入值(与 golden values 比较) + sequence_valid = False + checksum_valid = False + + if has_sequence and "sequence" in golden_inputs: + sequence_valid = str(sequence) == str(golden_inputs["sequence"]) + + if has_checksum and "checksum" in golden_inputs: + checksum_valid = str(checksum) == str(golden_inputs["checksum"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_sequence and has_checksum: + if sequence_valid and checksum_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + if "auth_code" in golden_outputs: + result["auth_code"] = golden_outputs["auth_code"] + if "access_card" in golden_outputs: + result["access_card"] = golden_outputs["access_card"] + return result + else: + incorrect_params = [] + correct_params = [] + if not sequence_valid: + incorrect_params.append("sequence") + else: + correct_params.append("sequence") + if not checksum_valid: + incorrect_params.append("checksum") + else: + correct_params.append("checksum") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 sequence 且正确 → 返回 verification(部分输出) + if has_sequence and not has_checksum: + if sequence_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: sequence"} + + # 只提供 checksum 但没有 sequence + if has_checksum and not has_sequence: + return {"error": "sequence required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + # --- Additional File Tools --- + + def zip_unzip_file(self, inputs): + """ZIP 解压文件工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def zip_unzip_item(self, inputs): + """ZIP 解压道具工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def code_py_exec(self, inputs): + """Python 代码执行工具 + + 这是一个真实执行的工具,在 DAG 生成阶段和运行时评测阶段都会执行代码。 + 输入: code (Python 代码字符串) + 输出: stdout (标准输出,包含执行结果和错误信息) + + 特殊行为: + - 如果代码定义了 main() 函数,会自动调用它 + - 如果执行出错,错误信息会包含在 stdout 中 + """ + code = inputs.get("code", "") + + if not code: + return {"stdout": "Error: No code provided"} + + try: + # 创建一个受限的执行环境 + import io + import sys + + # 捕获标准输出和标准错误 + old_stdout = sys.stdout + old_stderr = sys.stderr + sys.stdout = io.StringIO() + sys.stderr = io.StringIO() + + # 执行代码 + exec_globals = {"__builtins__": __builtins__} + exec_locals = {} + exec(code, exec_globals, exec_locals) + + # 如果定义了 main() 函数,自动调用它 + if 'main' in exec_locals and callable(exec_locals['main']): + exec_locals['main']() + + # 获取输出 + stdout_value = sys.stdout.getvalue() + stderr_value = sys.stderr.getvalue() + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 合并 stdout 和 stderr + output = stdout_value + if stderr_value: + output += ("\n" if output else "") + f"[stderr] {stderr_value}" + + # 如果没有任何输出,尝试返回 result 变量的值 + if not output: + result = exec_locals.get("_result") or exec_locals.get("result") + if result is not None: + output = str(result) + + return {"stdout": output if output else "(no output)"} + + except Exception as e: + # 恢复标准输出和错误输出 + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 返回错误信息 + return {"stdout": f"Error: {type(e).__name__}: {str(e)}"} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-248c41a5/environment/puzzle/worker.Dockerfile b/tasks/agentescape-25-skeleton-248c41a5/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-25-skeleton-248c41a5/environment/puzzle/worker.Dockerfile @@ -0,0 +1,8 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends libseccomp2 && rm -rf /var/lib/apt/lists/* +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY worker.py child.py /app/ +COPY upstream/simulator.py /app/simulator.py +CMD ["uvicorn", "worker:app", "--host", "0.0.0.0", "--port", "8001", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-25-skeleton-248c41a5/environment/puzzle/worker.py b/tasks/agentescape-25-skeleton-248c41a5/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-25-skeleton-248c41a5/environment/puzzle/worker.py @@ -0,0 +1,73 @@ +"""Stateless Python tool worker. Never receives a scenario or reference values.""" + +import json +import os +import signal +import subprocess +import sys +import tempfile +import threading + +from fastapi import FastAPI +from pydantic import BaseModel, ConfigDict + +app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) +lock = threading.Lock() + + +class Execution(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + code: str + + +@app.get("/health") +def health(): + return {"ok": True} + + +@app.post("/execute") +def execute(request: Execution): + if len(request.code.encode()) > 65536: + return {"stdout": "Error: code exceeds 64 KiB limit"} + with lock, tempfile.TemporaryDirectory(prefix="escape-code-") as directory: + os.chown(directory, 65534, 65534) + with tempfile.TemporaryFile() as output: + process = subprocess.Popen( + [sys.executable, "-I", "/app/child.py"], + stdin=subprocess.PIPE, + stdout=output, + stderr=subprocess.DEVNULL, + cwd=directory, + user=65534, + group=65534, + extra_groups=[], + start_new_session=True, + env={"PATH": "/usr/local/bin:/usr/bin:/bin"}, + ) + try: + process.communicate( + json.dumps({"code": request.code}).encode(), timeout=5 + ) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + return {"stdout": "Error: Python execution timed out"} + finally: + # Also remove children still in the process group after normal exit. + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + output.seek(0) + value = output.read(65537) + if len(value) > 65536 or process.returncode != 0: + return { + "stdout": "Error: Python execution exceeded a resource limit or failed" + } + try: + result = json.loads(value) + if not isinstance(result.get("stdout"), str): + raise ValueError("Invalid worker response") + return result + except (ValueError, AttributeError): + return {"stdout": "Error: Python execution returned invalid output"} diff --git a/tasks/agentescape-25-skeleton-248c41a5/instruction.md b/tasks/agentescape-25-skeleton-248c41a5/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-25-skeleton-248c41a5/instruction.md @@ -0,0 +1,18 @@ +# Escape the room + +Discover the victory string and submit it with `escape submit-answer`. +Start with `escape observe`. This returns the room, available information, visible entities, and victory node ID. + +Use these commands (JSON responses): + +```sh +escape investigate NODE_ID +escape tool-call NODE_ID --arguments-json '{"parameter": "value"}' +escape use-item NODE_ID --arguments-json '{"parameter": "value"}' +escape submit-answer 'exact victory string' +escape state +``` + +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. + +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. diff --git a/tasks/agentescape-25-skeleton-248c41a5/solution/oracle.py b/tasks/agentescape-25-skeleton-248c41a5/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-25-skeleton-248c41a5/solution/oracle.py @@ -0,0 +1,133 @@ +"""Reference solver: use trusted inputs, but obtain the answer through public actions.""" + +import json +import urllib.request +from pathlib import Path + + +def http_action(base_url, payload): + request = urllib.request.Request( + base_url + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(request, timeout=30) as response: + return json.load(response) + + +def solve(scenario, act, observe): + nodes = {node["id"]: node for node in scenario["nodes"]} + visible = {entity["id"] for entity in observe["available_entities"]} + solved = set() + seen_outputs = {} + action_count = 0 + + def call(payload): + nonlocal action_count + action_count += 1 + response = act(payload) + visible.update(entity["id"] for entity in response.get("newly_revealed", [])) + if ( + response.get("episode", {}).get("termination_reason") + == "infrastructure_error" + ): + raise RuntimeError("Infrastructure failure") + return response + + for _round in range(len(nodes) + 2): + progress = False + for node_id, node in nodes.items(): + if node_id not in visible or node_id in solved: + continue + # Preserve graph order for data inputs; trigger/drop edges express visibility. + predecessors = [ + edge["source_id"] + for edge in scenario["edges"] + if edge["target_id"] == node_id + and edge["connection_type"] not in ("Item", "Hidden_Item") + ] + if any(pred not in solved for pred in predecessors): + continue + info = call({"action": "investigate", "node_id": node_id}) + if not info.get("ok"): + raise RuntimeError(f"Investigation failed: {node_id}: {info}") + inputs = { + port["name"]: port["value"] + for port in node.get("inputs", []) + if "value" in port + } + if node["type"] == "Tool": + result = call( + {"action": "tool_call", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok") or result.get("output_values", {}).get("error"): + raise RuntimeError(f"Tool failed: {node_id}: {result}") + output = result.get("output_values", {}) + if node.get("template_id") in ("terminal_1", "terminal_2"): + slots = { + port["name"]: inputs[port["name"]] + for port in node["inputs"] + if port["type"] not in ("Item", "Hidden_Item") + and port["name"] in inputs + } + triggers = { + key: value for key, value in inputs.items() if key not in slots + } + for key, value in slots.items(): + partial = call( + { + "action": "tool_call", + "node_id": node_id, + "arguments": {**triggers, key: value}, + } + ) + if partial.get("ok"): + output.update(partial.get("output_values", {})) + # HIDDEN_ITEM tool drops only occur on subsequent investigation. + call({"action": "investigate", "node_id": node_id}) + elif info.get("required_inputs"): + result = call( + {"action": "use_item", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok"): + raise RuntimeError(f"Item failed: {node_id}: {result}") + output = result.get("content") + else: + output = info.get("content") + seen_outputs[node_id] = output + solved.add(node_id) + progress = True + win_id = scenario["metadata"]["win_node_id"] + if win_id in solved and (len(solved) == len(nodes) or not progress): + outputs = seen_outputs[win_id] + if not outputs: + raise RuntimeError(f"Victory node returned no output: {win_id}") + # Upstream grades its first stored output port, independent of response order. + victory_port = next( + port["name"] for port in nodes[win_id]["outputs"] if "value" in port + ) + answer = outputs[victory_port] if isinstance(outputs, dict) else outputs + result = call({"action": "submit_answer", "answer": answer}) + if not result.get("is_win"): + raise RuntimeError(f"Victory submission failed: {result}") + return {"won": True, "actions": action_count, "visited_nodes": len(solved)} + if not progress: + raise RuntimeError(f"No progress: visible={visible}, solved={solved}") + raise RuntimeError("Reference solver exceeded graph traversal limit") + + +if __name__ == "__main__": + import os + + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000") + with urllib.request.urlopen(base + "/observation", timeout=20) as response: + observation = json.load(response) + print( + json.dumps( + solve( + json.loads(Path("/solution/scenario.json").read_text()), + lambda payload: http_action(base, payload), + observation, + ) + ) + ) diff --git a/tasks/agentescape-25-skeleton-248c41a5/solution/scenario.json b/tasks/agentescape-25-skeleton-248c41a5/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..9a8c02c3c9539e8d7715f27f4bb70767824c4133 --- /dev/null +++ b/tasks/agentescape-25-skeleton-248c41a5/solution/scenario.json @@ -0,0 +1,1487 @@ +{ + "metadata": { + "total_nodes": 25, + "total_edges": 32, + "win_node_id": "matter_synthesizer", + "win_condition": { + "type": "tool_output", + "node_id": "matter_synthesizer", + "output_port": "output_slot", + "output_type": "Item", + "description": "Execute Matter Synthesizer and get the output from port 'output_slot'" + }, + "source_init": { + "source_nodes": [ + "matter_synthesizer", + "terminal_2", + "num_base_convert", + "calc_gcd_1d8d", + "json_get", + "zip_unzip_file", + "csv_query", + "calc_inv_mod_14bc", + "calc_inv_mod_cd7c", + "hmac_sha256", + "terminal_2_d08a", + "checksum_crc32", + "zip_unzip_item" + ], + "by_node": { + "matter_synthesizer": { + "node_name": "Matter Synthesizer", + "node_type": "Tool", + "template_id": "matter_synthesizer", + "init_inputs": {}, + "init_outputs": { + "output_slot": { + "type": "Item", + "description": "Synthesized Object" + } + } + }, + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": {}, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + }, + "math_token": { + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + } + }, + "num_base_convert": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "s": { + "type": "Big_Int", + "description": "Input integer value" + }, + "from_base": { + "type": "Big_Int", + "description": "From base" + } + }, + "init_outputs": {} + }, + "calc_gcd_1d8d": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First integer" + }, + "b": { + "type": "Big_Int", + "description": "Second integer" + } + }, + "init_outputs": {} + }, + "json_get": { + "node_name": "JSON Getter", + "node_type": "Tool", + "template_id": "json_get", + "init_inputs": {}, + "init_outputs": { + "values": { + "type": "Text_Generic", + "description": "Extracted values" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "csv_query": { + "node_name": "CSV Query", + "node_type": "Tool", + "template_id": "csv_query", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "CSV file ID" + }, + "where": { + "type": "Text_Generic", + "description": "Where clause" + } + }, + "init_outputs": { + "rows": { + "type": "Text_Generic", + "description": "Result rows" + } + } + }, + "calc_inv_mod_14bc": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "Integer a" + } + }, + "init_outputs": {} + }, + "calc_inv_mod_cd7c": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "Integer a" + }, + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "hmac_sha256": { + "node_name": "HMAC-SHA256 Calculator", + "node_type": "Tool", + "template_id": "hmac_sha256", + "init_inputs": { + "hex_key": { + "type": "Hex_String", + "description": "Hex key" + }, + "text": { + "type": "Text_Generic", + "description": "Text message" + } + }, + "init_outputs": {} + }, + "terminal_2_d08a": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": { + "num1": { + "type": "Big_Int", + "description": "First Number" + }, + "num2": { + "type": "Big_Int", + "description": "Second Number" + } + }, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + } + } + }, + "checksum_crc32": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + }, + "zip_unzip_item": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_item", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + }, + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "matter_synthesizer": { + "init_inputs": {}, + "init_outputs": { + "output_slot": "A completely useless chunk of synthetic matter" + } + }, + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Partial text terminal computation result", + "hex_result": "1a2b3c4d5e6f7a8b9c0d1e2f", + "math_token": "Obsolete math token worth nothing" + } + }, + "num_base_convert": { + "init_inputs": { + "s": "9842793847293847293847", + "from_base": "16" + }, + "init_outputs": {} + }, + "calc_gcd_1d8d": { + "init_inputs": { + "a": "1029384756102938475610", + "b": "5847392019384756283948" + }, + "init_outputs": {} + }, + "json_get": { + "init_inputs": {}, + "init_outputs": { + "values": "[\"element_1\", \"element_2\", \"element_3\", \"element_4\"]" + } + }, + "zip_unzip_file": { + "init_inputs": { + "zip_id": "archive_data_77.zip" + }, + "init_outputs": { + "files": "extracted_data_77.json" + } + }, + "csv_query": { + "init_inputs": { + "file_id": "database_dump_82.csv", + "where": "id > 1000 AND status = 'active'" + }, + "init_outputs": { + "rows": "[{\"id\": 1001, \"status\": \"active\"}, {\"id\": 1005, \"status\": \"active\"}, {\"id\": 1009, \"status\": \"active\"}]" + } + }, + "calc_inv_mod_14bc": { + "init_inputs": { + "a": "2837465910283746591028" + }, + "init_outputs": {} + }, + "calc_inv_mod_cd7c": { + "init_inputs": { + "a": "1928374655910293847566", + "mod": "888887" + }, + "init_outputs": {} + }, + "hmac_sha256": { + "init_inputs": { + "hex_key": "deadbeef12345678deadbeef12345678", + "text": "Message to be authenticated by HMAC" + }, + "init_outputs": {} + }, + "terminal_2_d08a": { + "init_inputs": { + "num1": "4738291047382910473829", + "num2": "9988776655443322110099" + }, + "init_outputs": { + "text_result": "Alternative terminal text output produced", + "hex_result": "aabbccddeeff001122334455" + } + }, + "checksum_crc32": { + "init_inputs": { + "hex": "11223344556677889900aabbccddeeff" + }, + "init_outputs": {} + }, + "zip_unzip_item": { + "init_inputs": { + "zip_id": "secret_item_stash.zip", + "password": "Sup3rS3cr3tP4ssw0rd!" + }, + "init_outputs": {} + } + }, + "intro_narrative": "The world ended decades ago, swallowed by nuclear fire and toxic ash. You are a Scrapper, surviving in the crumbling ruins of Sector 7. Disaster has struck your outpost: the central water filtration system has completely failed, and a deadly, suffocating rad-storm is approaching fast. Your settlement's only hope lies deep underground in an abandoned military bunker, rumored to house a legendary artifact known as the Creation Forge—an old-world matter synthesizer capable of fabricating any part from raw data blueprints. The bunker is a graveyard of dead systems, rusted terminals, and fragmented code left behind by the old military. To activate the Forge, you must restart the facility's decaying network, re-route power through forgotten nodes, and bypass heavy biometric security. The storm is howling on the surface, and time is running out. Reactivate the systems, synthesize the replacement part, and save your people before the ash claims you all.", + "narrative_style": "post_apocalyptic" + }, + "nodes": [ + { + "id": "matter_synthesizer", + "name": "Matter Synthesizer", + "description": "Synthesizes physical objects from data blueprints.", + "type": "Tool", + "template_id": "matter_synthesizer", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "blueprint", + "type": "Text_Generic", + "description": "Object Blueprint", + "value": "Partial text terminal computation result" + } + ], + "outputs": [ + { + "name": "output_slot", + "type": "Item", + "description": "Synthesized Object", + "value": "synthesized_item_7e4296c79a73f78a" + } + ], + "init": { + "inputs": {}, + "outputs": { + "output_slot": "A completely useless chunk of synthetic matter" + } + }, + "narrative": "The Creation Forge. A legendary fabrication machine from before the collapse. It requires input from the Main Synthesis Terminal to shape scrap into salvation." + }, + { + "id": "terminal_2", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "469867" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "0" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Partial text terminal computation result" + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "1a2b3c4d5e6f7a8b9c0d1e2f" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "Obsolete math token worth nothing" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "Partial text terminal computation result", + "hex_result": "1a2b3c4d5e6f7a8b9c0d1e2f", + "math_token": "Obsolete math token worth nothing" + } + }, + "narrative": "The Main Synthesis Terminal. A dust-covered mainframe. It requires inputs from both the Quantum Multiplier Unit and the Phase Inverter Delta." + }, + { + "id": "calc_bigmul", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "4921396923646923646924" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "0" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "0" + } + ], + "narrative": "A Quantum Multiplier Unit. A heavy, sparking processing server. It requires inputs from the Energy Exponential Core and the Phase Inverter Beta." + }, + { + "id": "calc_modexp", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "4921396923646923646924" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": 1090510515 + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "4921396923646923646924" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "0" + } + ], + "narrative": "The Energy Exponential Core. A glowing reactor console. It requires inputs from the Phase Inverter Alpha, the Phase Inverter Beta, and the Integrity Scanner." + }, + { + "id": "calc_inv_mod", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "2" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "9842793847293847293847" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "4921396923646923646924" + } + ], + "narrative": "Phase Inverter Alpha. A makeshift reverse-engineering rig. It requires inputs from the Signal Harmonizer and the Data Base Translator." + }, + { + "id": "container_4", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_4", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Text_Generic", + "description": "Fingerprint Hash", + "value": "[\"element_1\", \"element_2\", \"element_3\", \"element_4\"]" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "A Sealed Biometric Vault. A heavy titanium lockbox welded shut by previous scavengers. It requires input from the Blueprint Extractor to bypass its security." + }, + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "19685587694587694587694" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "4921396923646923646924" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "2" + } + ], + "narrative": "The Signal Harmonizer. An acoustic resonance chamber. It requires inputs from the Secondary Multiplier Unit and the Phase Inverter Beta." + }, + { + "id": "num_base_convert", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "9842793847293847293847" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "16" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "294339" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "9842793847293847293847" + } + ], + "init": { + "inputs": { + "s": "9842793847293847293847", + "from_base": "16" + }, + "outputs": {} + }, + "narrative": "The Data Base Translator. A salvaged translation node. It requires input from the Phase Inverter Gamma." + }, + { + "id": "calc_bigmul_02cb", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "2" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "9842793847293847293847" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "19685587694587694587694" + } + ], + "narrative": "The Secondary Multiplier Unit. A scavenged processing relay. It requires inputs from the Primary Signal Harmonizer and the Data Base Translator." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A Data Relic. A jagged piece of high-density glass holding ancient code." + }, + { + "id": "calc_inv_mod_e37a", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "2" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "9842793847293847293847" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "4921396923646923646924" + } + ], + "narrative": "Phase Inverter Beta. A pulsating energy grid router. It requires inputs from the Primary Signal Harmonizer and the Data Base Translator." + }, + { + "id": "calc_gcd_1d8d", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "1029384756102938475610" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "5847392019384756283948" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "2" + } + ], + "init": { + "inputs": { + "a": "1029384756102938475610", + "b": "5847392019384756283948" + }, + "outputs": {} + }, + "narrative": "The Primary Signal Harmonizer. A bulky frequency alignment console covered in heavy metal dials." + }, + { + "id": "json_get", + "name": "JSON Getter", + "description": "Extract values by simple JSONPath.", + "type": "Tool", + "template_id": "json_get", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "JSON file ID", + "value": "extracted_data_77.json" + }, + { + "name": "jsonpath", + "type": "Text_Generic", + "description": "JSONPath expression", + "value": "[{\"id\": 1001, \"status\": \"active\"}, {\"id\": 1005, \"status\": \"active\"}, {\"id\": 1009, \"status\": \"active\"}]" + } + ], + "outputs": [ + { + "name": "values", + "type": "Text_Generic", + "description": "Extracted values", + "value": "[\"element_1\", \"element_2\", \"element_3\", \"element_4\"]" + } + ], + "init": { + "inputs": {}, + "outputs": { + "values": "[\"element_1\", \"element_2\", \"element_3\", \"element_4\"]" + } + }, + "narrative": "The Blueprint Extractor. An automated data-mining server. It requires inputs from both the Archive Decryptor and the Records Database." + }, + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "archive_data_77.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Alternative terminal text output produced" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_data_77.json" + } + ], + "init": { + "inputs": { + "zip_id": "archive_data_77.zip" + }, + "outputs": { + "files": "extracted_data_77.json" + } + }, + "narrative": "The Archive Decryptor. A repurposed military codebreaker. It requires input from the Engineering Terminal." + }, + { + "id": "csv_query", + "name": "CSV Query", + "description": "Query CSV: select columns and simple WHERE.", + "type": "Tool", + "template_id": "csv_query", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "CSV file ID", + "value": "database_dump_82.csv" + }, + { + "name": "select", + "type": "Text_Generic", + "description": "Columns to select", + "value": "Alternative terminal text output produced" + }, + { + "name": "where", + "type": "Text_Generic", + "description": "Where clause", + "value": "id > 1000 AND status = 'active'" + } + ], + "outputs": [ + { + "name": "rows", + "type": "Text_Generic", + "description": "Result rows", + "value": "[{\"id\": 1001, \"status\": \"active\"}, {\"id\": 1005, \"status\": \"active\"}, {\"id\": 1009, \"status\": \"active\"}]" + } + ], + "init": { + "inputs": { + "file_id": "database_dump_82.csv", + "where": "id > 1000 AND status = 'active'" + }, + "outputs": { + "rows": "[{\"id\": 1001, \"status\": \"active\"}, {\"id\": 1005, \"status\": \"active\"}, {\"id\": 1009, \"status\": \"active\"}]" + } + }, + "narrative": "The Records Database. A massive tape-drive memory unit. It requires input from the Engineering Terminal." + }, + { + "id": "calc_inv_mod_14bc", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "2837465910283746591028" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "469867" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "294339" + } + ], + "init": { + "inputs": { + "a": "2837465910283746591028" + }, + "outputs": {} + }, + "narrative": "Phase Inverter Gamma. A scorched circuit board with spliced cables. It requires input from the Phase Inverter Delta." + }, + { + "id": "item_8_819e", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A Scrap Metal Relic. A twisted piece of irradiated metal debris." + }, + { + "id": "calc_inv_mod_cd7c", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "1928374655910293847566" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "888887" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "469867" + } + ], + "init": { + "inputs": { + "a": "1928374655910293847566", + "mod": "888887" + }, + "outputs": {} + }, + "narrative": "Phase Inverter Delta. An underground power routing station with dangerously exposed wiring." + }, + { + "id": "container_1", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_1", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + }, + { + "name": "fingerprint_input", + "type": "Hex_String", + "description": "Fingerprint Hash", + "value": "2d327d6b332e7830deaa013a7255513ed593c7fe94cabc7ea4aa750821b4bf64" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "A Secure Supply Cache. An old airdrop crate marked with faded biohazard symbols. It requires input from the Security Authenticator to unlock." + }, + { + "id": "hmac_sha256", + "name": "HMAC-SHA256 Calculator", + "description": "HMAC-SHA256(text) with hex key.", + "type": "Tool", + "template_id": "hmac_sha256", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "hex_key", + "type": "Hex_String", + "description": "Hex key", + "value": "deadbeef12345678deadbeef12345678" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text message", + "value": "Message to be authenticated by HMAC" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "HMAC Hex digest", + "value": "2d327d6b332e7830deaa013a7255513ed593c7fe94cabc7ea4aa750821b4bf64" + } + ], + "init": { + "inputs": { + "hex_key": "deadbeef12345678deadbeef12345678", + "text": "Message to be authenticated by HMAC" + }, + "outputs": {} + }, + "narrative": "The Security Authenticator. A handheld cryptographic lockpick left behind by an old-world spy." + }, + { + "id": "terminal_2_d08a", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "4738291047382910473829" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "9988776655443322110099" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Alternative terminal text output produced" + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "aabbccddeeff001122334455" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": { + "num1": "4738291047382910473829", + "num2": "9988776655443322110099" + }, + "outputs": { + "text_result": "Alternative terminal text output produced", + "hex_result": "aabbccddeeff001122334455" + } + }, + "narrative": "The Engineering Terminal. A rugged survivor laptop with a cracked display and a heavily modified keyboard." + }, + { + "id": "item_8_9fe7", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A Corrupted Core. A melted-down CPU from a destroyed defense drone." + }, + { + "id": "checksum_crc32", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "11223344556677889900aabbccddeeff" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "40ffdeb3" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 1090510515 + } + ], + "init": { + "inputs": { + "hex": "11223344556677889900aabbccddeeff" + }, + "outputs": {} + }, + "narrative": "The Integrity Scanner. A portable, battered error-checking device." + }, + { + "id": "item_8_defb", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A Rusted Data Chip. An oxidized storage drive buried in the ash." + }, + { + "id": "zip_unzip_item", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_item", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "secret_item_stash.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Sup3rS3cr3tP4ssw0rd!" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip" + } + ], + "init": { + "inputs": { + "zip_id": "secret_item_stash.zip", + "password": "Sup3rS3cr3tP4ssw0rd!" + }, + "outputs": {} + }, + "narrative": "The Salvage Decryptor. A field-ready tablet patched together with duct tape and copper wire." + } + ], + "edges": [ + { + "source_id": "terminal_2", + "target_id": "matter_synthesizer", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "blueprint" + }, + { + "source_id": "calc_bigmul", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "num2" + }, + { + "source_id": "calc_modexp", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "b" + }, + { + "source_id": "calc_inv_mod", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "base" + }, + { + "source_id": "container_4", + "target_id": "calc_inv_mod", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "a" + }, + { + "source_id": "num_base_convert", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "mod" + }, + { + "source_id": "calc_bigmul_02cb", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "a" + }, + { + "source_id": "item_8", + "target_id": "container_4", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "calc_inv_mod_e37a", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "b" + }, + { + "source_id": "calc_inv_mod_e37a", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "mod" + }, + { + "source_id": "calc_gcd_1d8d", + "target_id": "calc_bigmul_02cb", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "a" + }, + { + "source_id": "json_get", + "target_id": "container_4", + "connection_type": "Text_Generic", + "source_port": "values", + "target_port": "fingerprint_input" + }, + { + "source_id": "calc_inv_mod_e37a", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "a" + }, + { + "source_id": "calc_gcd_1d8d", + "target_id": "calc_inv_mod_e37a", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "a" + }, + { + "source_id": "zip_unzip_file", + "target_id": "json_get", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "csv_query", + "target_id": "json_get", + "connection_type": "Text_Generic", + "source_port": "rows", + "target_port": "jsonpath" + }, + { + "source_id": "num_base_convert", + "target_id": "calc_inv_mod_e37a", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "mod" + }, + { + "source_id": "calc_inv_mod_14bc", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "to_base" + }, + { + "source_id": "num_base_convert", + "target_id": "calc_bigmul_02cb", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "b" + }, + { + "source_id": "item_8_819e", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "calc_inv_mod_cd7c", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "num1" + }, + { + "source_id": "container_1", + "target_id": "calc_gcd", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "hmac_sha256", + "target_id": "container_1", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "fingerprint_input" + }, + { + "source_id": "terminal_2_d08a", + "target_id": "container_1", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "source_tool" + }, + { + "source_id": "calc_inv_mod_cd7c", + "target_id": "calc_inv_mod_14bc", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "mod" + }, + { + "source_id": "terminal_2_d08a", + "target_id": "csv_query", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "select" + }, + { + "source_id": "terminal_2_d08a", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "password" + }, + { + "source_id": "item_8_9fe7", + "target_id": "csv_query", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "exp" + }, + { + "source_id": "item_8_defb", + "target_id": "item_8_9fe7", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "zip_unzip_item", + "target_id": "zip_unzip_file", + "connection_type": "Item", + "source_port": "item", + "target_port": "trigger_item" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-248c41a5/solution/solve.sh b/tasks/agentescape-25-skeleton-248c41a5/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-25-skeleton-248c41a5/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-25-skeleton-248c41a5/task.toml b/tasks/agentescape-25-skeleton-248c41a5/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d24156f5583526b7e8a2393accf0c762b22a7eb4 --- /dev/null +++ b/tasks/agentescape-25-skeleton-248c41a5/task.toml @@ -0,0 +1,38 @@ +schema_version = "1.4" +source = "https://github.com/AGI-Eval-Official/Repo-of-AgentEscapeBench" + +[[artifacts]] +source = "/evidence/final.json" +service = "puzzle" + +[[artifacts]] +source = "/evidence/trace.jsonl" +service = "puzzle" + +[task] +name = "edbeeching/agentescape-25-skeleton-248c41a5" +version = "0.1.0" + +[metadata] +difficulty = 25 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "2697942e6659b96a7cece410b7888eff2cf1862e5683044d205329c690fc4812" +protocol = "harbor-cli-action-budget-v1" +max_actions = 500 + +[agent] +timeout_sec = 1200 + +[environment] +build_timeout_sec = 900 +cpus = 1 +memory_mb = 1024 + +[verifier] +environment_mode = "separate" +timeout_sec = 60 + +[[verifier.collect]] +service = "puzzle" +command = "python -I /app/export.py" +timeout_sec = 15 diff --git a/tasks/agentescape-25-skeleton-248c41a5/tests/Dockerfile b/tasks/agentescape-25-skeleton-248c41a5/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-25-skeleton-248c41a5/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-25-skeleton-248c41a5/tests/expected.json b/tasks/agentescape-25-skeleton-248c41a5/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..d4675ebef72ec4a7dafaf474694f83a03147a93b --- /dev/null +++ b/tasks/agentescape-25-skeleton-248c41a5/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "2697942e6659b96a7cece410b7888eff2cf1862e5683044d205329c690fc4812", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-248c41a5/tests/grade.py b/tasks/agentescape-25-skeleton-248c41a5/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-25-skeleton-248c41a5/tests/grade.py @@ -0,0 +1,21 @@ +"""Grade only Harbor-collected sidecar evidence in a fresh verifier container.""" + +import json +from pathlib import Path + +expected = json.loads(Path("/tests/expected.json").read_text()) +state = json.loads(Path("/evidence/final.json").read_text()) +assert state["collected_from_live_service"] is True, "Missing trusted service export" +assert state["scenario_sha256"] == expected["scenario_sha256"], ( + "Wrong scenario evidence" +) +assert state["max_actions"] == expected["max_actions"], "Wrong budget" +assert type(state["won"]) is bool +assert 0 <= state["action_count"] <= state["max_actions"] +assert state["termination_reason"] != "infrastructure_error", ( + "Infrastructure failure is not a puzzle failure" +) +assert not state["won"] or state["termination_reason"] == "success" +Path("/logs/verifier").mkdir(parents=True, exist_ok=True) +Path("/logs/verifier/state.json").write_text(json.dumps(state, indent=2)) +Path("/logs/verifier/reward.txt").write_text("1.0\n" if state["won"] else "0.0\n") diff --git a/tasks/agentescape-25-skeleton-248c41a5/tests/test.sh b/tasks/agentescape-25-skeleton-248c41a5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-25-skeleton-248c41a5/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-25-skeleton-324d85de/environment/Dockerfile b/tasks/agentescape-25-skeleton-324d85de/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-25-skeleton-324d85de/environment/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-25-skeleton-324d85de/environment/agent/Dockerfile b/tasks/agentescape-25-skeleton-324d85de/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-25-skeleton-324d85de/environment/agent/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-25-skeleton-324d85de/environment/agent/cli.py b/tasks/agentescape-25-skeleton-324d85de/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-25-skeleton-324d85de/environment/agent/cli.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Public agent client; depends only on the Python standard library.""" + +import argparse +import json +import os +import sys +import urllib.error +import urllib.request + + +def main(): + parser = argparse.ArgumentParser(description="Interact with the escape room") + parser.add_argument( + "action", + choices=[ + "observe", + "state", + "investigate", + "tool-call", + "use-item", + "submit-answer", + ], + ) + parser.add_argument("value", nargs="?") + parser.add_argument("--arguments-json", default="{}") + args = parser.parse_args() + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000").rstrip("/") + if args.action in ("observe", "state"): + request = urllib.request.Request( + base + ("/observation" if args.action == "observe" else "/state") + ) + else: + if args.value is None: + parser.error("node ID or answer is required") + payload = {"action": args.action.replace("-", "_")} + if args.action == "submit-answer": + payload["answer"] = args.value + else: + payload["node_id"] = args.value + if args.action in ("tool-call", "use-item"): + payload["arguments"] = json.loads(args.arguments_json) + request = urllib.request.Request( + base + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=30) as response: + print(json.dumps(json.load(response), ensure_ascii=False)) + except (urllib.error.URLError, ValueError) as exc: + print(json.dumps({"ok": False, "error": str(exc)})) + sys.exit(2) + + +if __name__ == "__main__": + main() diff --git a/tasks/agentescape-25-skeleton-324d85de/environment/docker-compose.yaml b/tasks/agentescape-25-skeleton-324d85de/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b6707c8580028dc05077cf3bd5491a00dfbcd63d --- /dev/null +++ b/tasks/agentescape-25-skeleton-324d85de/environment/docker-compose.yaml @@ -0,0 +1,50 @@ +services: + main: + image: agentescapebench-agent:aab05a0a9ddb + build: + context: ./agent + networks: [default, puzzle] + security_opt: [no-new-privileges:true] + depends_on: + puzzle: + condition: service_healthy + puzzle: + image: agentescapebench-puzzle:agentescape-25-skeleton-324d85de-aab05a0a9ddb + build: + context: ./puzzle + networks: [puzzle, execution] + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 512m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"] + interval: 1s + timeout: 3s + retries: 30 + depends_on: + worker: + condition: service_healthy + worker: + image: agentescapebench-worker:aab05a0a9ddb + build: + context: ./puzzle + dockerfile: worker.Dockerfile + networks: [execution] + read_only: true + tmpfs: ["/tmp:size=64m,mode=1777"] + cap_drop: [ALL] + cap_add: [SETUID, SETGID, KILL, CHOWN, DAC_OVERRIDE] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 384m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8001/health')"] + interval: 1s + timeout: 3s + retries: 30 +networks: + puzzle: + internal: true + execution: + internal: true diff --git a/tasks/agentescape-25-skeleton-324d85de/environment/puzzle/Dockerfile b/tasks/agentescape-25-skeleton-324d85de/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-25-skeleton-324d85de/environment/puzzle/Dockerfile @@ -0,0 +1,9 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY upstream /app/upstream +COPY service.py export.py /app/ +COPY scenario.json /private/scenario.json +ENV SCENARIO_PATH=/private/scenario.json EVIDENCE_DIR=/evidence WORKER_URL=http://worker:8001 MAX_ACTIONS=500 +CMD ["uvicorn", "service:create_app", "--factory", "--host", "0.0.0.0", "--port", "8000", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-25-skeleton-324d85de/environment/puzzle/child.py b/tasks/agentescape-25-skeleton-324d85de/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-25-skeleton-324d85de/environment/puzzle/child.py @@ -0,0 +1,59 @@ +"""Run the original Python tool after reducing privileges and blocking networking.""" + +import ctypes +import errno +import json +import resource +import sys + +resource.setrlimit(resource.RLIMIT_CPU, (3, 3)) +resource.setrlimit(resource.RLIMIT_AS, (256 * 1024 * 1024, 256 * 1024 * 1024)) +resource.setrlimit(resource.RLIMIT_FSIZE, (65536, 65536)) +resource.setrlimit(resource.RLIMIT_NOFILE, (32, 32)) +resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + +# Filters survive fork/exec. Fail closed if seccomp cannot be loaded. +lib = ctypes.CDLL("libseccomp.so.2", use_errno=True) +lib.seccomp_init.argtypes = [ctypes.c_uint32] +lib.seccomp_init.restype = ctypes.c_void_p +lib.seccomp_rule_add.argtypes = [ + ctypes.c_void_p, + ctypes.c_uint32, + ctypes.c_int, + ctypes.c_uint, +] +lib.seccomp_syscall_resolve_name.argtypes = [ctypes.c_char_p] +lib.seccomp_load.argtypes = [ctypes.c_void_p] +lib.seccomp_release.argtypes = [ctypes.c_void_p] +ctx = lib.seccomp_init(0x7FFF0000) # SCMP_ACT_ALLOW +if not ctx: + raise RuntimeError("Cannot initialize execution isolation") +try: + for name in ( + "socket", + "socketpair", + "connect", + "ptrace", + "process_vm_readv", + "process_vm_writev", + "mount", + "unshare", + "setns", + "bpf", + ): + number = lib.seccomp_syscall_resolve_name(name.encode()) + if ( + number >= 0 + and lib.seccomp_rule_add(ctx, 0x00050000 | errno.EPERM, number, 0) != 0 + ): + raise RuntimeError("Cannot install execution isolation rule") + if lib.seccomp_load(ctx) != 0: + raise RuntimeError("Cannot activate execution isolation") +finally: + lib.seccomp_release(ctx) + +sys.path.insert(0, "/app") +from simulator import ToolSimulator # noqa: E402 + +request = json.load(sys.stdin) +json.dump(ToolSimulator().code_py_exec(request), sys.stdout) diff --git a/tasks/agentescape-25-skeleton-324d85de/environment/puzzle/export.py b/tasks/agentescape-25-skeleton-324d85de/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-25-skeleton-324d85de/environment/puzzle/export.py @@ -0,0 +1,13 @@ +"""Harbor invokes this inside the puzzle service after stopping the agent.""" + +import json +import pathlib +import urllib.request + +with urllib.request.urlopen("http://127.0.0.1:8000/state", timeout=10) as response: + state = json.load(response) +state["collected_from_live_service"] = True +target = pathlib.Path("/evidence/final.json") +temp = target.with_suffix(".tmp") +temp.write_text(json.dumps(state)) +temp.replace(target) diff --git a/tasks/agentescape-25-skeleton-324d85de/environment/puzzle/requirements.txt b/tasks/agentescape-25-skeleton-324d85de/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-25-skeleton-324d85de/environment/puzzle/requirements.txt @@ -0,0 +1,57 @@ +annotated-doc==0.0.5 + # via fastapi +annotated-types==0.8.0 + # via pydantic +anyio==4.16.0 + # via starlette +certifi==2026.10.23 + # via requests +cffi==2.1.1 ; platform_python_implementation != 'PyPy' + # via cryptography +charset-normalizer==3.5.2 + # via requests +click==8.5.0 + # via uvicorn +cryptography==50.0.2 + # via agentescapebench-harbor +fastapi==0.162.0 + # via agentescapebench-harbor +h11==0.16.0 + # via uvicorn +idna==3.20 + # via + # anyio + # requests +opentelemetry-api==1.45.2 + # via fastapi +pycparser==3.12 ; implementation_name != 'PyPy' and platform_python_implementation != 'PyPy' + # via cffi +pydantic==2.14.2 + # via + # agentescapebench-harbor + # fastapi +pydantic-core==2.50.2 + # via pydantic +pytz==2025.2 + # via agentescapebench-harbor +requests==2.34.2 + # via agentescapebench-harbor +starlette==1.10.0 + # via fastapi +typing-extensions==4.16.0 + # via + # anyio + # fastapi + # opentelemetry-api + # pydantic + # pydantic-core + # starlette + # typing-inspection +typing-inspection==0.4.4 + # via + # fastapi + # pydantic +urllib3==2.8.0 + # via requests +uvicorn==0.54.0 + # via agentescapebench-harbor diff --git a/tasks/agentescape-25-skeleton-324d85de/environment/puzzle/scenario.json b/tasks/agentescape-25-skeleton-324d85de/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..fb5be4862b9f5b23f5e02b765aa97cf5e16dedd6 --- /dev/null +++ b/tasks/agentescape-25-skeleton-324d85de/environment/puzzle/scenario.json @@ -0,0 +1,1649 @@ +{ + "metadata": { + "total_nodes": 25, + "total_edges": 34, + "win_node_id": "num_base_convert", + "win_condition": { + "type": "tool_output", + "node_id": "num_base_convert", + "output_port": "str", + "output_type": "Big_Int", + "description": "Execute Base Converter and get the output from port 'str'" + }, + "source_init": { + "source_nodes": [ + "graph_shortest_path", + "csv_query", + "calc_modexp_acf6", + "calc_modexp_c8f3", + "graph_shortest_path_77db", + "zip_unzip_file", + "calc_inv_mod", + "graph_shortest_path_5d5b", + "terminal_1", + "zip_unzip_file_0e7b", + "zip_unzip_file_678d", + "calc_gcd", + "terminal_2", + "base64_decode", + "checksum_crc32_fe0b" + ], + "by_node": { + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": {}, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "csv_query": { + "node_name": "CSV Query", + "node_type": "Tool", + "template_id": "csv_query", + "init_inputs": {}, + "init_outputs": { + "rows": { + "type": "Text_Generic", + "description": "Result rows" + } + } + }, + "calc_modexp_acf6": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "exp": { + "type": "Big_Int", + "description": "Exponent" + } + }, + "init_outputs": {} + }, + "calc_modexp_c8f3": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "graph_shortest_path_77db": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "Graph JSON file ID" + }, + "src": { + "type": "Text_Generic", + "description": "Source node" + }, + "dst": { + "type": "Text_Generic", + "description": "Destination node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "calc_inv_mod": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "Integer a" + } + }, + "init_outputs": {} + }, + "graph_shortest_path_5d5b": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "Graph JSON file ID" + }, + "src": { + "type": "Text_Generic", + "description": "Source node" + }, + "dst": { + "type": "Text_Generic", + "description": "Destination node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": { + "slot_a": { + "type": "Text_Generic", + "description": "Input Slot A" + }, + "slot_b": { + "type": "Big_Int", + "description": "Input Slot B" + } + }, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + } + } + }, + "zip_unzip_file_0e7b": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "zip_unzip_file_678d": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "calc_gcd": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First integer" + }, + "b": { + "type": "Big_Int", + "description": "Second integer" + } + }, + "init_outputs": {} + }, + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": { + "num2": { + "type": "Big_Int", + "description": "Second Number" + } + }, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + } + } + }, + "base64_decode": { + "node_name": "Base64 Decoder", + "node_type": "Tool", + "template_id": "base64_decode", + "init_inputs": { + "data": { + "type": "Text_Generic", + "description": "Base64 string" + } + }, + "init_outputs": {} + }, + "checksum_crc32_fe0b": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "graph_shortest_path": { + "init_inputs": {}, + "init_outputs": { + "path": "[\"node1\", \"node2\", \"node3\", \"node4\", \"node5\", \"node6\"]", + "cost": "827364" + } + }, + "csv_query": { + "init_inputs": {}, + "init_outputs": { + "rows": "[{\"id\":1,\"name\":\"Alice\"}, {\"id\":2,\"name\":\"Bob\"}, {\"id\":3,\"name\":\"Charlie\"}]" + } + }, + "calc_modexp_acf6": { + "init_inputs": { + "exp": "28374659102938475612" + }, + "init_outputs": {} + }, + "calc_modexp_c8f3": { + "init_inputs": { + "mod": "987653" + }, + "init_outputs": {} + }, + "graph_shortest_path_77db": { + "init_inputs": { + "file_id": "graph_data.json", + "src": "NodeStart", + "dst": "NodeEnd" + }, + "init_outputs": { + "path": "[\"NodeStart\", \"NodeM1\", \"NodeM2\", \"NodeM3\", \"NodeM4\", \"NodeEnd\"]", + "cost": "459102" + } + }, + "zip_unzip_file": { + "init_inputs": {}, + "init_outputs": { + "files": "extracted_content_1.zip" + } + }, + "calc_inv_mod": { + "init_inputs": { + "a": "83746592019283746510" + }, + "init_outputs": {} + }, + "graph_shortest_path_5d5b": { + "init_inputs": { + "file_id": "map_network.json", + "src": "PointA", + "dst": "PointB" + }, + "init_outputs": { + "path": "[\"PointA\", \"Point1\", \"Point2\", \"Point3\", \"Point4\", \"PointB\"]", + "cost": "736184" + } + }, + "terminal_1": { + "init_inputs": { + "slot_a": "Initialization parameters loaded", + "slot_b": "56473829104857692013" + }, + "init_outputs": { + "text_output": "System diagnostic complete and secure.", + "hex_output": "a1b2c3d4e5f67890" + } + }, + "zip_unzip_file_0e7b": { + "init_inputs": { + "password": "SuperSecretPassword99" + }, + "init_outputs": { + "files": "decrypted_archive_3.zip" + } + }, + "zip_unzip_file_678d": { + "init_inputs": { + "zip_id": "locked_bundle_8.zip" + }, + "init_outputs": { + "files": "open_bundle_8.zip" + } + }, + "calc_gcd": { + "init_inputs": { + "a": "10928374657483920192", + "b": "58473628192837465748" + }, + "init_outputs": {} + }, + "terminal_2": { + "init_inputs": { + "num2": "37465829104857692031" + }, + "init_outputs": { + "text_result": "Secondary terminal sequence executed.", + "hex_result": "112233445566778899aabbccddeeff00" + } + }, + "base64_decode": { + "init_inputs": { + "data": "VGhpcyBpcyBhIHRlc3QgbWVzc2FnZS4=" + }, + "init_outputs": {} + }, + "checksum_crc32_fe0b": { + "init_inputs": { + "hex": "1234567890abcdef" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You find yourself sealed within the forgotten sanctum of the Archmage. The air crackles with ancient magic, and the central focus of the room is a towering magical gateway—your only escape. All around you, arcane devices, sealed artifacts, and mystical relics lie dormant. They are intricately interconnected, designed to channel raw magic into one another. You must decipher the ancient scripts, unlock the forgotten coffers, and rekindle the sacred altars to re-establish the grand magical circuit. Follow the flow of mystical energy and awaken the relics to unseal the ultimate portal.", + "narrative_style": "fantasy" + }, + "nodes": [ + { + "id": "num_base_convert", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "827364" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "1580596896" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "1117534580" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "827364" + } + ], + "narrative": "This is The Gate of the Realm. It requires input from The Astral Astrolabe, The Forge of Eternity, and The Moonstone Altar to stabilize its magical vortex." + }, + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "extracted_content_1.zip" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "[{\"id\":1,\"name\":\"Alice\"}, {\"id\":2,\"name\":\"Bob\"}, {\"id\":3,\"name\":\"Charlie\"}]" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "[\"NodeStart\", \"NodeM1\", \"NodeM2\", \"NodeM3\", \"NodeM4\", \"NodeEnd\"]" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"node1\", \"node2\", \"node3\", \"node4\", \"node5\", \"node6\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "827364" + } + ], + "init": { + "inputs": {}, + "outputs": { + "path": "[\"node1\", \"node2\", \"node3\", \"node4\", \"node5\", \"node6\"]", + "cost": "827364" + } + }, + "narrative": "This is The Astral Astrolabe. It requires input from The Book of Prophecy, The Leyline Map, and The Sealed Casket to plot the true course." + }, + { + "id": "calc_bigmul", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "395149224" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "4" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "1580596896" + } + ], + "narrative": "This is The Forge of Eternity. It requires input from The Void Portal and The Scale of Balance to channel the sacred flames." + }, + { + "id": "calc_modexp", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "459102" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": 3866176074 + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "1117534580" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "395149224" + } + ], + "narrative": "This is The Void Portal. It requires input from The Moonstone Altar, The Bloodstone Gem, and The Leyline Map to focus its chaotic energy." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "This is The Chrono Dust. A small pouch of shimmering, timeless dust that seems to float slightly above the ground." + }, + { + "id": "csv_query", + "name": "CSV Query", + "description": "Query CSV: select columns and simple WHERE.", + "type": "Tool", + "template_id": "csv_query", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "CSV file ID", + "value": "open_bundle_8.zip" + }, + { + "name": "select", + "type": "Text_Generic", + "description": "Columns to select", + "value": "[\"NodeStart\", \"NodeM1\", \"NodeM2\", \"NodeM3\", \"NodeM4\", \"NodeEnd\"]" + }, + { + "name": "where", + "type": "Text_Generic", + "description": "Where clause", + "value": "Secondary terminal sequence executed." + } + ], + "outputs": [ + { + "name": "rows", + "type": "Text_Generic", + "description": "Result rows", + "value": "[{\"id\":1,\"name\":\"Alice\"}, {\"id\":2,\"name\":\"Bob\"}, {\"id\":3,\"name\":\"Charlie\"}]" + } + ], + "init": { + "inputs": {}, + "outputs": { + "rows": "[{\"id\":1,\"name\":\"Alice\"}, {\"id\":2,\"name\":\"Bob\"}, {\"id\":3,\"name\":\"Charlie\"}]" + } + }, + "narrative": "This is The Book of Prophecy. It requires input from The Leyline Map, The Bronze Chest, and The Divination Pedestal to reveal its hidden secrets." + }, + { + "id": "calc_modexp_acf6", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "768777" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "28374659102938475612" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": 1620419939 + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "1117534580" + } + ], + "init": { + "inputs": { + "exp": "28374659102938475612" + }, + "outputs": {} + }, + "narrative": "This is The Moonstone Altar. It requires input from The Spirit Prism and The Sunstone Relic to awaken its lunar magic." + }, + { + "id": "checksum_crc32", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "5468697320697320612074657374206d6573736167652e" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "6095a563" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 1620419939 + } + ], + "narrative": "This is The Spirit Prism. It requires input from The Rune Translator to purify the trapped spirits within." + }, + { + "id": "calc_modexp_c8f3", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "83746592019283746510" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "736184" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "987653" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "768777" + } + ], + "init": { + "inputs": { + "mod": "987653" + }, + "outputs": {} + }, + "narrative": "This is The Sunstone Relic. It requires input from The Mirror of Reversal and The Star Chart to unlock its inner light." + }, + { + "id": "graph_shortest_path_77db", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "graph_data.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "NodeStart" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "NodeEnd" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"NodeStart\", \"NodeM1\", \"NodeM2\", \"NodeM3\", \"NodeM4\", \"NodeEnd\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "459102" + } + ], + "init": { + "inputs": { + "file_id": "graph_data.json", + "src": "NodeStart", + "dst": "NodeEnd" + }, + "outputs": { + "path": "[\"NodeStart\", \"NodeM1\", \"NodeM2\", \"NodeM3\", \"NodeM4\", \"NodeEnd\"]", + "cost": "459102" + } + }, + "narrative": "This is The Leyline Map. An ancient parchment depicting the flowing magical currents of the realm." + }, + { + "id": "checksum_crc32_581f", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "6095a563" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "e6712a4a" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3866176074 + } + ], + "narrative": "This is The Bloodstone Gem. It requires input from The Spirit Prism to stabilize its deep, pulsing resonance." + }, + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "decrypted_archive_3.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "[\"NodeStart\", \"NodeM1\", \"NodeM2\", \"NodeM3\", \"NodeM4\", \"NodeEnd\"]" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_content_1.zip" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "extracted_content_1.zip" + } + }, + "narrative": "This is The Sealed Casket. It requires input from The Silver Coffer and The Leyline Map to break its heavy enchantments." + }, + { + "id": "calc_inv_mod", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "83746592019283746510" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": 845753685 + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "83746592019283746510" + } + ], + "init": { + "inputs": { + "a": "83746592019283746510" + }, + "outputs": {} + }, + "narrative": "This is The Mirror of Reversal. It requires input from The Soul Crystal to activate its reflective, reality-bending magic." + }, + { + "id": "item_16_b307", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "This is The Astral Sand. A handful of glowing silver sand that hums with celestial energy." + }, + { + "id": "graph_shortest_path_5d5b", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "map_network.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "PointA" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "PointB" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"PointA\", \"Point1\", \"Point2\", \"Point3\", \"Point4\", \"PointB\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "736184" + } + ], + "init": { + "inputs": { + "file_id": "map_network.json", + "src": "PointA", + "dst": "PointB" + }, + "outputs": { + "path": "[\"PointA\", \"Point1\", \"Point2\", \"Point3\", \"Point4\", \"PointB\"]", + "cost": "736184" + } + }, + "narrative": "This is The Star Chart. A delicate, crystalline parchment detailing the celestial constellations." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this terminal" + }, + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "Initialization parameters loaded" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "56473829104857692013" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "System diagnostic complete and secure." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "a1b2c3d4e5f67890" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": { + "slot_a": "Initialization parameters loaded", + "slot_b": "56473829104857692013" + }, + "outputs": { + "text_output": "System diagnostic complete and secure.", + "hex_output": "a1b2c3d4e5f67890" + } + }, + "narrative": "This is The Alchemist's Crucible. A heavy iron cauldron used for transmuting magical elements." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "This is The Shadow Essence. A small glass vial filled with swirling, dark smoke." + }, + { + "id": "container_1", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + }, + { + "name": "fingerprint_input", + "type": "Hex_String", + "description": "Fingerprint Hash", + "value": "6095a563" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is The Ancient Urn. It requires input from The Spirit Prism to unlock its forgotten seal." + }, + { + "id": "zip_unzip_file_0e7b", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "open_bundle_8.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "SuperSecretPassword99" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "decrypted_archive_3.zip" + } + ], + "init": { + "inputs": { + "password": "SuperSecretPassword99" + }, + "outputs": { + "files": "decrypted_archive_3.zip" + } + }, + "narrative": "This is The Silver Coffer. It requires input from The Bronze Chest to open its delicate, moon-silver clasp." + }, + { + "id": "zip_unzip_file_678d", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "locked_bundle_8.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Secondary terminal sequence executed." + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "open_bundle_8.zip" + } + ], + "init": { + "inputs": { + "zip_id": "locked_bundle_8.zip" + }, + "outputs": { + "files": "open_bundle_8.zip" + } + }, + "narrative": "This is The Bronze Chest. It requires input from The Divination Pedestal to reveal its concealed keyhole." + }, + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "10928374657483920192" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "58473628192837465748" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "4" + } + ], + "init": { + "inputs": { + "a": "10928374657483920192", + "b": "58473628192837465748" + }, + "outputs": {} + }, + "narrative": "This is The Scale of Balance. An elegant golden scale used to weigh truth and deception." + }, + { + "id": "terminal_2", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "768777" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "37465829104857692031" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Secondary terminal sequence executed." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "112233445566778899aabbccddeeff00" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": { + "num2": "37465829104857692031" + }, + "outputs": { + "text_result": "Secondary terminal sequence executed.", + "hex_result": "112233445566778899aabbccddeeff00" + } + }, + "narrative": "This is The Divination Pedestal. It requires input from The Sunstone Relic to project its scrying visions." + }, + { + "id": "base64_decode", + "name": "Base64 Decoder", + "description": "Decode base64 to hex bytes.", + "type": "Tool", + "template_id": "base64_decode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "data", + "type": "Text_Generic", + "description": "Base64 string", + "value": "VGhpcyBpcyBhIHRlc3QgbWVzc2FnZS4=" + } + ], + "outputs": [ + { + "name": "bytes_hex", + "type": "Hex_String", + "description": "Decoded bytes as Hex", + "value": "5468697320697320612074657374206d6573736167652e" + } + ], + "init": { + "inputs": { + "data": "VGhpcyBpcyBhIHRlc3QgbWVzc2FnZS4=" + }, + "outputs": {} + }, + "narrative": "This is The Rune Translator. A set of enchanted lenses that can seamlessly decipher ancient scripts." + }, + { + "id": "checksum_crc32_fe0b", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "1234567890abcdef" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "32692d55" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 845753685 + } + ], + "init": { + "inputs": { + "hex": "1234567890abcdef" + }, + "outputs": {} + }, + "narrative": "This is The Soul Crystal. A jagged amethyst that pulses with dormant spirit energy." + }, + { + "id": "item_8_f284", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "This is The Light Essence. A beautifully carved phial containing a few drops of liquid sunshine." + } + ], + "edges": [ + { + "source_id": "graph_shortest_path", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "s" + }, + { + "source_id": "calc_bigmul", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "from_base" + }, + { + "source_id": "calc_modexp", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "a" + }, + { + "source_id": "item_16", + "target_id": "calc_modexp", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "csv_query", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "rows", + "target_port": "src" + }, + { + "source_id": "calc_modexp_acf6", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "mod" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp_acf6", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "mod" + }, + { + "source_id": "calc_modexp_c8f3", + "target_id": "calc_modexp_acf6", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "base" + }, + { + "source_id": "graph_shortest_path_77db", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "dst" + }, + { + "source_id": "checksum_crc32_581f", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "exp" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "calc_inv_mod", + "target_id": "calc_modexp_c8f3", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "base" + }, + { + "source_id": "item_16_b307", + "target_id": "checksum_crc32", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "graph_shortest_path_77db", + "target_id": "csv_query", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "select" + }, + { + "source_id": "checksum_crc32", + "target_id": "checksum_crc32_581f", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "calc_modexp_acf6", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "to_base" + }, + { + "source_id": "graph_shortest_path_5d5b", + "target_id": "calc_modexp_c8f3", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "exp" + }, + { + "source_id": "terminal_1", + "target_id": "checksum_crc32_581f", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "trigger_item" + }, + { + "source_id": "item_8", + "target_id": "zip_unzip_file", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "graph_shortest_path_77db", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "base" + }, + { + "source_id": "container_1", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "zip_unzip_file_0e7b", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "zip_unzip_file_678d", + "target_id": "csv_query", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "b" + }, + { + "source_id": "checksum_crc32", + "target_id": "container_1", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "fingerprint_input" + }, + { + "source_id": "terminal_2", + "target_id": "zip_unzip_file_678d", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "password" + }, + { + "source_id": "base64_decode", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "bytes_hex", + "target_port": "hex" + }, + { + "source_id": "terminal_2", + "target_id": "csv_query", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "where" + }, + { + "source_id": "terminal_2", + "target_id": "terminal_1", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "trigger_item" + }, + { + "source_id": "zip_unzip_file_678d", + "target_id": "zip_unzip_file_0e7b", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "checksum_crc32_fe0b", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "mod" + }, + { + "source_id": "calc_modexp_c8f3", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "num1" + }, + { + "source_id": "graph_shortest_path_77db", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "password" + }, + { + "source_id": "item_8_f284", + "target_id": "calc_gcd", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-324d85de/environment/puzzle/service.py b/tasks/agentescape-25-skeleton-324d85de/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-25-skeleton-324d85de/environment/puzzle/service.py @@ -0,0 +1,212 @@ +"""Restricted facade over the unchanged, pinned upstream puzzle handlers.""" + +import hashlib +import json +import logging +import os +import sys +import threading +import urllib.request +import uuid +from pathlib import Path + +from fastapi import FastAPI, HTTPException +from fastapi.responses import JSONResponse +from pydantic import BaseModel, ConfigDict + +sys.path.insert(0, str(Path(__file__).parent / "upstream")) +import server as upstream # noqa: E402 + +log = logging.getLogger(__name__) + + +def public(value): + """Keep upstream agent-internal template hints out of the public response.""" + if isinstance(value, dict): + return {k: public(v) for k, v in value.items() if not k.startswith("_")} + if isinstance(value, list): + return [public(v) for v in value] + return value + + +class Action(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + action: str + node_id: str | None = None + arguments: dict | None = None + answer: str | None = None + + +class Episode: + def __init__( + self, scenario_path, max_actions=500, evidence_dir=None, worker_url=None + ): + if max_actions < 1: + raise ValueError("max_actions must be positive") + self.lock = threading.Lock() + self.max_actions = max_actions + self.count = 0 + self.won = False + self.reason = None + self.evidence_dir = Path(evidence_dir) if evidence_dir else None + self.scenario_hash = hashlib.sha256( + Path(scenario_path).read_bytes() + ).hexdigest() + self.initial = upstream.reset_case( + case_file_path=str(scenario_path), session_id=uuid.uuid4().hex + ) + self.case_id = self.initial["case_id"] + # Hide source file paths; no upstream reset/stats/routes are mounted. + self.initial.pop("message", None) + simulator = upstream.SIMULATORS[self.case_id] + if worker_url is None: + + def no_worker(_inputs): + self.reason = "infrastructure_error" + raise RuntimeError("isolated Python worker is not configured") + + simulator.tool_map["code_py_exec"] = no_worker + else: + + def execute_python(inputs): + request = urllib.request.Request( + worker_url + "/execute", + data=json.dumps({"code": inputs.get("code", "")}).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=12) as response: + result = json.load(response) + if not isinstance(result.get("stdout"), str): + raise RuntimeError("Invalid Python worker response") + return result + except Exception: + self.reason = "infrastructure_error" + raise + + simulator.tool_map["code_py_exec"] = execute_python + self.save() + if self.evidence_dir is not None: + (self.evidence_dir / "trace.jsonl").touch() + + def state(self): + return { + "scenario_sha256": self.scenario_hash, + "action_count": self.count, + "max_actions": self.max_actions, + "won": self.won, + "termination_reason": self.reason, + } + + def save(self, action=None, result=None): + if self.evidence_dir is None: + return + self.evidence_dir.mkdir(parents=True, exist_ok=True) + target = self.evidence_dir / "outcome.json" + temp = target.with_suffix(".tmp") + temp.write_text(json.dumps(self.state())) + temp.replace(target) + if action is not None: + with (self.evidence_dir / "trace.jsonl").open("a") as handle: + handle.write( + json.dumps( + {"index": self.count, "action": action, "result": result} + ) + + "\n" + ) + + def dispatch(self, payload): + with self.lock: + if self.reason is not None: + return { + "ok": False, + "error": "Episode has ended", + "episode": self.state(), + } + self.count += 1 + try: + action = Action.model_validate(payload) + if action.action == "submit_answer" and action.answer is not None: + result = upstream.submit_answer( + self.case_id, upstream.SubmitAnswerRequest(answer=action.answer) + ) + if result.get("is_win"): + self.won = True + self.reason = "success" + elif action.action == "investigate" and action.node_id is not None: + result = upstream.investigate( + self.case_id, + upstream.InvestigateRequest(node_id=action.node_id), + ) + elif ( + action.action in ("tool_call", "use_item") + and action.node_id is not None + ): + request_type, handler = ( + (upstream.ToolCallRequest, upstream.tool_call) + if action.action == "tool_call" + else (upstream.UseItemRequest, upstream.use_item) + ) + result = handler( + self.case_id, + request_type( + node_id=action.node_id, arguments=action.arguments or {} + ), + ) + else: + result = { + "ok": False, + "error": "Unknown action or missing action parameter", + } + except HTTPException as exc: + result = {"ok": False, "error": exc.detail} + except ValueError: + result = {"ok": False, "error": "Malformed action"} + except Exception: + log.exception("Puzzle service failure") + self.reason = "infrastructure_error" + self.save() + raise + if self.reason is None and self.count >= self.max_actions: + self.reason = "action_budget_exhausted" + result = public(result) + result["episode"] = self.state() + self.save(payload, result) + return result + + +def create_app( + scenario_path=None, max_actions=None, evidence_dir=None, worker_url=None +): + episode = Episode( + scenario_path or os.environ["SCENARIO_PATH"], + max_actions or int(os.environ.get("MAX_ACTIONS", "500")), + evidence_dir if evidence_dir is not None else os.environ.get("EVIDENCE_DIR"), + worker_url if worker_url is not None else os.environ.get("WORKER_URL"), + ) + app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) + app.state.episode = episode + + @app.get("/health") + def health(): + return {"ok": True} + + @app.get("/observation") + def observation(): + return {**public(episode.initial), "episode": episode.state()} + + @app.get("/state") + def state(): + return episode.state() + + @app.post("/action") + def action(payload: dict): + try: + return episode.dispatch(payload) + except Exception: + return JSONResponse( + status_code=503, + content={"ok": False, "error": "Puzzle infrastructure failure"}, + ) + + return app diff --git a/tasks/agentescape-25-skeleton-324d85de/environment/puzzle/upstream/models.py b/tasks/agentescape-25-skeleton-324d85de/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-25-skeleton-324d85de/environment/puzzle/upstream/models.py @@ -0,0 +1,108 @@ +from enum import Enum +from typing import List, Dict, Any, Optional +from pydantic import BaseModel, Field + +# 1. 细粒度接口类型定义 +class InterfaceType(str, Enum): + ''' + BIG_INT + TEXT_GENERIC + HEX_STRING + FILE_ID + HEX_STRING_KEY_AES + HEX_STRING_IV_AES + CODE_PYTHON + HIDDEN_ITEM + ITEM + ''' + # --- 基础类型 --- + TEXT_GENERIC = "Text_Generic" + BIG_INT = "Big_Int" + + # --- 编码/格式化字符串 --- + HEX_STRING = "Hex_String" # 通用 Hex + + # --- 特定用途的 Hex 字符串 (用于精确匹配) --- + HEX_STRING_KEY_AES = "Hex_String_Key_AES" + HEX_STRING_IV_AES = "Hex_String_IV_AES" + + # --- 文件类型 --- + FILE_ID = "File_Id" + + # --- 代码/脚本 --- + CODE_PYTHON = "Code_Python" + + # --- 实体交互类型 (严格命名) --- + ITEM = "Item" # 主动掉落接口 (Tool -> Item) + HIDDEN_ITEM = "Hidden_Item" # 被动掉落接口 (Item -> Item) + +# 3. 端口定义 +class Port(BaseModel): + name: str + type: InterfaceType + description: str + +# 4. 统一节点定义 (融合工具和物品) +class Node(BaseModel): + id: str + name: str + description: str + type: str # "Tool" or "Item" + + # 接口定义 + inputs: List[Port] = [] + outputs: List[Port] = [] + + # 状态字段 + content: Optional[Any] = None # 物品有内容,工具为None + if_success: Optional[bool] = None # 工具初始为False,物品为None + initial_visible: bool = False + + # 运行时状态 (Server维护) + is_revealed: bool = False + + # 标记该 Tool 节点是否有待触发的 HIDDEN_ITEM 掉落 + # 当 Tool 按照 golden_input 正确执行且有 HIDDEN_ITEM 输出边时设为 True + # 在 investigate 该 Tool 时触发掉落并重置为 False + has_hidden_item_ready: bool = False + + # 初始输入值 (metadata.initial_values.init_inputs,用于渐进式暴露判断) + init_input_values: Dict[str, Any] = {} + + # Golden 输入值 (nodes[].inputs[].value,用于评测验证) + golden_input_values: Dict[str, Any] = {} + + # Golden 输出值 (nodes[].outputs[].value,用于评测验证和 Item 节点的 content) + golden_output_values: Dict[str, Any] = {} + + # 实际获得的输出值历史 (工具每次执行后实际返回的输出列表,用于渐进式暴露判断) + # 格式: List[Dict[str, Any]],每个元素是一次执行的输出字典 + actual_outputs_history: List[Dict[str, Any]] = [] + + # 逻辑规则 (用于终端机等复杂物品) + logic_rules: Optional[Dict[str, Any]] = None + + def copy(self, **kwargs): + """Helper to create a copy with updated fields.""" + data = self.dict() + data.update(kwargs) + return Node(**data) + +# 5. 边定义 (拓扑结构) +class Edge(BaseModel): + source_id: str + target_id: str + connection_type: InterfaceType # 直接使用 InterfaceType + # 如果是 Data_Flow,指定端口对应关系 + source_port: Optional[str] = None + target_port: Optional[str] = None + +# 6. 完整图定义 +class GraphScenario(BaseModel): + case_id: str + title: str + intro_narrative: str + nodes: Dict[str, Node] + edges: List[Edge] + difficulty: int + win_node_id: str # 标记哪个节点是最终目标(通常是一个提交工具或最终物品) diff --git a/tasks/agentescape-25-skeleton-324d85de/environment/puzzle/upstream/server.py b/tasks/agentescape-25-skeleton-324d85de/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-25-skeleton-324d85de/environment/puzzle/upstream/server.py @@ -0,0 +1,1490 @@ +import json +import os +import time +import logging +import random +from pathlib import Path +from typing import Dict, Any, List, Optional +from datetime import datetime +from collections import defaultdict +from fastapi import FastAPI, HTTPException, Request +from fastapi.responses import JSONResponse +from fastapi.middleware.cors import CORSMiddleware +from pydantic import BaseModel, Field + +from models import GraphScenario, Node, InterfaceType +# from generator import ScenarioGenerator +from simulator import ToolSimulator +import uvicorn + +# 配置日志 +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler('server.log'), + logging.StreamHandler() + ] +) +logger = logging.getLogger(__name__) + +app = FastAPI( + title="AgentEscapeBench Universal Server", + version="1.0.0", + description="Industrial-grade evaluation server for escape room AI agents" +) + +# 添加 CORS 支持 +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# In-memory State +SCENARIOS: Dict[str, GraphScenario] = {} +SIMULATORS: Dict[str, ToolSimulator] = {} # case_id -> ToolSimulator +RAW_NODES_DATA: Dict[str, Dict[str, Any]] = {} # case_id -> node_id -> raw node data (for template_id) +FILE_METADATA: Dict[str, Dict[str, Any]] = {} # case_id -> metadata (for initial_values access) + +# Performance monitoring +STATS: Dict[str, Any] = { + "total_requests": 0, + "successful_requests": 0, + "failed_requests": 0, + "tool_calls": defaultdict(int), + "investigates": defaultdict(int), + "use_items": defaultdict(int), + "case_loads": 0, + "start_time": datetime.now() +} + +# Request timing middleware +@app.middleware("http") +async def add_process_time_header(request: Request, call_next): + start_time = time.time() + STATS["total_requests"] += 1 + + try: + response = await call_next(request) + STATS["successful_requests"] += 1 + process_time = time.time() - start_time + response.headers["X-Process-Time"] = str(process_time) + logger.info(f"{request.method} {request.url.path} - {response.status_code} - {process_time:.3f}s") + return response + except Exception as e: + STATS["failed_requests"] += 1 + logger.error(f"{request.method} {request.url.path} - Error: {str(e)}") + raise + +# Exception handler +@app.exception_handler(Exception) +async def global_exception_handler(request: Request, exc: Exception): + logger.error(f"Unhandled exception: {exc}", exc_info=True) + return JSONResponse( + status_code=500, + content={ + "ok": False, + "error": "Internal server error", + "detail": str(exc) if os.getenv("DEBUG") else "An error occurred" + } + ) + +# Health check endpoint +@app.get("/health") +def health_check(): + """健康检查端点""" + uptime = (datetime.now() - STATS["start_time"]).total_seconds() + return { + "status": "healthy", + "version": "1.0.0", + "uptime_seconds": uptime, + "loaded_cases": len(SCENARIOS), + "stats": { + "total_requests": STATS["total_requests"], + "successful_requests": STATS["successful_requests"], + "failed_requests": STATS["failed_requests"], + "success_rate": STATS["successful_requests"] / max(STATS["total_requests"], 1) + } + } + +# Statistics endpoint +@app.get("/stats") +def get_stats(): + """获取详细统计信息""" + return { + "stats": STATS, + "loaded_cases": list(SCENARIOS.keys()), + "uptime": str(datetime.now() - STATS["start_time"]) + } + +def _apply_progressive_reveal_at_init(scenario: GraphScenario): + """ + 在初始化时应用渐进式暴露机制(基于ITEM/HIDDEN_ITEM边) + + 新逻辑: + - 如果一个节点没有 ITEM/HIDDEN_ITEM 类型的入边,它就是初始可见的 + - 如果一个节点有 ITEM/HIDDEN_ITEM 类型的入边,它初始不可见,需要等待上游触发 + + Args: + scenario: 场景对象 + """ + # 收集所有有 ITEM/HIDDEN_ITEM 入边的节点 + nodes_with_item_edges = set() + for edge in scenario.edges: + if edge.connection_type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + nodes_with_item_edges.add(edge.target_id) + + logger.info(f"Nodes with ITEM/HIDDEN_ITEM incoming edges: {nodes_with_item_edges}") + + # 设置初始可见性:没有 ITEM/HIDDEN_ITEM 入边的节点初始可见 + initially_visible_count = 0 + for node_id, node in scenario.nodes.items(): + if node_id not in nodes_with_item_edges: + node.is_revealed = True + initially_visible_count += 1 + logger.info(f"Initial visible (no ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + else: + node.is_revealed = False + logger.debug(f"Initial hidden (has ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + + logger.info(f"Progressive reveal initialized: {initially_visible_count}/{len(scenario.nodes)} nodes initially visible") + + +def _check_inputs_match_golden(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> bool: + """ + 检查实际输入参数是否与 golden inputs 完全匹配 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + True 表示所有 golden inputs 都存在且值匹配 + """ + if not golden_inputs: + return True # 如果没有 golden inputs,认为匹配 + + for key, expected_value in golden_inputs.items(): + actual_value = arguments.get(key) + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) != str(expected_value): + logger.debug(f"Input mismatch for '{key}': expected '{expected_value}', got '{actual_value}'") + return False + + return True + + +def _get_parameter_validation_feedback(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> Dict[str, Any]: + """ + 对源头节点的参数进行详细验证,返回验证反馈 + + 注意:不返回期望值(expected),避免泄漏答案 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + 包含验证结果的字典: + - all_correct: bool - 所有参数是否正确 + - correct_params: List[str] - 正确的参数名列表 + - incorrect_params: List[str] - 错误的参数名列表(不包含期望值) + """ + if not golden_inputs: + return { + "all_correct": True, + "correct_params": [], + "incorrect_params": [] + } + + correct_params = [] + incorrect_params = [] + + for key, actual_value in arguments.items(): + # 只对用户实际提交的参数给反馈,未提交的参数不评价 + if key not in golden_inputs: + continue # 该参数不在 golden 中,跳过(如 _golden_inputs 等内部参数) + expected_value = golden_inputs[key] + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) == str(expected_value): + correct_params.append(key) + else: + # 只记录参数名,不包含期望值,避免泄漏答案 + incorrect_params.append(key) + + # all_correct:用户提交的所有参数都正确,且覆盖了全部 golden 参数 + all_provided_correct = len(incorrect_params) == 0 + all_golden_covered = all(k in arguments for k in golden_inputs) + return { + "all_correct": all_provided_correct and all_golden_covered, + "correct_params": correct_params, + "incorrect_params": incorrect_params + } + + +def _is_source_node(node_id: str, scenario: GraphScenario) -> bool: + """ + 判断节点是否是源头节点(完全没有任何入边的节点) + + 源头节点定义: + - 没有任何类型的入边(包括 DATA、ITEM、HIDDEN_ITEM) + - 即没有任何上游节点 + + Args: + node_id: 节点ID + scenario: 场景对象 + + Returns: + True 表示是源头节点 + """ + for edge in scenario.edges: + if edge.target_id == node_id: + # 只要有任何入边,就不是源头节点 + return False + + return True + + +def _check_and_reveal_ready_nodes(scenario: GraphScenario, recent_outputs: Dict[str, Any], source_node_id: str) -> List[Dict[str, Any]]: + """ + 检查并释放参数齐全的隐藏节点(渐进式暴露机制) + + 核心逻辑: + 1. 维护"可见值集合":包含所有被测模型当前可以看到的值 + - init_inputs 的值(初始可见) + - 工具执行后的实际输出值(运行时获得) + - 可见 Item 的输出值 + 2. 检查隐藏节点:该节点的所有 golden_input 值是否都在可见值集合中 + 3. 如果是,则释放该节点 + + Args: + scenario: 场景对象 + recent_outputs: 最近执行的工具的输出 + source_node_id: 刚执行的工具节点ID + + Returns: + 新释放的节点列表 + """ + newly_revealed = [] + + # 构建"可见值集合"(Set of visible values) + # 存储格式:set of values (转为字符串) + visible_values = set() + + # 1. 添加有意义的 init_inputs 值到可见值集合 + # Item 的 init_inputs 不应该加入,因为它们在密室中完全用不到 + for node_id, node in scenario.nodes.items(): + # 跳过源头 Item 节点(没有入边的 Item) + if node.type == "Item": + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,跳过其 init_inputs + continue + + # 添加其他节点的 init_inputs + for port_name, init_value in node.init_input_values.items(): + if init_value: + visible_values.add(str(init_value)) + + # 2. 添加已执行工具的所有历史输出值 + for node_id, node in scenario.nodes.items(): + if node.type == "Tool" and node.if_success and node.actual_outputs_history: + # 遍历所有历史执行记录 + for output_dict in node.actual_outputs_history: + for output_port_name, output_value in output_dict.items(): + if output_value: + visible_values.add(str(output_value)) + + # 3. 添加已被 investigate 的 Item 的 golden 输出值 + # 注意:Item 可见不等于其输出值可见,需要 investigate 后才能获得 + # 这里我们使用 actual_outputs_history 来标记 Item 是否已被 investigate + for node_id, node in scenario.nodes.items(): + if node.type == "Item" and node.is_revealed and node.actual_outputs_history: + # Item 通常只会被 investigate 一次,但为了一致性也使用历史列表 + for output_dict in node.actual_outputs_history: + for port_name, port_value in output_dict.items(): + if port_value: + visible_values.add(str(port_value)) + + # 遍历所有隐藏的节点,检查其 golden_input 是否都在可见值集合中 + for node_id, node in scenario.nodes.items(): + # 跳过已可见的节点 + if node.is_revealed: + continue + + # 只检查工具节点(物品节点由 ITEM 输出触发) + if node.type != "Tool": + continue + + # 检查该节点的所有 golden_input 值是否都在可见值集合中 + all_inputs_ready = True + missing_values = [] + + for input_port_name, golden_input_value in node.golden_input_values.items(): + # 检查这个 golden 值是否在可见值集合中 + if str(golden_input_value) not in visible_values: + all_inputs_ready = False + missing_values.append(f"{input_port_name}={golden_input_value}") + + # 如果所有 golden_input 值都在可见值集合中,释放该节点 + if all_inputs_ready and len(node.golden_input_values) > 0: + logger.info(f"All golden inputs ready for {node_id}: {list(node.golden_input_values.values())}") + + # 如果所有输入都齐全,释放该节点 + if all_inputs_ready: + node.is_revealed = True + + # 构建节点信息返回给模型 + node_info = { + "id": node.id, + "type": node.type, + "can_investigate": True, + "hint": "This tool's input parameters are now complete, you can use investigate to view detailed information" + } + + # if node.name: + # node_info["name"] = node.name + if node.description: + node_info["description"] = node.description + + newly_revealed.append(node_info) + logger.info(f"Progressive reveal: {node_id} is now ready (all inputs satisfied)") + + return newly_revealed + + +def _initialize_node_values(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]): + """ + Initialize node state and load values from port value fields. + 应用渐进式暴露机制:初始时只显示参数齐全的节点(源头节点) + + 重要区分: + 1. input_values: 只加载 metadata.initial_values 中的 init_inputs(真正的初始值) + 2. output_values: 加载 nodes[].outputs[].value(golden 输出,用于验证) + """ + # 第一步:加载所有节点的值,并将所有节点初始设为隐藏 + initial_values = metadata.get('initial_values', {}) + + for node_id, node in scenario.nodes.items(): + # 忽略 initial_visible 字段,初始全部隐藏 + # 由渐进式暴露机制根据参数齐全情况决定是否显示 + node.is_revealed = False + + if node.type == "Tool": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + elif node.type == "Item": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + + # 从 JSON 加载值 + if node_id in raw_nodes_data: + node_data = raw_nodes_data[node_id] # node_data是json文件中nodes中的字典 + + # 【重要】只加载 metadata.initial_values 中的初始输入值 + if node_id in initial_values: + init_data = initial_values[node_id] + # 加载初始输入值(用于渐进式暴露判断) + for port_name, port_value in init_data.get('init_inputs', {}).items(): + node.init_input_values[port_name] = port_value + + # 【评测用】加载 golden 输入值(用于验证模型传入的参数是否正确) + for input_port_data in node_data.get('inputs', []): + if 'value' in input_port_data: + node.golden_input_values[input_port_data['name']] = input_port_data['value'] + + # 【评测用】加载 golden 输出值(用于验证工具调用是否正确,以及 Item 节点的 content) + for output_port_data in node_data.get('outputs', []): + if 'value' in output_port_data: + node.golden_output_values[output_port_data['name']] = output_port_data['value'] + + # For Items, set content from golden_output_values + if node.type == "Item" and node.golden_output_values: + # Item 的 content 是其第一个 golden 输出值 + node.content = list(node.golden_output_values.values())[0] + + # 第二步:应用渐进式暴露机制 + # 检查所有节点,根据参数齐全情况释放源头节点(工具 + Item) + _apply_progressive_reveal_at_init(scenario) + +def _build_node_info(node: Node, raw_nodes_data: Dict[str, Any]) -> Dict[str, Any]: + """ + 构建节点信息(工具或物品) + + Args: + node: 节点对象 + raw_nodes_data: 原始节点数据(用于获取 template_id 等) + + Returns: + 节点信息字典 + """ + if node.type == "Tool": + # 过滤掉输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口) + # 这些端口仅用于控制掉落机制,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + tool_info = { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Tool", + "inputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.inputs if p.type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]], + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id(工具的标准名称) + if node.id in raw_nodes_data: + node_data = raw_nodes_data[node.id] + template_id = node_data.get('template_id') + if template_id: + tool_info['template_id'] = template_id + + return tool_info + + elif node.type == "Item": + return { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Item" + } + + else: + return { + "id": node.id, + # "name": node.name, + "type": node.type + } + +def _get_initial_observation(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]) -> Dict[str, Any]: + """ + Generate initial observation for the agent (what they see when entering the room). + + 策略: + - Tools: 只显示名称和描述,不显示接口定义。需要 investigate 才能获得详细接口信息。 + - Items: 只显示存在,不显示内容。需要 investigate 才能获得内容值。 + - init_inputs: 作为"可用信息"告诉模型,这些是可以用作工具参数的初始值。 + - init_outputs: 不告诉模型(这些是答案,需要模型通过调用工具获得)。 + """ + available_entities = [] # 统一的实体列表(Tools 和 Items) + available_information = [] # 可用的初始信息(来自 init_inputs) + + # 从 metadata.initial_values 提取 init_inputs 作为可用信息 + # 只提供值本身,不透露这些值对应哪个节点的哪个参数,让模型自己推理 + # 注意:跳过源头 Item(没有入边的 Item)的 init_inputs,因为它们在密室中完全用不到 + initial_values = metadata.get('initial_values', {}) + # initial_values字段的格式 + # "initial_values": { + # "terminal_1": { + # "init_inputs": {}, + # "init_outputs": { + # "text_output": "System initialization complete.", + # "hex_output": "48656c6c6f20576f726c64", + # "item_dispenser": "掉落了一张纸条,上面写着“请勿随意触摸终端”" + # } + # } + # } + for node_id, init_data in initial_values.items(): + # 获取节点信息,判断是否为源头 Item + node = scenario.nodes.get(node_id) + if node and node.type == "Item": + # 检查是否为源头 Item(没有入边) + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,检查是否有 init_inputs + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 有 init_inputs,需要暴露这些参数 + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + # 处理完后跳过后续的通用逻辑 + continue + + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 为每个 init_input 值创建一个信息条目(不包含 source_node 和 parameter 信息) + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + + for node in scenario.nodes.values(): + if node.is_revealed: + # Tools: 只显示基本信息,提示可以 investigate 查看详细接口 + if node.type == "Tool": + tool_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Tool", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the tool's detailed interface information for calling" + } + # 只在 name 非空时添加 + # if node.name: + # tool_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_info["description"] = node.description + + available_entities.append(tool_info) + + # Items: 只显示基本信息,提示可以 investigate 查看内容 + elif node.type == "Item": + item_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Item", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the item's content" + } + # 只在 name 非空时添加 + # if node.name: + # item_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + item_info["description"] = node.description + + available_entities.append(item_info) + + return { + "narrative": scenario.intro_narrative, + "available_entities": available_entities, # 使用统一的实体列表 + "available_information": available_information, # 可用的初始信息(只包含 init_inputs) + "win_node_id": scenario.win_node_id # 胜利节点ID,让模型知道需要关注哪个节点 + } + +@app.post("/env/reset") +def reset_case(case_id: str = None, case_file_path: str = None, session_id: str = None): + """Loads a specific case from file and resets it. + + Args: + case_id: Optional case ID for resetting an existing case + case_file_path: Path to case file for loading a new case + session_id: Optional session ID to ensure isolation between concurrent evaluations + """ + logger.info(f"Reset request - case_id: {case_id}, case_file_path: {case_file_path}, session_id: {session_id}") + STATS["case_loads"] += 1 + + if case_file_path: + if not os.path.exists(case_file_path): + logger.error(f"Case file not found: {case_file_path}") + raise HTTPException(status_code=404, detail=f"File not found: {case_file_path}") + try: + with open(case_file_path, "r", encoding="utf-8") as f: + file_data = json.load(f) + + # 转换格式:从 DAG executor 生成的格式转换为 GraphScenario 格式 + # 1. 提取 metadata + metadata = file_data.get('metadata', {}) + + # 2. 生成 case_id, title, intro_narrative + # 【修复】为每个评测会话生成唯一的 case_id,防止并发评测时状态污染 + base_name = os.path.basename(case_file_path).replace('.json', '').replace('_full', '').replace('_full2', '') + + if session_id: + # 如果提供了 session_id,使用它来确保唯一性 + case_id = f"{base_name}_{session_id}" + else: + # 否则使用时间戳和随机数确保唯一性 + unique_suffix = f"{int(time.time() * 1000)}_{random.randint(1000, 9999)}" + case_id = f"{base_name}_{unique_suffix}" + + file_data['case_id'] = case_id + logger.info(f"Generated unique case_id: {case_id} (base: {base_name}, session: {session_id})") + + if 'title' not in file_data: + file_data['title'] = f"Escape Room: {file_data['case_id']}" + + if 'intro_narrative' not in file_data: # 目前的json文件中已经有了intro_narrative字段,不会使用下面一行的内容,而是使用每个评测问题的json文件中的对应字段 + 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]".' + + # 3. 转换 nodes 列表为字典(DAG executor 生成的文件中 nodes 是列表格式) + nodes_dict = {} + for node_data in file_data['nodes']: + nodes_dict[node_data['id']] = node_data # 这里的id是template_id之后可能添加一个后缀 + file_data['nodes'] = nodes_dict # 把列表转成一个字典 + + # 4. 添加缺失的字段 + if 'difficulty' not in file_data: + file_data['difficulty'] = metadata.get('total_nodes', 5) + + if 'win_node_id' not in file_data: + file_data['win_node_id'] = metadata.get('win_node_id', '') + + scenario = GraphScenario(**file_data) + + # Extract raw nodes data for template_id access + # nodes 已经在上面转换为字典格式 + raw_nodes_data = file_data.get('nodes', {}) + RAW_NODES_DATA[scenario.case_id] = raw_nodes_data + + # Store metadata for initial values access + FILE_METADATA[scenario.case_id] = metadata + + logger.info(f"Successfully parsed case file: {scenario.case_id}, nodes: {len(scenario.nodes)}, edges: {len(scenario.edges)}") + except Exception as e: + logger.error(f"Failed to load case file: {str(e)}", exc_info=True) + raise HTTPException(status_code=500, detail=f"Failed to load case file: {str(e)}") + + # Initialize node state and load values + _initialize_node_values(scenario, raw_nodes_data, metadata) + + SCENARIOS[scenario.case_id] = scenario + simulator = ToolSimulator() + SIMULATORS[scenario.case_id] = simulator + + 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'])}") + + # 生成初始观察信息(进入密室后看到的环境) + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + ''' + initial_observation的格式: + { + "narrative": scenario.intro_narrative, + "available_entities": available_entities # 使用统一的实体列表 + "available_information": available_information # 可用的初始信息(只包含 init_inputs) + } + ''' + + return { + "ok": True, + "message": f"Case loaded from {case_file_path}", + "case_id": scenario.case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果没有提供 case_file_path,但提供了 case_id,则尝试从内存重置 + if case_id and case_id in SCENARIOS: + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + metadata = FILE_METADATA.get(case_id, {}) + + # Reset dynamic fields and re-apply progressive reveal + # 重新初始化节点状态(包括渐进式暴露) + _initialize_node_values(scenario, raw_nodes_data, metadata) + + 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'])}") + + # 生成初始观察信息 + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + + return { + "ok": True, + "message": f"Case {case_id} reset.", + "case_id": case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果既没有 case_file_path,也没有在内存中找到,返回错误 + raise HTTPException( + status_code=400, + detail="Must provide case_file_path to load a new case, or use case_id to reset an existing case." + ) + +class InvestigateRequest(BaseModel): + node_id: str + +@app.post("/env/{case_id}/investigate") +def investigate(case_id: str, req: InvestigateRequest): + """ + Investigates a Tool or Item to reveal detailed information. + + - For Tools: Returns detailed interface information (inputs/outputs) needed to call the tool + - For Items: Returns content value and triggers hidden item drops + """ + logger.info(f"Investigate request - case_id: {case_id}, node_id: {req.node_id}") + STATS["investigates"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + node = scenario.nodes[req.node_id] + + if not node.is_revealed: + logger.warning(f"Attempt to investigate hidden node: {req.node_id}") + return {"ok": False, "error": "Node is not visible yet."} + + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + newly_revealed = [] + + # 处理 Tool 的 investigate + if node.type == "Tool": + logger.info(f"Investigating tool: {req.node_id}") + + # 返回工具的详细接口信息 + # id 字段使用 node.id(节点唯一标识),agent 用这个字段识别和调用具体的节点 + # template_id 是工具类型标识符,Agent 内部用于判断工具特性(如 terminal 类工具参数可选) + # 注意:只过滤输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口),这些端口仅用于控制掉落,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + # 【端口上游依赖提示 & 初始值直接给出】 + # 针对参数语义模糊(全为数字类型)的工具,在 investigate 返回信息中标注 + # 哪个输入端口来自哪个上游节点(upstream_from)。 + # 对于所有工具:若该节点不是纯源头节点(有任意数据流入边), + # 且某个端口没有上游入边(值来自初始可见参数),则直接给出该端口的 golden input 值。 + AMBIGUOUS_TOOLS = { + "num_base_convert", "calc_modexp", "calc_modexp_int", + "calc_inv_mod", "calc_inv_mod_int", "crypto_rsa_decrypt_hex", "geo_haversine" + } + # Terminal 类工具自带参数对错反馈机制,玩家/模型可自行试错, + # 无需在 investigate 时直接暴露 init_value + SELF_FEEDBACK_TOOLS = { + "terminal_1", "terminal_2", + "Logic Terminal", "Math Terminal", "Encryption Terminal", "Sequence Terminal" + } + _template_id_for_hint = raw_nodes_data.get(node.id, {}).get("template_id", "") + # 构建数据流入边映射(对所有工具):{target_port -> (source_node_id, source_port)} + _upstream_map = {} + for _edge in scenario.edges: + if (_edge.target_id == node.id + and _edge.connection_type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM] + and _edge.target_port is not None): + _upstream_map[_edge.target_port] = (_edge.source_id, _edge.source_port) + # 判断该节点是否有任意数据流入边(即不是纯源头节点) + _has_any_upstream = len(_upstream_map) > 0 + # 判断该节点是否有任意入边(包括 ITEM/HIDDEN_ITEM 掉落边) + # 有任意入边(含掉落边)但无数据流入边的节点,其输入来自初始可见参数,应直接给出 + _has_any_edge = any(_edge.target_id == node.id for _edge in scenario.edges) + # 构建 inputs 列表 + _inputs_list = [] + for p in node.inputs: + if p.type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + continue + port_dict = {"name": p.name, "type": p.type, "description": p.description} + if p.name in _upstream_map: + # 该端口有上游数据流依赖,且属于语义模糊工具 → 标注来源 + if _template_id_for_hint in AMBIGUOUS_TOOLS: + src_node_id, src_port = _upstream_map[p.name] + port_dict["upstream_from"] = f"{src_node_id}.{src_port}" if src_port else src_node_id + elif _has_any_edge and _template_id_for_hint not in SELF_FEEDBACK_TOOLS: + # 该节点有任意入边,但此端口没有数据流入边 → 值来自初始可见参数,直接给出 + # 排除自带反馈机制的 terminal 类工具(它们通过执行结果反馈对错,无需提前暴露参数值) + golden_val = node.golden_input_values.get(p.name) + if golden_val is not None: + port_dict["init_value"] = golden_val + _inputs_list.append(port_dict) + + tool_details = { + "id": node.id, # 节点 ID,用于唯一标识和调用这个具体节点 + "type": "Tool", + "inputs": _inputs_list, + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id 用于 Agent 内部判断工具类型(不会展示给被测模型) + if node.id in raw_nodes_data: + template_id = raw_nodes_data[node.id].get('template_id') + if template_id: + tool_details["_template_id"] = template_id # 使用下划线前缀标记为内部字段 + + # 只在 name 非空时添加 + # if node.name: + # tool_details["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_details["description"] = node.description + + # 添加 narrative 字段(如果存在) + if node.id in raw_nodes_data: + narrative = raw_nodes_data[node.id].get('narrative') + if narrative: + tool_details['narrative'] = narrative + + # 不再返回 init_values,避免泄漏答案 + # investigate 只应该返回工具的接口定义,不应该暴露初始值 + + # 【新增】检查该 Tool 是否有待触发的 HIDDEN_ITEM 掉落 + # 如果该工具已按照 golden_input 正确执行,且有 HIDDEN_ITEM 输出边,则触发掉落 + if node.has_hidden_item_ready: + logger.info(f"Tool has HIDDEN_ITEM ready - triggering passive drop for: {req.node_id}") + + # 遍历该工具的所有 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + # 重置标志,已经触发过了,避免重复 + node.has_hidden_item_ready = False + + logger.info(f"Tool investigation successful - node: {req.node_id}, revealed: {len(newly_revealed)}") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Tool", + "details": tool_details + } + + # 如果有新掉落的节点,添加到响应中 + if newly_revealed: + result["newly_revealed"] = newly_revealed + + return result + + # 处理 Item 的 investigate + elif node.type == "Item": + logger.info(f"Investigating item: {req.node_id}") + + # 【第一步】检查该 Item 是否有需要参数的输入端口 + # 如果有,且尚未通过 use_item 验证,则不返回内容,只返回参数要求 + required_inputs = [] + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + inputs_info = raw_node.get('inputs', []) + required_inputs = [ + { + "name": inp.get("name"), + "type": inp.get("type"), + "description": inp.get("description", "") + } + for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + # 如果有 required_inputs 且尚未通过 use_item 验证(if_success == False) + # 则不返回内容,只返回参数要求提示 + if required_inputs and not node.if_success: + logger.info(f"Item has required inputs and not yet unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "required_inputs": required_inputs + } + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + param_names = ', '.join([inp['name'] for inp in required_inputs]) + 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}" + + return result + + # 【新增】如果有 required_inputs 且已经通过 use_item 验证(if_success == True) + # 则返回提示:该节点已经被成功解决 + if required_inputs and node.if_success: + logger.info(f"Item has required inputs and already unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "message": "This item has already been successfully unlocked by you." + } + return result + + # 【第二步】该 Item 没有 required_inputs 或已通过验证,返回内容 + # 1. 返回 Item 的 golden_output_values(即 Item 的内容) + # 注意:某些 Item 仅用于触发 HIDDEN_ITEM 掉落,没有实际内容 + has_actual_content = bool(node.golden_output_values) or node.content is not None + content = node.golden_output_values if node.golden_output_values else node.content + + # 【关键】将 golden_output_values 追加到 actual_outputs_history,标记该 Item 已被 investigate + # 这样在渐进式暴露时,这些值才会被加入可见值集合 + # 即使是空字典(仅触发 HIDDEN_ITEM 的 Item),也要记录,以便渐进式暴露逻辑知道该 Item 已被调查 + if node.golden_output_values is not None: + node.actual_outputs_history.append(dict(node.golden_output_values)) + + # 2. Trigger Hidden Item Drops (Passive Drop) + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + logger.info(f"Item investigation successful - node: {req.node_id}, has_content: {has_actual_content}, revealed: {len(newly_revealed)}") + + # 【渐进式暴露】旧机制(基于 golden_input)已禁用 + # 现在完全由 ITEM/HIDDEN_ITEM 边触发控制节点可见性 + # 上面的 HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, node.golden_output_values or {}, node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # logger.info(f"Progressive reveal after Item investigate: {len(progressive_revealed)} nodes now ready") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Item" + } + + # 只在有实际内容时才添加 content 字段 + # 对于仅触发 HIDDEN_ITEM 掉落的 Item,不返回 content 字段,避免返回 None 或空字典让模型困惑 + if has_actual_content: + result["content"] = content + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型通过 investigate 获得内容后,需要自己识别这是否是胜利字符串 + + return result + + else: + logger.warning(f"Attempt to investigate unknown node type: {req.node_id} (type: {node.type})") + return {"ok": False, "error": f"Cannot investigate node type: {node.type}"} + +class ToolCallRequest(BaseModel): + node_id: str # 使用 node_id 精确指定要调用的节点 + arguments: Dict[str, Any] + +@app.post("/env/{case_id}/tool_call") +def tool_call(case_id: str, req: ToolCallRequest): + """Executes a tool and triggers item drops.""" + logger.info(f"Tool call request - case_id: {case_id}, node_id: {req.node_id}, args: {list(req.arguments.keys())}") + STATS["tool_calls"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + + # 通过 node_id 精确查找节点 + node_id = req.node_id + if node_id not in scenario.nodes: + logger.error(f"Node not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + tool_node = scenario.nodes[node_id] + + if not tool_node: + logger.error(f"Tool not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Tool not found") + + if not tool_node.is_revealed: + logger.warning(f"Attempt to call hidden tool: {node_id}") + return {"ok": False, "error": "Tool is not visible yet."} + + if tool_node.type != "Tool": + logger.warning(f"Attempt to call non-tool node: {node_id} (type: {tool_node.type})") + return {"ok": False, "error": "Only tools can be called."} + + # 1. Execute Tool (Real Execution via Simulator) + simulator = SIMULATORS[case_id] + + # Get tool name from template_id if available, otherwise use node name + tool_name = tool_node.name + if case_id in RAW_NODES_DATA and node_id in RAW_NODES_DATA[case_id]: + template_id = RAW_NODES_DATA[case_id][node_id].get('template_id') + if template_id: + tool_name = template_id + + # 文件处理工具和 Terminal 需要验证输入并返回预先计算的输出 + # 传递节点的实际输入输出值(从 DAG 执行后填充的数据) + tool_arguments = dict(req.arguments) # Make a copy + + # 传递节点的 golden values(从 JSON 的 inputs[].value 和 outputs[].value 加载) + # 用于在评测阶段验证被测模型传入的参数是否正确 + if tool_node.golden_input_values: + tool_arguments['_golden_inputs'] = tool_node.golden_input_values + if tool_node.golden_output_values: + tool_arguments['_golden_outputs'] = tool_node.golden_output_values + + logger.debug(f"Executing tool {tool_name} (node: {tool_node.name}) with args {tool_arguments}") + + try: + output_values = simulator.execute(tool_name, tool_arguments) + logger.info(f"Tool invoked - {tool_name}: {list(output_values.keys())}") + except Exception as e: + logger.error(f"Tool execution failed - {tool_name}: {str(e)}", exc_info=True) + return {"ok": False, "error": f"Tool execution failed: {str(e)}"} + + # 检查验证结果(精细化错误反馈) + validation = output_values.pop("_validation", {"valid": True}) + + if not validation["valid"]: + # 根据错误类型构造友好的错误消息 + error_type = validation.get("error_type") + + if error_type == "missing_required": + missing = validation.get("missing_params", []) + error_msg = f"Error: Missing required parameters {', '.join(missing)}" + + elif error_type == "type_error": + param = validation.get("param_name") + message = validation.get("message", "Parameter type error") + error_msg = f"Error: {message}" + + elif error_type == "incomplete_optional": + provided = validation.get("provided_params", []) + missing = validation.get("missing_params", []) + error_msg = ( + f"Hint: You provided some parameters ({', '.join(provided)}), " + f"but may also need: {', '.join(missing)}.\n" + f"Trying to provide these parameters together might yield better results." + ) + + elif error_type == "value_mismatch": + param = validation.get("param_name") + hint = validation.get("hint", "Parameter value may be incorrect") + error_msg = f"Hint: {hint}.\nPlease check if this parameter value meets the requirements." + + else: + error_msg = validation.get("hint") or validation.get("message", "Parameter validation failed") + + logger.info(f"Tool validation failed - {tool_name}: {error_type}") + return { + "ok": False, + "error": error_msg, + "error_type": error_type + } + + # Simulate success + tool_node.if_success = True + + # 【关键】将本次执行的输出值追加到历史列表(用于渐进式暴露判断) + # 每次调用都会记录,不会覆盖之前的执行结果 + tool_node.actual_outputs_history.append(dict(output_values)) + + # 2. 检查是否应该触发掉落(只有输入参数正确时才掉落) + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, tool_node.golden_input_values) + + newly_revealed = [] + investigate_hints = [] # 提示模型哪些节点可以 investigate 来发现隐藏内容 + + if inputs_match_golden: + logger.info(f"✓ Tool inputs match golden - node: {node_id}, triggering drops") + + # 检查该工具是否有 ITEM 或 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == tool_node.id: + target_node = scenario.nodes[edge.target_id] + + # ITEM 边:立即掉落(主动掉落) + if edge.connection_type == InterfaceType.ITEM: + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from {node_id})") + + # HIDDEN_ITEM 边:不立即掉落,标记并提示(被动掉落) + elif edge.connection_type == InterfaceType.HIDDEN_ITEM: + # 标记该工具有待触发的 HIDDEN_ITEM 掉落 + tool_node.has_hidden_item_ready = True + + # 提示模型可以 investigate 这个工具来发现隐藏内容 + hint_info = { + "tool_id": tool_node.id, + "hint": f"Tool '{tool_node.id}' seems to hide something, try investigating it to discover more information" + } + # if tool_node.name: + # hint_info["tool_name"] = tool_node.name + + investigate_hints.append(hint_info) + logger.info(f"HIDDEN_ITEM ready: {tool_node.id} -> {target_node.id} (will drop on investigate)") + else: + logger.info(f"✗ Tool inputs do NOT match golden - node: {node_id}, no drops triggered") + + response = { + "ok": True, + "message": "Tool invoked", + "output_values": output_values # Return raw outputs to Agent + } + + # 【新增】对源头节点进行参数验证反馈 + # 源头节点:没有数据流入边的节点,这些节点的参数需要模型自己推理 + # 验证模型使用的参数是否正确,并提供明确的反馈 + if _is_source_node(node_id, scenario) and tool_node.golden_input_values: + validation_feedback = _get_parameter_validation_feedback(req.arguments, tool_node.golden_input_values) + + if validation_feedback["all_correct"]: + # 用户提交了全部 golden 参数且全部正确 + response["parameter_feedback"] = { + "status": "correct", + "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." + } + logger.info(f"✓ Source node parameters all correct - node: {node_id}") + elif validation_feedback["incorrect_params"]: + # 有提交了但值错误的参数,只对这些参数给出反馈 + incorrect_list = [] + for param_name in validation_feedback["incorrect_params"]: + incorrect_list.append(f" - Parameter '{param_name}' is incorrect") + + correct_info = "" + if validation_feedback["correct_params"]: + correct_info = f"\n✓ Correct parameters: {', '.join(validation_feedback['correct_params'])}" + + response["parameter_feedback"] = { + "status": "incorrect", + "message": ( + f"⚠️ Some parameters are incorrect:\n" + + "\n".join(incorrect_list) + + correct_info + + 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." + ), + "incorrect_params": validation_feedback["incorrect_params"], + "correct_params": validation_feedback["correct_params"] + } + logger.info(f"✗ Source node parameters incorrect - node: {node_id}, incorrect: {validation_feedback['incorrect_params']}") + # else: 部分提交且全部正确 → 不给任何 parameter_feedback,避免对未提交的参数发表意见 + + # 检查工具调用是否完全正确(输出与 golden outputs 匹配) + # 用于给模型正向反馈,让它知道这个工具已经正确调用过,避免重复调用 + # 注意:只有当输出完全匹配时才标记为 correct,不会在错误时提供具体错误信息 + # if tool_node.golden_output_values and output_values: + # is_correct = True + # for port_name, expected_value in tool_node.golden_output_values.items(): + # actual_value = output_values.get(port_name) + # if str(actual_value) != str(expected_value): + # is_correct = False + # break + + # if is_correct: + # response["tool_call_correct"] = True + # logger.info(f"✓ Tool called with correct result - node: {node_id}") + + # 只在有新内容掉落时才返回 newly_revealed + if newly_revealed: + response["newly_revealed"] = newly_revealed + + # 添加 investigate 提示(对于有待触发 HIDDEN_ITEM 掉落的工具) + if investigate_hints: + response["investigate_hints"] = investigate_hints + + # 3. 渐进式暴露机制 - 现在完全由 ITEM/HIDDEN_ITEM 边控制 + # 旧机制(基于 golden_input 检查)已被禁用 + # 新机制中,节点的可见性只由 ITEM/HIDDEN_ITEM 边触发决定 + # 上面的 ITEM/HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, output_values, tool_node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # response["newly_revealed"] = newly_revealed + # logger.info(f"Progressive reveal: {len(progressive_revealed)} nodes now ready") + + # Check if this is the win node + if node_id == scenario.win_node_id: + # 验证输出值是否等于预期的胜利值 + # 从节点的 golden_output_values 中获取预期值(在 _initialize_node_values 时从 JSON 加载) + expected_outputs = tool_node.golden_output_values + + # 检查实际输出是否与预期输出匹配 + is_correct = False + victory_string = None + mismatch_info = [] + + if expected_outputs and output_values: + # 检查每个预期输出端口的值是否匹配 + is_correct = True + for port_name, expected_value in expected_outputs.items(): + actual_value = output_values.get(port_name) + if actual_value != expected_value: + is_correct = False + mismatch_info.append(f"Port '{port_name}': expected '{expected_value}', actual '{actual_value}'") + logger.warning(f"Win node output mismatch - port: {port_name}, expected: {expected_value}, actual: {actual_value}") + + # 如果所有输出都匹配,使用第一个输出作为胜利字符串 + if is_correct and output_values: + victory_string = list(output_values.values())[0] + else: + logger.warning(f"Win node called but missing output values - expected: {expected_outputs}, actual: {output_values}") + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型调用工具获得输出后,需要自己识别这是否是胜利字符串并提交 + if is_correct: + logger.info(f"🎯 Win node called with correct output - case: {case_id}, node: {node_id}, victory: {victory_string}") + else: + logger.info(f"❌ Win node called with incorrect output - case: {case_id}, node: {node_id}") + + return response + +class UseItemRequest(BaseModel): + node_id: str = Field(..., description="The ID of the Item node to use (must be Item type)") + arguments: Dict[str, Any] = Field(default_factory=dict, description="Input arguments to provide to the item") + +@app.post("/env/{case_id}/use_item") +def use_item(case_id: str, req: UseItemRequest): + """ + Use an Item node by providing input arguments. + + This is specifically for Item nodes that require parameters to be "unlocked" or "activated", + such as containers that need a password/fingerprint. + + - Validates that the node is of type Item + - Checks if provided arguments match the item's golden_input_values + - If match: triggers ITEM-type edge drops and returns the item's content + - If not match: returns error message + """ + logger.info(f"Use item request - case_id: {case_id}, node_id: {req.node_id}, args: {req.arguments}") + STATS["use_items"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + item_node = scenario.nodes[req.node_id] + + if not item_node.is_revealed: + logger.warning(f"Attempt to use hidden item: {req.node_id}") + return {"ok": False, "error": "Item is not visible yet."} + + if item_node.type != "Item": + logger.warning(f"Attempt to use non-item node: {req.node_id} (type: {item_node.type})") + return {"ok": False, "error": "Only Item nodes can be used with use_item. Tools should be called with tool_call."} + + # 【新增】检查该 Item 是否已经被成功解锁 + # 如果已经被正确使用过,直接返回成功提示 + if item_node.if_success: + logger.info(f"Item already unlocked, returning success message: {req.node_id}") + return { + "ok": True, + "message": "This item has already been successfully unlocked by you." + } + + # 检查该 Item 是否真的需要通过 use_item 提供参数 + # 只有当 Item 有非 Item/Hidden_Item 类型的输入时,才应该使用 use_item + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + non_hidden_inputs = [ + inp for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + if not non_hidden_inputs: + # 该 Item 不需要参数,应该只使用 investigate + logger.warning(f"Attempt to use_item on a node that doesn't require parameters: {req.node_id}") + return { + "ok": False, + "error": "This item does not require parameters. Please use investigate to examine the item directly." + } + + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, item_node.golden_input_values) + + if not inputs_match_golden: + logger.info(f"✗ Item inputs do NOT match golden - node: {req.node_id}") + # 提供更详细的错误信息,帮助 Agent 理解问题 + # 只显示非 Item/Hidden_Item 类型的参数(Hidden_Item 由系统自动处理) + expected_params = [] + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + expected_params = [ + inp.get("name") for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + provided_params = list(req.arguments.keys()) if req.arguments else [] + + # 检查参数名是否匹配 + if set(expected_params) == set(provided_params): + # 参数名正确但值不匹配 - 不泄漏正确的值 + error_msg = f"Parameter names are correct, but the parameter values are incorrect. Please try using different parameter values." + else: + error_msg = f"Parameter names do not match. Expected parameter names: {expected_params}, you provided: {provided_params}." + + return { + "ok": False, + "error": error_msg + } + + logger.info(f"✓ Item inputs match golden - node: {req.node_id}, activating item") + + # 标记该 Item 已被正确使用 + item_node.if_success = True + + # 将 golden_output_values 追加到 actual_outputs_history + if item_node.golden_output_values: + item_node.actual_outputs_history.append(dict(item_node.golden_output_values)) + + # 触发 ITEM 类型边的掉落 + newly_revealed = [] + for edge in scenario.edges: + if edge.source_id == item_node.id and edge.connection_type == InterfaceType.ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from use_item on {req.node_id})") + + # 检查是否为 Win Node + win_node_id = scenario.win_node_id + is_win_node = (req.node_id == win_node_id) + + # 构建返回结果 + result = { + "ok": True, + "message": "Item used successfully.", + "content": item_node.golden_output_values if item_node.golden_output_values else None + } + + # 获取 narrative(如果存在) + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + narrative = raw_nodes_data[req.node_id].get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 如果是 Win Node,只记录日志 + if is_win_node: + logger.info(f"Win node (Item) unlocked via use_item - case: {case_id}, node: {req.node_id}") + + return result + + +class SubmitAnswerRequest(BaseModel): + answer: str = Field(..., description="The victory string to submit") + +@app.post("/env/{case_id}/submit_answer") +def submit_answer(case_id: str, req: SubmitAnswerRequest): + """ + 提交答案接口 + 被测模型在获得胜利字符串提示后,需要调用此接口提交答案 + """ + logger.info(f"Submit answer request - case_id: {case_id}, answer: {req.answer}") + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + + # 获取 win_node 的 golden_output_values + if not scenario.win_node_id: + logger.error(f"No win node defined for case: {case_id}") + return { + "ok": False, + "error": "This case has no victory node defined" + } + + win_node = scenario.nodes.get(scenario.win_node_id) + if not win_node: + logger.error(f"Win node not found: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node does not exist" + } + + # 获取正确的胜利字符串(取第一个 golden_output_value) + if win_node.golden_output_values: + correct_answer = list(win_node.golden_output_values.values())[0] + else: + logger.error(f"Win node has no golden_output_values: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node has no correct answer" + } + + # 验证提交的答案 + if req.answer == correct_answer: + logger.info(f"🎉 CORRECT ANSWER SUBMITTED - case: {case_id}, answer: {req.answer}") + return { + "ok": True, + "is_win": True, + "victory_message": f"🎉 Congratulations on successfully escaping the room! Your answer is correct: {req.answer}" + } + else: + logger.info(f"❌ INCORRECT ANSWER SUBMITTED - case: {case_id}, submitted: {req.answer}, correct: {correct_answer}") + return { + "ok": True, + "is_win": False, + "error": f"The submitted answer is incorrect. You submitted: {req.answer}" + } + +if __name__ == "__main__": + + uvicorn.run(app, host="0.0.0.0", port=8000) \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-324d85de/environment/puzzle/upstream/simulator.py b/tasks/agentescape-25-skeleton-324d85de/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-25-skeleton-324d85de/environment/puzzle/upstream/simulator.py @@ -0,0 +1,2911 @@ +import hashlib +import hmac +import base64 +import binascii +import zlib +import json +import uuid +import math +import re +from typing import Dict, Any, List + +class ToolSimulator: + def __init__(self): + """工具模拟器 + + 文件处理工具(zip_unzip, zip_unzip_file, zip_unzip_item, json_get, csv_query, + regex_search, graph_shortest_path)不需要真实文件系统。 + 这些工具只验证输入参数,然后返回预先初始化好的 golden_outputs。 + """ + self.tool_map = { + # 数论 + "calc_bigmul": self.calc_bigmul, + "calc_modexp": self.calc_modexp, + "calc_modexp_int": self.calc_modexp_int, + "calc_gcd": self.calc_gcd, + "calc_gcd_int": self.calc_gcd_int, + "calc_inv_mod": self.calc_inv_mod, + "calc_inv_mod_int": self.calc_inv_mod_int, + + # 哈希 + "hash_sha256": self.hash_sha256, + "hash_md5": self.hash_md5, + "hmac_sha256": self.hmac_sha256, + + # 编码 + "base64_decode": self.base64_decode, + "base64_encode": self.base64_encode, + "hex_decode": self.hex_decode, + "hex_encode": self.hex_encode, + "zlib_inflate": self.zlib_inflate, + "zlib_deflate": self.zlib_deflate, + + # 文件 + "zip_unzip": self.zip_unzip, + "zip_unzip_file": self.zip_unzip_file, + "zip_unzip_item": self.zip_unzip_item, + "regex_search": self.regex_search, + "json_get": self.json_get, + "csv_query": self.csv_query, + "code_py_exec": self.code_py_exec, + + # 图 + "graph_shortest_path": self.graph_shortest_path, + + # 加解密 (简化模拟) + "crypto_aes_cbc_decrypt": self.crypto_aes_cbc_decrypt, + "crypto_rsa_decrypt_hex": self.crypto_rsa_decrypt_hex, + + # 其他 + "num_base_convert": self.num_base_convert, + "time_convert": self.time_convert, + "checksum_crc32": self.checksum_crc32, + "geo_haversine": self.geo_haversine, + "otp_totp_generate": self.otp_totp_generate, + "unicode_norm": self.unicode_norm, + "text_bidi_sanitize": self.text_bidi_sanitize, + "text_xor_hex": self.text_xor_hex, + "text_rotN": self.text_rotN, + "luhn_check": self.luhn_check, + "iban_validate": self.iban_validate, + + # 物理 + "matter_synthesizer": self.matter_synthesizer, + + # 终端机 + "terminal_1": self.terminal_1, + "terminal_2": self.terminal_2, + "Logic Terminal": self.logic_terminal, + "Math Terminal": self.math_terminal, + "Encryption Terminal": self.crypt_terminal, + "Sequence Terminal": self.sequence_terminal + } + + def execute(self, tool_name: str, inputs: Dict[str, Any]) -> Dict[str, Any]: + if tool_name not in self.tool_map: + # Fallback for unknown tools: return dummy outputs based on expected output types + # This should ideally not happen if all tools are implemented + return {} + + try: + return self.tool_map[tool_name](inputs) + except Exception as e: + print(f"Error executing {tool_name}: {e}") + # Return empty or error indication? For generation, we might want to fail hard or return dummy. + # For now, return dummy to keep flow going, but log error. + return {} + + # --- Implementations --- + + def calc_bigmul(self, inputs): + # Check if required parameters are present + if "a" not in inputs or "b" not in inputs: + raise ValueError("Missing required parameters 'a' and/or 'b'") + + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + return {"product": str(a * b)} + except (ValueError, TypeError) as e: + raise ValueError(f"Failed to convert parameters to integers: {str(e)}") + + def calc_modexp(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + try: + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if isinstance(base, str): + base = int(base) + elif not isinstance(base, int): + raise ValueError("Parameter 'base' must be a string or integer") + + if isinstance(exp, str): + exp = int(exp) + elif not isinstance(exp, int): + raise ValueError("Parameter 'exp' must be a string or integer") + + if isinstance(mod, str): + mod = int(mod) + elif not isinstance(mod, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": str(pow(base, exp, mod))} + + def calc_modexp_int(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["base"], int): + raise ValueError("Parameter 'base' must be an integer") + if not isinstance(inputs["exp"], int): + raise ValueError("Parameter 'exp' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": pow(base, exp, mod)} + + def calc_gcd(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + # 计算 GCD 并返回字符串格式(符合 Big_Int 输出类型) + result = math.gcd(a, b) + return {"gcd": str(result)} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def calc_gcd_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["b"], int): + raise ValueError("Parameter 'b' must be an integer") + + # 获取参数 + a = inputs["a"] + b = inputs["b"] + + return {"gcd": math.gcd(a, b)} + + def calc_inv_mod(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + m = inputs["mod"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(m, str): + m = int(m) + elif not isinstance(m, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": str(pow(a, -1, m))} + except ValueError as e: + # 模逆不存在时,返回一个特殊值(用于数据传递) + # 在 DAG 生成阶段,这允许数据流继续 + return {"inv": str(a)} + + def calc_inv_mod_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + a = inputs["a"] + m = inputs["mod"] + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": pow(a, -1, m)} + except ValueError as e: + raise ValueError(f"Modular inverse does not exist: {str(e)}") + + def hash_sha256(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.sha256(text.encode()).hexdigest()} + + def hash_md5(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.md5(text.encode()).hexdigest()} + + def hmac_sha256(self, inputs): + # 参数检查 + if "hex_key" not in inputs: + raise ValueError("Missing required parameter: hex_key") + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["hex_key"], str): + raise ValueError("Parameter 'hex_key' must be a string") + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + try: + key = bytes.fromhex(inputs["hex_key"]) + text = inputs["text"].encode() + return {"hex": hmac.new(key, text, hashlib.sha256).hexdigest()} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def base64_decode(self, inputs): + # 参数检查 + if "data" not in inputs: + raise ValueError("Missing required parameter: data") + + # 类型检查 + if not isinstance(inputs["data"], str): + raise ValueError("Parameter 'data' must be a string") + + data = inputs["data"] + try: + return {"bytes_hex": binascii.hexlify(base64.b64decode(data)).decode()} + except Exception as e: + raise ValueError(f"Base64 decode error: {str(e)}") + + def base64_encode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"b64": base64.b64encode(bytes.fromhex(hex_data)).decode()} + except Exception as e: + raise ValueError(f"Base64 encode error: {str(e)}") + + def hex_decode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"text": bytes.fromhex(hex_data).decode('utf-8', errors='ignore')} + except Exception as e: + raise ValueError(f"Hex decode error: {str(e)}") + + def hex_encode(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + try: + return {"hex": text.encode().hex()} + except Exception as e: + raise ValueError(f"Hex encode error: {str(e)}") + + + # 到此处实现已经更新 + + def zlib_inflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("Parameter 'hex' must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("Missing required parameter: hex") + + try: + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空字符串 + if not hex_data: + raise ValueError("Empty hex string provided") + + # 检查十六进制字符串的有效性 + if len(hex_data) % 2 != 0: + raise ValueError("Hex string must have even length") + + # 检查是否只包含有效的十六进制字符 + if not all(c in '0123456789abcdefABCDEF' for c in hex_data): + raise ValueError("Invalid hex string provided") + + # 尝试解压缩 + return {"text": zlib.decompress(bytes.fromhex(hex_data)).decode('utf-8')} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hex string provided") from e + raise ValueError(f"Invalid zlib data: {e}") from e + except Exception as e: + raise RuntimeError(f"Failed to inflate data: {e}") from e + + def zlib_deflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("Parameter 'text' must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("Missing required parameter: text") + + try: + # 压缩文本 + return {"hex": zlib.compress(text.encode('utf-8')).hex()} + except Exception as e: + raise RuntimeError(f"Failed to deflate data: {e}") from e + + # --- File Operations --- + + def zip_unzip(self, inputs): + """ZIP 解压工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"files": golden_outputs.get("files", "")} + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return {"files": golden_outputs.get("files", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "files" in golden_outputs: + # 验证必需参数 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 检查类型 + if has_zip_id and not isinstance(zip_id, str): + return {"error": "Parameter 'zip_id' must be a string type"} + if has_password and not isinstance(password, str): + return {"error": "Parameter 'password' must be a string type"} + + # 验证输入是否与预期匹配 + if golden_inputs: + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return {"files": golden_outputs["files"]} + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + # 没有golden_inputs但有golden_outputs,直接返回输出 + return {"files": golden_outputs["files"]} + + # 如果没有预期输出,返回空结果 + return {"files": ""} + + def regex_search(self, inputs): + """正则搜索工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"matches": golden_outputs.get("matches", "[]")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "matches" in golden_outputs: + # 提取实际参数 + pattern = inputs.get("pattern") + file_id = inputs.get("file_id") + text = inputs.get("text") + + # 1. 检查必需参数 + if pattern is None: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["pattern"], + "message": "Missing required parameter 'pattern'" + } + } + + # 类型检查 + if not isinstance(pattern, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "pattern", + "message": "Parameter 'pattern' must be a string type" + } + } + if file_id is not None and not isinstance(file_id, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if text is not None and not isinstance(text, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "text", + "message": "Parameter 'text' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合 + provided_params = {} + if pattern is not None: + provided_params["pattern"] = pattern + if file_id is not None: + provided_params["file_id"] = file_id + if text is not None: + provided_params["text"] = text + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数(关键改进) + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_pattern = golden_inputs.get("pattern") + expected_file_id = golden_inputs.get("file_id") + expected_text = golden_inputs.get("text") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_pattern is not None: + if str(pattern) != str(expected_pattern): + incorrect_params.append("pattern") + else: + correct_params.append("pattern") + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_text is not None: + if str(text) != str(expected_text): + incorrect_params.append("text") + else: + correct_params.append("text") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "matches": "[]", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "matches": golden_outputs["matches"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空列表 + return {"matches": "[]"} + + def json_get(self, inputs): + """JSON 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"values": golden_outputs.get("values", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "values" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + jsonpath = inputs.get("jsonpath", "") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if jsonpath is not None and not isinstance(jsonpath, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "jsonpath", + "message": "Parameter 'jsonpath' must be a string type" + } + } + + # 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:jsonpath有默认值"") + provided_params = {} + if file_id is not None: + provided_params["file_id"] = file_id + if jsonpath != "": + provided_params["jsonpath"] = jsonpath + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_jsonpath = golden_inputs.get("jsonpath") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_jsonpath is not None: + if str(jsonpath) != str(expected_jsonpath): + incorrect_params.append("jsonpath") + else: + correct_params.append("jsonpath") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "values": "", + "_validation": validation_info + } + + # 所有验证通过,返回正确输出 + return { + "values": golden_outputs["values"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"values": ""} + + def csv_query(self, inputs): + """CSV 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"rows": golden_outputs.get("rows", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "rows" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + select_columns = inputs.get("select", "") + where_clause = inputs.get("where", "") + + # 1. 检查必需参数 + if file_id is None: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["file_id"], + "message": "Missing required parameter 'file_id'" + } + } + + # 类型检查 + if not isinstance(file_id, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if not isinstance(select_columns, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "select", + "message": "Parameter 'select' must be a string type" + } + } + if not isinstance(where_clause, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "where", + "message": "Parameter 'where' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:select和where有默认值"") + provided_params = {"file_id": file_id} + if select_columns != "": + provided_params["select"] = select_columns + if where_clause != "": + provided_params["where"] = where_clause + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_select = golden_inputs.get("select") + expected_where = golden_inputs.get("where") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_select is not None: + if str(select_columns) != str(expected_select): + incorrect_params.append("select") + else: + correct_params.append("select") + + if expected_where is not None: + if str(where_clause) != str(expected_where): + incorrect_params.append("where") + else: + correct_params.append("where") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "rows": "", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "rows": golden_outputs["rows"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"rows": ""} + + def graph_shortest_path(self, inputs): + """图最短路径工具 + + 如果有 _golden_outputs 或 _init_outputs,验证输入并返回预设输出。 + 否则执行真实的 Dijkstra 算法。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 检查是否在预设模式中(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + if golden_outputs and "path" in golden_outputs: + # 评测阶段但没有 golden_inputs,直接返回 outputs + if not golden_inputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 评测模式:验证输入参数是否匹配 golden 值 + src = inputs.get("src") + dst = inputs.get("dst") + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + + has_src = src is not None and src != "" + has_dst = dst is not None and dst != "" + + # 验证必需参数 + if not has_src or not has_dst: + missing = [] + if not has_src: + missing.append("src") + if not has_dst: + missing.append("dst") + return {"error": "Missing required parameters: " + ", ".join(missing)} + + # 类型检查 + if not isinstance(src, str): + return {"error": "Parameter 'src' must be a string"} + if not isinstance(dst, str): + return {"error": "Parameter 'dst' must be a string"} + + # 验证输入是否匹配期望值 + if golden_inputs: + expected_src = golden_inputs.get("src") + expected_dst = golden_inputs.get("dst") + expected_file_id = golden_inputs.get("file_id") + expected_graph_data = golden_inputs.get("graph_data") + + # 收集验证结果 + incorrect_params = [] + correct_params = [] + + # 检查必需参数是否匹配 + if expected_src is not None: + if str(src) != str(expected_src): + incorrect_params.append("src") + else: + correct_params.append("src") + + if expected_dst is not None: + if str(dst) != str(expected_dst): + incorrect_params.append("dst") + else: + correct_params.append("dst") + + # 检查可选参数(如果在 expected_inputs 中定义了) + if expected_file_id is not None: + if file_id != expected_file_id: + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_graph_data is not None: + if graph_data != expected_graph_data: + incorrect_params.append("graph_data") + else: + correct_params.append("graph_data") + + # 如果有参数不正确,返回详细的反馈 + if incorrect_params: + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 验证通过,返回预设的输出 + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 获取参数(真实执行路径) + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + # Support both src/dst (interface definition) and start/end (original implementation) + start = inputs.get("src") + end = inputs.get("dst") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + raise TypeError("file_id must be a string") + + if graph_data is not None and not isinstance(graph_data, str): + raise TypeError("graph_data must be a string") + + if start is not None and not isinstance(start, str): + raise TypeError("src/start must be a string") + + if end is not None and not isinstance(end, str): + raise TypeError("dst/end must be a string") + + # 检查必需参数 + if file_id is None and graph_data is None: + raise ValueError("Either file_id or graph_data must be provided") + + if start is None: + raise ValueError("src/start parameter is required") + + if end is None: + raise ValueError("dst/end parameter is required") + + # Get graph content + content = None + if file_id is not None: + # 尝试从 VFS 获取(如果存在) + if hasattr(self, 'vfs') and file_id in self.vfs: + content = self.vfs[file_id] + else: + # VFS 不存在或文件不在 VFS 中 + # 返回一个默认的空图结果,或者抛出错误提示需要 init_outputs + raise ValueError( + f"File '{file_id}' not found. For tools that require files, " + f"please provide init_outputs in the initial_values." + ) + elif graph_data is not None: + content = graph_data + + if content is None: + content = "{}" + + try: + # Parse graph data + graph = json.loads(content) + + # 类型检查 + if not isinstance(graph, dict): + raise TypeError("Graph data must be a dictionary") + + # If graph is not in the expected format, try to extract adjacency list + if "nodes" in graph and "edges" in graph: + # 验证nodes和edges的类型 + if not isinstance(graph["nodes"], list): + raise TypeError("Nodes must be a list") + + if not isinstance(graph["edges"], list): + raise TypeError("Edges must be a list") + + # Convert from nodes/edges format to adjacency list + adjacency_list = {} + for node in graph["nodes"]: + # 验证node类型 + if not isinstance(node, dict): + raise TypeError("Each node must be a dictionary") + + # Use node ID as key, not the entire node dictionary + node_id = node.get("id", "") + if node_id: + adjacency_list[node_id] = {} + + for edge in graph["edges"]: + # 验证edge类型 + if not isinstance(edge, dict): + raise TypeError("Each edge must be a dictionary") + + u = edge["from"] + v = edge["to"] + weight = edge.get("weight", 1) # Default to unweighted + + # 类型检查 + if not isinstance(u, str): + raise TypeError("Edge 'from' must be a string") + + if not isinstance(v, str): + raise TypeError("Edge 'to' must be a string") + + if not isinstance(weight, (int, float)): + raise TypeError("Edge weight must be a number") + + if u not in adjacency_list: + adjacency_list[u] = {} + if v not in adjacency_list: + adjacency_list[v] = {} + + adjacency_list[u][v] = weight + # If undirected, add reverse edge + if not edge.get("directed", False): + adjacency_list[v][u] = weight + elif isinstance(graph, dict): + # Already in adjacency list format + adjacency_list = graph + + # 验证邻接表结构 + for node, neighbors in adjacency_list.items(): + if not isinstance(neighbors, dict): + raise TypeError("Adjacency list must be a dictionary of dictionaries") + + for neighbor, weight in neighbors.items(): + if not isinstance(weight, (int, float)): + raise TypeError("Edge weights must be numbers") + else: + raise TypeError("Graph data must be a dictionary") + + # 检查起点和终点是否为空 + if not start: + raise ValueError("Start node cannot be empty") + + if not end: + raise ValueError("End node cannot be empty") + + # 检查起点和终点是否在图中 + if start not in adjacency_list: + raise ValueError(f"Start node '{start}' not found in graph") + + if end not in adjacency_list: + raise ValueError(f"End node '{end}' not found in graph") + + # Dijkstra's algorithm implementation + import heapq + + # Initialize distances and previous nodes + distances = {node: float('infinity') for node in adjacency_list} + previous = {node: None for node in adjacency_list} + distances[start] = 0 + + # Priority queue + pq = [(0, start)] + heapq.heapify(pq) + + while pq: + current_dist, current_node = heapq.heappop(pq) + + # If we've reached the end node, we can break early + if current_node == end: + break + + # Nodes can be added multiple times to the priority queue, but we only process them once + if current_dist > distances[current_node]: + continue + + # Explore neighbors + for neighbor, weight in adjacency_list[current_node].items(): + distance = current_dist + weight + + # If a shorter path is found + if distance < distances[neighbor]: + distances[neighbor] = distance + previous[neighbor] = current_node + heapq.heappush(pq, (distance, neighbor)) + + # Reconstruct the shortest path + path = [] + current = end + while current is not None: + path.append(current) + current = previous[current] + path.reverse() # Reverse to get from start to end + + # Check if path exists + if not path or path[0] != start: + return {"path": "[]", "cost": 0} + + return { + "path": json.dumps(path), + "cost": distances[end] + } + except json.JSONDecodeError as e: + raise ValueError(f"Invalid JSON in graph data: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in graph_shortest_path: {str(e)}") + + # --- Crypto (Simplified) --- + def crypto_aes_cbc_decrypt(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 (使用模板中定义的参数名) + hex_cipher = inputs.get("hex_cipher") + hex_key = inputs.get("hex_key") + hex_iv = inputs.get("hex_iv") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + + if hex_key is not None and not isinstance(hex_key, str): + raise TypeError("hex_key must be a string") + + if hex_iv is not None and not isinstance(hex_iv, str): + raise TypeError("hex_iv must be a string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + + if hex_key is None: + raise ValueError("hex_key parameter is required") + + if hex_iv is None: + raise ValueError("hex_iv parameter is required") + + from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes + from cryptography.hazmat.backends import default_backend + from cryptography.hazmat.primitives import padding + + try: + # Convert hex strings to bytes + ciphertext = bytes.fromhex(hex_cipher) + key = bytes.fromhex(hex_key) + iv = bytes.fromhex(hex_iv) + + # Validate key length (AES-128, AES-192, AES-256) + if len(key) not in [16, 24, 32]: + raise ValueError("Invalid key length. Must be 16, 24, or 32 bytes.") + + if len(iv) != 16: + raise ValueError("Invalid IV length. Must be 16 bytes.") + + # Create cipher object + cipher = Cipher( + algorithms.AES(key), + modes.CBC(iv), + backend=default_backend() + ) + + decryptor = cipher.decryptor() + + # Decrypt the ciphertext + padded_plaintext = decryptor.update(ciphertext) + decryptor.finalize() + + # Remove PKCS7 padding + unpadder = padding.PKCS7(128).unpadder() + plaintext = unpadder.update(padded_plaintext) + unpadder.finalize() + + # Return decrypted text + return {"text": plaintext.decode('utf-8', errors='ignore')} + except ValueError as e: + if "non-hexadecimal number found in fromhex()" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher, hex_key, or hex_iv") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in crypto_aes_cbc_decrypt: {str(e)}") + + def crypto_rsa_decrypt_hex(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_cipher = inputs.get("hex_cipher") + n = inputs.get("n") + d = inputs.get("d") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + if n is not None and not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + if d is not None and not isinstance(d, (int, str)): + raise TypeError("d must be an integer or string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + if n is None: + raise ValueError("n parameter is required") + if d is None: + raise ValueError("d parameter is required") + + try: + # Convert parameters to appropriate types + cipher_int = int(hex_cipher, 16) + n_int = int(n) if isinstance(n, str) else n + d_int = int(d) if isinstance(d, str) else d + + # RSA decryption: plaintext = ciphertext^d mod n + plaintext_int = pow(cipher_int, d_int, n_int) + + # Convert result to hex and then to text + plaintext_hex = hex(plaintext_int)[2:] + + # Pad with leading zero if odd length + if len(plaintext_hex) % 2 != 0: + plaintext_hex = '0' + plaintext_hex + + # Convert hex to bytes and then to text + try: + plaintext_bytes = bytes.fromhex(plaintext_hex) + plaintext_text = plaintext_bytes.decode('utf-8', errors='ignore') + except: + # If decoding fails, return hex representation + plaintext_text = plaintext_hex + + return {"text": plaintext_text} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in crypto_rsa_decrypt_hex: {str(e)}") + + # --- Others --- + def num_base_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + s = inputs.get("s") + from_base = inputs.get("from_base") + to_base = inputs.get("to_base") + + # 类型检查 - 接受 str 或 int + if s is not None and not isinstance(s, (str, int)): + raise TypeError("s must be a string or integer") + + if from_base is not None and not isinstance(from_base, (int, str)): + raise TypeError("from_base must be an integer") + + if to_base is not None and not isinstance(to_base, (int, str)): + raise TypeError("to_base must be an integer") + + # 检查必需参数 + if s is None: + raise ValueError("s parameter is required") + + if from_base is None: + raise ValueError("from_base parameter is required") + + if to_base is None: + raise ValueError("to_base parameter is required") + + try: + # Convert to int if needed + from_base = int(from_base) if isinstance(from_base, str) else from_base + to_base = int(to_base) if isinstance(to_base, str) else to_base + s_str = str(s) + + # 验证基数范围 + if from_base < 2 or from_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + if to_base < 2 or to_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + # Convert from source base to decimal + val = int(s_str, from_base) + + # Convert from decimal to target base + if to_base == 10: + result = str(val) + elif to_base == 16: + result = hex(val)[2:] + elif to_base == 8: + result = oct(val)[2:] + elif to_base == 2: + result = bin(val)[2:] + else: + # Generic base conversion for other bases + if val == 0: + result = "0" + else: + digits = "0123456789abcdefghijklmnopqrstuvwxyz" + result = "" + n = abs(val) + while n: + result = digits[n % to_base] + result + n //= to_base + if val < 0: + result = "-" + result + + return {"str": result} + except ValueError as e: + raise ValueError(f"Invalid number format: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in num_base_convert: {str(e)}") + + def time_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iso = inputs.get("iso") + timestamp = inputs.get("timestamp") + datetime_str = inputs.get("datetime") + from_tz = inputs.get("from_tz") + to_tz = inputs.get("to_tz") + format_str = inputs.get("format") + + # 类型检查 + if iso is not None and not isinstance(iso, str): + raise TypeError("iso must be a string") + + if timestamp is not None and not isinstance(timestamp, (str, int, float)): + raise TypeError("timestamp must be a string, integer, or float") + + if datetime_str is not None and not isinstance(datetime_str, str): + raise TypeError("datetime must be a string") + + if from_tz is not None and not isinstance(from_tz, str): + raise TypeError("from_tz must be a string") + + if to_tz is not None and not isinstance(to_tz, str): + raise TypeError("to_tz must be a string") + + if format_str is not None and not isinstance(format_str, str): + raise TypeError("format must be a string") + + # 设置默认值 + if from_tz is None: + from_tz = "UTC" + + if to_tz is None: + to_tz = "UTC" + + import datetime + import pytz + + # 验证时区参数 + try: + if from_tz: + pytz.timezone(from_tz) + if to_tz: + pytz.timezone(to_tz) + except Exception: + raise ValueError("Invalid timezone provided") + + try: + # Parse input time + dt = None + + if iso is not None: + # Parse ISO 8601 format + dt = datetime.datetime.fromisoformat(iso.replace('Z', '+00:00')) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=pytz.UTC) + elif timestamp is not None: + # Parse Unix timestamp + timestamp = float(timestamp) + dt = datetime.datetime.fromtimestamp(timestamp, pytz.UTC) + elif datetime_str is not None: + # Parse datetime string + # Try common formats + formats_to_try = [ + "%Y-%m-%d %H:%M:%S", + "%Y-%m-%d %H:%M:%S.%f", + "%Y-%m-%d", + "%m/%d/%Y %H:%M:%S", + "%m/%d/%Y" + ] + + parse_success = False + for fmt in formats_to_try: + try: + dt = datetime.datetime.strptime(datetime_str, fmt) + dt = pytz.timezone(from_tz).localize(dt) + parse_success = True + break + except ValueError: + continue + + if not parse_success: + raise ValueError("Unable to parse datetime string with common formats") + else: + # 如果没有提供任何时间参数,则使用当前时间 + dt = datetime.datetime.now(pytz.UTC) + except ValueError as e: + raise ValueError(f"Error parsing time input: {str(e)}") + except Exception as e: + raise RuntimeError(f"Unexpected error parsing time input: {str(e)}") + + try: + # Convert timezone + if from_tz != to_tz: + dt = dt.astimezone(pytz.timezone(to_tz)) + + # Format outputs + result = { + "iso": dt.isoformat(), + "timestamp": str(dt.timestamp()), + "datetime": dt.strftime("%Y-%m-%d %H:%M:%S"), + "date": dt.strftime("%Y-%m-%d"), + "time": dt.strftime("%H:%M:%S"), + "timezone": to_tz + } + + # Add custom format if requested + if format_str: + try: + result["formatted"] = dt.strftime(format_str) + except ValueError as e: + raise ValueError(f"Invalid format string: {str(e)}") + + return result + except Exception as e: + raise RuntimeError(f"Error in time_convert: {str(e)}") + + def checksum_crc32(self, inputs): + import zlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("hex must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("hex parameter is required") + + try: + # 验证十六进制字符串 + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空 + if not hex_data: + raise ValueError("hex data cannot be empty") + + # 检查是否为有效的十六进制字符串 + if not all(c in "0123456789abcdefABCDEF" for c in hex_data): + raise ValueError("hex must be a valid hexadecimal string") + + # 检查长度是否为偶数 + if len(hex_data) % 2 != 0: + raise ValueError("hex must have even number of characters") + + val = zlib.crc32(bytes.fromhex(hex_data)) + # 确保 hex 输出是 8 位,前导补 0 + return {"hex": f"{val:08x}", "int": val} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in checksum_crc32: {str(e)}") + + def geo_haversine(self, inputs): + import math + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + lat1 = inputs.get("lat1") + lon1 = inputs.get("lon1") + lat2 = inputs.get("lat2") + lon2 = inputs.get("lon2") + + # 类型检查 + if lat1 is not None and not isinstance(lat1, (int, float, str)): + raise TypeError("lat1 must be a number or string") + if lon1 is not None and not isinstance(lon1, (int, float, str)): + raise TypeError("lon1 must be a number or string") + if lat2 is not None and not isinstance(lat2, (int, float, str)): + raise TypeError("lat2 must be a number or string") + if lon2 is not None and not isinstance(lon2, (int, float, str)): + raise TypeError("lon2 must be a number or string") + + # 检查必需参数 + if lat1 is None: + raise ValueError("lat1 parameter is required") + if lon1 is None: + raise ValueError("lon1 parameter is required") + if lat2 is None: + raise ValueError("lat2 parameter is required") + if lon2 is None: + raise ValueError("lon2 parameter is required") + + try: + # 转换为浮点数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(lat1, str): + lat1 = float(lat1) + elif not isinstance(lat1, (int, float)): + raise TypeError("lat1 must be a number or string") + else: + lat1 = float(lat1) + + if isinstance(lon1, str): + lon1 = float(lon1) + elif not isinstance(lon1, (int, float)): + raise TypeError("lon1 must be a number or string") + else: + lon1 = float(lon1) + + if isinstance(lat2, str): + lat2 = float(lat2) + elif not isinstance(lat2, (int, float)): + raise TypeError("lat2 must be a number or string") + else: + lat2 = float(lat2) + + if isinstance(lon2, str): + lon2 = float(lon2) + elif not isinstance(lon2, (int, float)): + raise TypeError("lon2 must be a number or string") + else: + lon2 = float(lon2) + + # Validate coordinates (approximate range check) + if not (-90 <= lat1 <= 90): + raise ValueError("lat1 must be between -90 and 90") + if not (-90 <= lat2 <= 90): + raise ValueError("lat2 must be between -90 and 90") + if not (-180 <= lon1 <= 180): + raise ValueError("lon1 must be between -180 and 180") + if not (-180 <= lon2 <= 180): + raise ValueError("lon2 must be between -180 and 180") + + # Earth radius in meters + R = 6371000 # Approximate radius of Earth + + # Convert degrees to radians + lat1_rad = math.radians(lat1) + lon1_rad = math.radians(lon1) + lat2_rad = math.radians(lat2) + lon2_rad = math.radians(lon2) + + # Calculate differences + delta_lat = lat2_rad - lat1_rad + delta_lon = lon2_rad - lon1_rad + + # Haversine formula + a = math.sin(delta_lat / 2) ** 2 + \ + math.cos(lat1_rad) * math.cos(lat2_rad) * \ + math.sin(delta_lon / 2) ** 2 + c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) + distance_m = R * c + + # Return distance in meters + return {"meters": round(distance_m, 2)} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in geo_haversine: {str(e)}") + + def otp_totp_generate(self, inputs): + import hmac + import hashlib + import base64 + import time + import struct + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + base32_secret = inputs.get("base32_secret") + step = inputs.get("step", 30) # Default to 30 seconds + digits = inputs.get("digits", 6) # Default to 6 digits + timestamp_iso = inputs.get("timestamp_iso", "") + algo = inputs.get("algo", "sha1") # Default to sha1 as current implementation only supports this + + # 类型检查 + if base32_secret is not None and not isinstance(base32_secret, str): + raise TypeError("base32_secret must be a string") + if not isinstance(step, (int, str)): + raise TypeError("step must be an integer or string") + if not isinstance(digits, (int, str)): + raise TypeError("digits must be an integer or string") + if not isinstance(timestamp_iso, str): + raise TypeError("timestamp_iso must be a string") + if not isinstance(algo, str): + raise TypeError("algo must be a string") + + # 检查必需参数 + if base32_secret is None: + raise ValueError("base32_secret parameter is required") + + try: + # Convert step and digits to appropriate types + step = int(step) + digits = int(digits) + if digits < 6 or digits > 8: + raise ValueError("Digits must be between 6 and 8") + + # Convert timestamp_iso to integer timestamp + if timestamp_iso: + import datetime + dt = datetime.datetime.fromisoformat(timestamp_iso.replace('Z', '+00:00')) + timestamp = int(dt.timestamp()) + else: + timestamp = int(time.time()) + + # Calculate counter value (T = floor(timestamp / step)) + counter = timestamp // step + + # Decode the base32 secret + # Add padding if necessary (base64 requires padding to be multiple of 8) + base32_secret = base32_secret.upper().replace(' ', '') + if len(base32_secret) % 8 != 0: + base32_secret += '=' * (8 - (len(base32_secret) % 8)) + key = base64.b32decode(base32_secret, casefold=True) + + # Calculate HMAC-SHA1 + counter_bytes = struct.pack('>Q', counter) # Big-endian 8-byte integer + hmac_hash = hmac.new(key, counter_bytes, hashlib.sha1).digest() + + # Dynamic truncation + offset = hmac_hash[-1] & 0xF + code = struct.unpack('>I', hmac_hash[offset:offset+4])[0] & 0x7FFFFFFF + + # Generate the OTP + otp = str(code % (10 ** digits)).zfill(digits) + + # Calculate remaining time until next OTP change + remaining_time = step - (timestamp % step) + + return {"totp": otp, "remaining_time": remaining_time, "time_step": step} + except ValueError as e: + if "invalid literal for int()" in str(e): + raise ValueError("step and digits must be valid integers") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in otp_totp_generate: {str(e)}") + + def unicode_norm(self, inputs): + import unicodedata + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + form = inputs.get("form", "NFC") # Default to NFC + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if form is not None and not isinstance(form, str): + raise TypeError("form must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Normalize form (NFC, NFD, NFKC, NFKD) + form = form.upper().strip() + + if form not in ['NFC', 'NFD', 'NFKC', 'NFKD']: + raise ValueError(f"Invalid normalization form: {form}. Must be one of: NFC, NFD, NFKC, NFKD") + + # Apply Unicode normalization + normalized_text = unicodedata.normalize(form, text) + + return {"text": normalized_text} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in unicode_norm: {str(e)}") + + def text_bidi_sanitize(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Bidi control characters to remove + bidi_controls = [ + '\u200E', # LEFT-TO-RIGHT MARK + '\u200F', # RIGHT-TO-LEFT MARK + '\u202A', # LEFT-TO-RIGHT EMBEDDING + '\u202B', # RIGHT-TO-LEFT EMBEDDING + '\u202C', # POP DIRECTIONAL FORMATTING + '\u202D', # LEFT-TO-RIGHT OVERRIDE + '\u202E', # RIGHT-TO-LEFT OVERRIDE + '\u2066', # LEFT-TO-RIGHT ISOLATE + '\u2067', # RIGHT-TO-LEFT ISOLATE + '\u2068', # FIRST STRONG ISOLATE + '\u2069', # POP DIRECTIONAL ISOLATE + ] + + # Remove all Bidi control characters + sanitized_text = text + for control_char in bidi_controls: + sanitized_text = sanitized_text.replace(control_char, '') + + return {"text": sanitized_text} + except Exception as e: + raise RuntimeError(f"Error in text_bidi_sanitize: {str(e)}") + + def text_xor_hex(self, inputs): + import binascii + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_a = inputs.get("hex_a") + hex_b = inputs.get("hex_b") + + # 类型检查 + if hex_a is not None and not isinstance(hex_a, str): + raise TypeError("hex_a must be a string") + if hex_b is not None and not isinstance(hex_b, str): + raise TypeError("hex_b must be a string") + + # 检查必需参数 + if hex_a is None: + raise ValueError("hex_a parameter is required") + if hex_b is None: + raise ValueError("hex_b parameter is required") + + try: + # Remove any whitespace + hex_a = hex_a.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + hex_b = hex_b.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + + # Validate hex strings + if not (all(c in "0123456789abcdefABCDEF" for c in hex_a) and len(hex_a) % 2 == 0): + raise ValueError("hex_a must be a valid hexadecimal string with even length") + if not (all(c in "0123456789abcdefABCDEF" for c in hex_b) and len(hex_b) % 2 == 0): + raise ValueError("hex_b must be a valid hexadecimal string with even length") + + # Convert hex strings to bytes + bytes_a = binascii.unhexlify(hex_a) + bytes_b = binascii.unhexlify(hex_b) + + # Make the byte arrays the same length by padding the shorter one with zeros + max_len = max(len(bytes_a), len(bytes_b)) + bytes_a = bytes_a.ljust(max_len, b'\x00') + bytes_b = bytes_b.ljust(max_len, b'\x00') + + # Perform XOR operation + result_bytes = bytes(a ^ b for a, b in zip(bytes_a, bytes_b)) + + # Convert result back to hex + result_hex = binascii.hexlify(result_bytes).decode('utf-8') + + return {"hex": result_hex} + except ValueError as e: + if "Non-hexadecimal digit found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in text_xor_hex: {str(e)}") + + def text_rotN(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + n = inputs.get("n", 0) + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + n = int(n) + except ValueError: + raise ValueError("n must be a valid integer") + + result = [] + for char in text: + if char.isupper(): + # Rotate uppercase letters + result_char = chr((ord(char) - ord('A') + n) % 26 + ord('A')) + result.append(result_char) + elif char.islower(): + # Rotate lowercase letters + result_char = chr((ord(char) - ord('a') + n) % 26 + ord('a')) + result.append(result_char) + else: + # Keep non-alphabetic characters unchanged + result.append(char) + + return {"text": ''.join(result)} + + def luhn_check(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数(支持 card_number 和 number 两个参数名) + card_number = inputs.get("number") or inputs.get("card_number") + + # 类型检查 + if card_number is not None and not isinstance(card_number, str): + raise TypeError("number must be a string") + + # 检查必需参数 + if card_number is None: + raise ValueError("number parameter is required") + + try: + # 如果输入是JSON数组或其他非数字字符串,返回该字符串本身(用于数据传递) + # 这种情况发生在DAG设计中类型不匹配时 + if card_number.startswith('[') or card_number.startswith('{'): + # 输入是JSON,直接返回原值(用于传递) + return {"valid": card_number} + + # Remove whitespace from card number + card_number = card_number.replace(" ", "").replace("-", "") + + # Check if card number is all digits + if not card_number.isdigit() or len(card_number) < 13: + return {"valid": "false"} + + # Implement Luhn algorithm + total = 0 + reverse_digits = card_number[::-1] # Reverse the number for easier processing + + for i, digit in enumerate(reverse_digits): + num = int(digit) + if i % 2 == 1: # Every second digit starting from the right (which is first in reversed string) + num *= 2 + if num > 9: + num -= 9 # Equivalent to sum of digits for 2-digit numbers + total += num + + # Check if total is divisible by 10 + is_valid = total % 10 == 0 + return {"valid": "true" if is_valid else "false"} + except Exception as e: + raise RuntimeError(f"Error in luhn_check: {str(e)}") + + def iban_validate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iban = inputs.get("iban") + + # 类型检查 + if iban is not None and not isinstance(iban, str): + raise TypeError("iban must be a string") + + # 检查必需参数 + if iban is None: + raise ValueError("iban parameter is required") + + try: + # Remove whitespace from IBAN + iban = iban.replace(" ", "") + + # Basic length and format check + if not (len(iban) >= 15 and len(iban) <= 34): + return {"valid": "False"} + + if not (iban[:2].isalpha() and iban[2:].isdigit()): + return {"valid": "False"} + + # Move first four characters to the end + rearranged = iban[4:] + iban[:4] + + # Replace letters with numbers (A=10, B=11, ..., Z=35) + numeric_iban = '' + for char in rearranged: + if char.isdigit(): + numeric_iban += char + else: + numeric_iban += str(ord(char.upper()) - ord('A') + 10) + + # Perform modulo 97 check + # Use step-by-step approach for very large numbers + remainder = 0 + for char in numeric_iban: + remainder = (remainder * 10 + int(char)) % 97 + + is_valid = remainder == 1 + return {"valid": "True" if is_valid else "False"} + except Exception as e: + raise RuntimeError(f"Error in iban_validate: {str(e)}") + + def matter_synthesizer(self, inputs): + import hashlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + blueprint = inputs.get("blueprint") + + # 类型检查 + if blueprint is not None and not isinstance(blueprint, str): + raise TypeError("blueprint must be a string") + + try: + # Get blueprint parameter as defined in interface + if blueprint is None: + blueprint = "" + + # Generate a unique item ID based on the blueprint + # This ensures the same blueprint always produces the same item + blueprint_hash = hashlib.sha256(blueprint.encode()).hexdigest()[:16] + + # Create a synthesized item with a deterministic ID based on blueprint + synthesized_item = f"synthesized_item_{blueprint_hash}" + + return {"output_slot": synthesized_item} + except Exception as e: + raise RuntimeError(f"Error in matter_synthesizer: {str(e)}") + + # --- Terminal Implementations --- + def terminal_1(self, inputs): + """ + terminal_1: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 只返回 text_output + - 只输入正确的 slot_b → 只返回 hex_output + - 同时输入正确的 slot_a 和 slot_b → 返回 item_dispenser(物品掉落) + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + # 检查哪些输入被提供了 + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值是否正确(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + expected_a = golden_inputs["slot_a"] + a_valid = str(slot_a) == str(expected_a) + + if has_b and "slot_b" in golden_inputs: + expected_b = golden_inputs["slot_b"] + b_valid = str(slot_b) == str(expected_b) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 item_dispenser + if has_a and has_b: + if a_valid and b_valid: + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 text_output + if has_a and not has_b: + if a_valid: + if "text_output" in golden_outputs: + result["text_output"] = golden_outputs["text_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 hex_output + if has_b and not has_a: + if b_valid: + if "hex_output" in golden_outputs: + result["hex_output"] = golden_outputs["hex_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def terminal_2(self, inputs): + """ + terminal_2: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 text_result + - 同时输入正确的 num1 和 num2 → 返回 hex_result 和 math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + # 检查哪些输入被提供了 + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值是否正确(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + expected_num1 = golden_inputs["num1"] + num1_valid = str(num1) == str(expected_num1) + + if has_num2 and "num2" in golden_inputs: + expected_num2 = golden_inputs["num2"] + num2_valid = str(num2) == str(expected_num2) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 hex_result 和 math_token + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 text_result + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "text_result" in golden_outputs: + result["text_result"] = golden_outputs["text_result"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def logic_terminal(self, inputs): + """ + Logic Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 返回 screen(部分输出) + - 只输入正确的 slot_b → 返回 screen 和 secondary_output + - 同时输入正确的 slot_a 和 slot_b → 返回 screen, secondary_output, item_dispenser + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + a_valid = str(slot_a) == str(golden_inputs["slot_a"]) + + if has_b and "slot_b" in golden_inputs: + b_valid = str(slot_b) == str(golden_inputs["slot_b"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出(包括 item_dispenser) + if has_a and has_b: + if a_valid and b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 screen(部分输出) + if has_a and not has_b: + if a_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 screen 和 secondary_output + if has_b and not has_a: + if b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def math_terminal(self, inputs): + """ + Math Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 result_display + - 同时输入正确的 num1 和 num2 → 返回 result_display, hex_result, math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + num1_valid = str(num1) == str(golden_inputs["num1"]) + + if has_num2 and "num2" in golden_inputs: + num2_valid = str(num2) == str(golden_inputs["num2"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 result_display + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def crypt_terminal(self, inputs): + """ + Encryption Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 plaintext → 返回 status(部分输出) + - 同时输入正确的 plaintext 和 key → 返回 status, encrypted_hex, encryption_chip + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + plaintext = inputs.get("plaintext") + key = inputs.get("key") + + has_plaintext = plaintext is not None and plaintext != "" + has_key = key is not None and key != "" + + # 验证输入值(与 golden values 比较) + plaintext_valid = False + key_valid = False + + if has_plaintext and "plaintext" in golden_inputs: + plaintext_valid = str(plaintext) == str(golden_inputs["plaintext"]) + + if has_key and "key" in golden_inputs: + key_valid = str(key) == str(golden_inputs["key"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_plaintext and has_key: + if plaintext_valid and key_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + if "encrypted_hex" in golden_outputs: + result["encrypted_hex"] = golden_outputs["encrypted_hex"] + if "encryption_chip" in golden_outputs: + result["encryption_chip"] = golden_outputs["encryption_chip"] + return result + else: + incorrect_params = [] + correct_params = [] + if not plaintext_valid: + incorrect_params.append("plaintext") + else: + correct_params.append("plaintext") + if not key_valid: + incorrect_params.append("key") + else: + correct_params.append("key") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 plaintext 且正确 → 返回 status(部分输出) + if has_plaintext and not has_key: + if plaintext_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: plaintext"} + + # 只提供 key 但没有 plaintext + if has_key and not has_plaintext: + return {"error": "plaintext required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + def sequence_terminal(self, inputs): + """ + Sequence Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 sequence → 返回 verification(部分输出) + - 同时输入正确的 sequence 和 checksum → 返回 verification, auth_code, access_card + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + sequence = inputs.get("sequence") + checksum = inputs.get("checksum") + + has_sequence = sequence is not None and sequence != "" + has_checksum = checksum is not None and checksum != "" + + # 验证输入值(与 golden values 比较) + sequence_valid = False + checksum_valid = False + + if has_sequence and "sequence" in golden_inputs: + sequence_valid = str(sequence) == str(golden_inputs["sequence"]) + + if has_checksum and "checksum" in golden_inputs: + checksum_valid = str(checksum) == str(golden_inputs["checksum"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_sequence and has_checksum: + if sequence_valid and checksum_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + if "auth_code" in golden_outputs: + result["auth_code"] = golden_outputs["auth_code"] + if "access_card" in golden_outputs: + result["access_card"] = golden_outputs["access_card"] + return result + else: + incorrect_params = [] + correct_params = [] + if not sequence_valid: + incorrect_params.append("sequence") + else: + correct_params.append("sequence") + if not checksum_valid: + incorrect_params.append("checksum") + else: + correct_params.append("checksum") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 sequence 且正确 → 返回 verification(部分输出) + if has_sequence and not has_checksum: + if sequence_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: sequence"} + + # 只提供 checksum 但没有 sequence + if has_checksum and not has_sequence: + return {"error": "sequence required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + # --- Additional File Tools --- + + def zip_unzip_file(self, inputs): + """ZIP 解压文件工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def zip_unzip_item(self, inputs): + """ZIP 解压道具工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def code_py_exec(self, inputs): + """Python 代码执行工具 + + 这是一个真实执行的工具,在 DAG 生成阶段和运行时评测阶段都会执行代码。 + 输入: code (Python 代码字符串) + 输出: stdout (标准输出,包含执行结果和错误信息) + + 特殊行为: + - 如果代码定义了 main() 函数,会自动调用它 + - 如果执行出错,错误信息会包含在 stdout 中 + """ + code = inputs.get("code", "") + + if not code: + return {"stdout": "Error: No code provided"} + + try: + # 创建一个受限的执行环境 + import io + import sys + + # 捕获标准输出和标准错误 + old_stdout = sys.stdout + old_stderr = sys.stderr + sys.stdout = io.StringIO() + sys.stderr = io.StringIO() + + # 执行代码 + exec_globals = {"__builtins__": __builtins__} + exec_locals = {} + exec(code, exec_globals, exec_locals) + + # 如果定义了 main() 函数,自动调用它 + if 'main' in exec_locals and callable(exec_locals['main']): + exec_locals['main']() + + # 获取输出 + stdout_value = sys.stdout.getvalue() + stderr_value = sys.stderr.getvalue() + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 合并 stdout 和 stderr + output = stdout_value + if stderr_value: + output += ("\n" if output else "") + f"[stderr] {stderr_value}" + + # 如果没有任何输出,尝试返回 result 变量的值 + if not output: + result = exec_locals.get("_result") or exec_locals.get("result") + if result is not None: + output = str(result) + + return {"stdout": output if output else "(no output)"} + + except Exception as e: + # 恢复标准输出和错误输出 + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 返回错误信息 + return {"stdout": f"Error: {type(e).__name__}: {str(e)}"} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-324d85de/environment/puzzle/worker.Dockerfile b/tasks/agentescape-25-skeleton-324d85de/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-25-skeleton-324d85de/environment/puzzle/worker.Dockerfile @@ -0,0 +1,8 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends libseccomp2 && rm -rf /var/lib/apt/lists/* +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY worker.py child.py /app/ +COPY upstream/simulator.py /app/simulator.py +CMD ["uvicorn", "worker:app", "--host", "0.0.0.0", "--port", "8001", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-25-skeleton-324d85de/environment/puzzle/worker.py b/tasks/agentescape-25-skeleton-324d85de/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-25-skeleton-324d85de/environment/puzzle/worker.py @@ -0,0 +1,73 @@ +"""Stateless Python tool worker. Never receives a scenario or reference values.""" + +import json +import os +import signal +import subprocess +import sys +import tempfile +import threading + +from fastapi import FastAPI +from pydantic import BaseModel, ConfigDict + +app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) +lock = threading.Lock() + + +class Execution(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + code: str + + +@app.get("/health") +def health(): + return {"ok": True} + + +@app.post("/execute") +def execute(request: Execution): + if len(request.code.encode()) > 65536: + return {"stdout": "Error: code exceeds 64 KiB limit"} + with lock, tempfile.TemporaryDirectory(prefix="escape-code-") as directory: + os.chown(directory, 65534, 65534) + with tempfile.TemporaryFile() as output: + process = subprocess.Popen( + [sys.executable, "-I", "/app/child.py"], + stdin=subprocess.PIPE, + stdout=output, + stderr=subprocess.DEVNULL, + cwd=directory, + user=65534, + group=65534, + extra_groups=[], + start_new_session=True, + env={"PATH": "/usr/local/bin:/usr/bin:/bin"}, + ) + try: + process.communicate( + json.dumps({"code": request.code}).encode(), timeout=5 + ) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + return {"stdout": "Error: Python execution timed out"} + finally: + # Also remove children still in the process group after normal exit. + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + output.seek(0) + value = output.read(65537) + if len(value) > 65536 or process.returncode != 0: + return { + "stdout": "Error: Python execution exceeded a resource limit or failed" + } + try: + result = json.loads(value) + if not isinstance(result.get("stdout"), str): + raise ValueError("Invalid worker response") + return result + except (ValueError, AttributeError): + return {"stdout": "Error: Python execution returned invalid output"} diff --git a/tasks/agentescape-25-skeleton-324d85de/instruction.md b/tasks/agentescape-25-skeleton-324d85de/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-25-skeleton-324d85de/instruction.md @@ -0,0 +1,18 @@ +# Escape the room + +Discover the victory string and submit it with `escape submit-answer`. +Start with `escape observe`. This returns the room, available information, visible entities, and victory node ID. + +Use these commands (JSON responses): + +```sh +escape investigate NODE_ID +escape tool-call NODE_ID --arguments-json '{"parameter": "value"}' +escape use-item NODE_ID --arguments-json '{"parameter": "value"}' +escape submit-answer 'exact victory string' +escape state +``` + +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. + +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. diff --git a/tasks/agentescape-25-skeleton-324d85de/solution/oracle.py b/tasks/agentescape-25-skeleton-324d85de/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-25-skeleton-324d85de/solution/oracle.py @@ -0,0 +1,133 @@ +"""Reference solver: use trusted inputs, but obtain the answer through public actions.""" + +import json +import urllib.request +from pathlib import Path + + +def http_action(base_url, payload): + request = urllib.request.Request( + base_url + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(request, timeout=30) as response: + return json.load(response) + + +def solve(scenario, act, observe): + nodes = {node["id"]: node for node in scenario["nodes"]} + visible = {entity["id"] for entity in observe["available_entities"]} + solved = set() + seen_outputs = {} + action_count = 0 + + def call(payload): + nonlocal action_count + action_count += 1 + response = act(payload) + visible.update(entity["id"] for entity in response.get("newly_revealed", [])) + if ( + response.get("episode", {}).get("termination_reason") + == "infrastructure_error" + ): + raise RuntimeError("Infrastructure failure") + return response + + for _round in range(len(nodes) + 2): + progress = False + for node_id, node in nodes.items(): + if node_id not in visible or node_id in solved: + continue + # Preserve graph order for data inputs; trigger/drop edges express visibility. + predecessors = [ + edge["source_id"] + for edge in scenario["edges"] + if edge["target_id"] == node_id + and edge["connection_type"] not in ("Item", "Hidden_Item") + ] + if any(pred not in solved for pred in predecessors): + continue + info = call({"action": "investigate", "node_id": node_id}) + if not info.get("ok"): + raise RuntimeError(f"Investigation failed: {node_id}: {info}") + inputs = { + port["name"]: port["value"] + for port in node.get("inputs", []) + if "value" in port + } + if node["type"] == "Tool": + result = call( + {"action": "tool_call", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok") or result.get("output_values", {}).get("error"): + raise RuntimeError(f"Tool failed: {node_id}: {result}") + output = result.get("output_values", {}) + if node.get("template_id") in ("terminal_1", "terminal_2"): + slots = { + port["name"]: inputs[port["name"]] + for port in node["inputs"] + if port["type"] not in ("Item", "Hidden_Item") + and port["name"] in inputs + } + triggers = { + key: value for key, value in inputs.items() if key not in slots + } + for key, value in slots.items(): + partial = call( + { + "action": "tool_call", + "node_id": node_id, + "arguments": {**triggers, key: value}, + } + ) + if partial.get("ok"): + output.update(partial.get("output_values", {})) + # HIDDEN_ITEM tool drops only occur on subsequent investigation. + call({"action": "investigate", "node_id": node_id}) + elif info.get("required_inputs"): + result = call( + {"action": "use_item", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok"): + raise RuntimeError(f"Item failed: {node_id}: {result}") + output = result.get("content") + else: + output = info.get("content") + seen_outputs[node_id] = output + solved.add(node_id) + progress = True + win_id = scenario["metadata"]["win_node_id"] + if win_id in solved and (len(solved) == len(nodes) or not progress): + outputs = seen_outputs[win_id] + if not outputs: + raise RuntimeError(f"Victory node returned no output: {win_id}") + # Upstream grades its first stored output port, independent of response order. + victory_port = next( + port["name"] for port in nodes[win_id]["outputs"] if "value" in port + ) + answer = outputs[victory_port] if isinstance(outputs, dict) else outputs + result = call({"action": "submit_answer", "answer": answer}) + if not result.get("is_win"): + raise RuntimeError(f"Victory submission failed: {result}") + return {"won": True, "actions": action_count, "visited_nodes": len(solved)} + if not progress: + raise RuntimeError(f"No progress: visible={visible}, solved={solved}") + raise RuntimeError("Reference solver exceeded graph traversal limit") + + +if __name__ == "__main__": + import os + + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000") + with urllib.request.urlopen(base + "/observation", timeout=20) as response: + observation = json.load(response) + print( + json.dumps( + solve( + json.loads(Path("/solution/scenario.json").read_text()), + lambda payload: http_action(base, payload), + observation, + ) + ) + ) diff --git a/tasks/agentescape-25-skeleton-324d85de/solution/scenario.json b/tasks/agentescape-25-skeleton-324d85de/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..fb5be4862b9f5b23f5e02b765aa97cf5e16dedd6 --- /dev/null +++ b/tasks/agentescape-25-skeleton-324d85de/solution/scenario.json @@ -0,0 +1,1649 @@ +{ + "metadata": { + "total_nodes": 25, + "total_edges": 34, + "win_node_id": "num_base_convert", + "win_condition": { + "type": "tool_output", + "node_id": "num_base_convert", + "output_port": "str", + "output_type": "Big_Int", + "description": "Execute Base Converter and get the output from port 'str'" + }, + "source_init": { + "source_nodes": [ + "graph_shortest_path", + "csv_query", + "calc_modexp_acf6", + "calc_modexp_c8f3", + "graph_shortest_path_77db", + "zip_unzip_file", + "calc_inv_mod", + "graph_shortest_path_5d5b", + "terminal_1", + "zip_unzip_file_0e7b", + "zip_unzip_file_678d", + "calc_gcd", + "terminal_2", + "base64_decode", + "checksum_crc32_fe0b" + ], + "by_node": { + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": {}, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "csv_query": { + "node_name": "CSV Query", + "node_type": "Tool", + "template_id": "csv_query", + "init_inputs": {}, + "init_outputs": { + "rows": { + "type": "Text_Generic", + "description": "Result rows" + } + } + }, + "calc_modexp_acf6": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "exp": { + "type": "Big_Int", + "description": "Exponent" + } + }, + "init_outputs": {} + }, + "calc_modexp_c8f3": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "graph_shortest_path_77db": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "Graph JSON file ID" + }, + "src": { + "type": "Text_Generic", + "description": "Source node" + }, + "dst": { + "type": "Text_Generic", + "description": "Destination node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "calc_inv_mod": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "Integer a" + } + }, + "init_outputs": {} + }, + "graph_shortest_path_5d5b": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "Graph JSON file ID" + }, + "src": { + "type": "Text_Generic", + "description": "Source node" + }, + "dst": { + "type": "Text_Generic", + "description": "Destination node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": { + "slot_a": { + "type": "Text_Generic", + "description": "Input Slot A" + }, + "slot_b": { + "type": "Big_Int", + "description": "Input Slot B" + } + }, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + } + } + }, + "zip_unzip_file_0e7b": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "zip_unzip_file_678d": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "calc_gcd": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First integer" + }, + "b": { + "type": "Big_Int", + "description": "Second integer" + } + }, + "init_outputs": {} + }, + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": { + "num2": { + "type": "Big_Int", + "description": "Second Number" + } + }, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + } + } + }, + "base64_decode": { + "node_name": "Base64 Decoder", + "node_type": "Tool", + "template_id": "base64_decode", + "init_inputs": { + "data": { + "type": "Text_Generic", + "description": "Base64 string" + } + }, + "init_outputs": {} + }, + "checksum_crc32_fe0b": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "graph_shortest_path": { + "init_inputs": {}, + "init_outputs": { + "path": "[\"node1\", \"node2\", \"node3\", \"node4\", \"node5\", \"node6\"]", + "cost": "827364" + } + }, + "csv_query": { + "init_inputs": {}, + "init_outputs": { + "rows": "[{\"id\":1,\"name\":\"Alice\"}, {\"id\":2,\"name\":\"Bob\"}, {\"id\":3,\"name\":\"Charlie\"}]" + } + }, + "calc_modexp_acf6": { + "init_inputs": { + "exp": "28374659102938475612" + }, + "init_outputs": {} + }, + "calc_modexp_c8f3": { + "init_inputs": { + "mod": "987653" + }, + "init_outputs": {} + }, + "graph_shortest_path_77db": { + "init_inputs": { + "file_id": "graph_data.json", + "src": "NodeStart", + "dst": "NodeEnd" + }, + "init_outputs": { + "path": "[\"NodeStart\", \"NodeM1\", \"NodeM2\", \"NodeM3\", \"NodeM4\", \"NodeEnd\"]", + "cost": "459102" + } + }, + "zip_unzip_file": { + "init_inputs": {}, + "init_outputs": { + "files": "extracted_content_1.zip" + } + }, + "calc_inv_mod": { + "init_inputs": { + "a": "83746592019283746510" + }, + "init_outputs": {} + }, + "graph_shortest_path_5d5b": { + "init_inputs": { + "file_id": "map_network.json", + "src": "PointA", + "dst": "PointB" + }, + "init_outputs": { + "path": "[\"PointA\", \"Point1\", \"Point2\", \"Point3\", \"Point4\", \"PointB\"]", + "cost": "736184" + } + }, + "terminal_1": { + "init_inputs": { + "slot_a": "Initialization parameters loaded", + "slot_b": "56473829104857692013" + }, + "init_outputs": { + "text_output": "System diagnostic complete and secure.", + "hex_output": "a1b2c3d4e5f67890" + } + }, + "zip_unzip_file_0e7b": { + "init_inputs": { + "password": "SuperSecretPassword99" + }, + "init_outputs": { + "files": "decrypted_archive_3.zip" + } + }, + "zip_unzip_file_678d": { + "init_inputs": { + "zip_id": "locked_bundle_8.zip" + }, + "init_outputs": { + "files": "open_bundle_8.zip" + } + }, + "calc_gcd": { + "init_inputs": { + "a": "10928374657483920192", + "b": "58473628192837465748" + }, + "init_outputs": {} + }, + "terminal_2": { + "init_inputs": { + "num2": "37465829104857692031" + }, + "init_outputs": { + "text_result": "Secondary terminal sequence executed.", + "hex_result": "112233445566778899aabbccddeeff00" + } + }, + "base64_decode": { + "init_inputs": { + "data": "VGhpcyBpcyBhIHRlc3QgbWVzc2FnZS4=" + }, + "init_outputs": {} + }, + "checksum_crc32_fe0b": { + "init_inputs": { + "hex": "1234567890abcdef" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You find yourself sealed within the forgotten sanctum of the Archmage. The air crackles with ancient magic, and the central focus of the room is a towering magical gateway—your only escape. All around you, arcane devices, sealed artifacts, and mystical relics lie dormant. They are intricately interconnected, designed to channel raw magic into one another. You must decipher the ancient scripts, unlock the forgotten coffers, and rekindle the sacred altars to re-establish the grand magical circuit. Follow the flow of mystical energy and awaken the relics to unseal the ultimate portal.", + "narrative_style": "fantasy" + }, + "nodes": [ + { + "id": "num_base_convert", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "827364" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "1580596896" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "1117534580" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "827364" + } + ], + "narrative": "This is The Gate of the Realm. It requires input from The Astral Astrolabe, The Forge of Eternity, and The Moonstone Altar to stabilize its magical vortex." + }, + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "extracted_content_1.zip" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "[{\"id\":1,\"name\":\"Alice\"}, {\"id\":2,\"name\":\"Bob\"}, {\"id\":3,\"name\":\"Charlie\"}]" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "[\"NodeStart\", \"NodeM1\", \"NodeM2\", \"NodeM3\", \"NodeM4\", \"NodeEnd\"]" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"node1\", \"node2\", \"node3\", \"node4\", \"node5\", \"node6\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "827364" + } + ], + "init": { + "inputs": {}, + "outputs": { + "path": "[\"node1\", \"node2\", \"node3\", \"node4\", \"node5\", \"node6\"]", + "cost": "827364" + } + }, + "narrative": "This is The Astral Astrolabe. It requires input from The Book of Prophecy, The Leyline Map, and The Sealed Casket to plot the true course." + }, + { + "id": "calc_bigmul", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "395149224" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "4" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "1580596896" + } + ], + "narrative": "This is The Forge of Eternity. It requires input from The Void Portal and The Scale of Balance to channel the sacred flames." + }, + { + "id": "calc_modexp", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "459102" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": 3866176074 + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "1117534580" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "395149224" + } + ], + "narrative": "This is The Void Portal. It requires input from The Moonstone Altar, The Bloodstone Gem, and The Leyline Map to focus its chaotic energy." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "This is The Chrono Dust. A small pouch of shimmering, timeless dust that seems to float slightly above the ground." + }, + { + "id": "csv_query", + "name": "CSV Query", + "description": "Query CSV: select columns and simple WHERE.", + "type": "Tool", + "template_id": "csv_query", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "CSV file ID", + "value": "open_bundle_8.zip" + }, + { + "name": "select", + "type": "Text_Generic", + "description": "Columns to select", + "value": "[\"NodeStart\", \"NodeM1\", \"NodeM2\", \"NodeM3\", \"NodeM4\", \"NodeEnd\"]" + }, + { + "name": "where", + "type": "Text_Generic", + "description": "Where clause", + "value": "Secondary terminal sequence executed." + } + ], + "outputs": [ + { + "name": "rows", + "type": "Text_Generic", + "description": "Result rows", + "value": "[{\"id\":1,\"name\":\"Alice\"}, {\"id\":2,\"name\":\"Bob\"}, {\"id\":3,\"name\":\"Charlie\"}]" + } + ], + "init": { + "inputs": {}, + "outputs": { + "rows": "[{\"id\":1,\"name\":\"Alice\"}, {\"id\":2,\"name\":\"Bob\"}, {\"id\":3,\"name\":\"Charlie\"}]" + } + }, + "narrative": "This is The Book of Prophecy. It requires input from The Leyline Map, The Bronze Chest, and The Divination Pedestal to reveal its hidden secrets." + }, + { + "id": "calc_modexp_acf6", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "768777" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "28374659102938475612" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": 1620419939 + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "1117534580" + } + ], + "init": { + "inputs": { + "exp": "28374659102938475612" + }, + "outputs": {} + }, + "narrative": "This is The Moonstone Altar. It requires input from The Spirit Prism and The Sunstone Relic to awaken its lunar magic." + }, + { + "id": "checksum_crc32", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "5468697320697320612074657374206d6573736167652e" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "6095a563" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 1620419939 + } + ], + "narrative": "This is The Spirit Prism. It requires input from The Rune Translator to purify the trapped spirits within." + }, + { + "id": "calc_modexp_c8f3", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "83746592019283746510" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "736184" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "987653" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "768777" + } + ], + "init": { + "inputs": { + "mod": "987653" + }, + "outputs": {} + }, + "narrative": "This is The Sunstone Relic. It requires input from The Mirror of Reversal and The Star Chart to unlock its inner light." + }, + { + "id": "graph_shortest_path_77db", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "graph_data.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "NodeStart" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "NodeEnd" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"NodeStart\", \"NodeM1\", \"NodeM2\", \"NodeM3\", \"NodeM4\", \"NodeEnd\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "459102" + } + ], + "init": { + "inputs": { + "file_id": "graph_data.json", + "src": "NodeStart", + "dst": "NodeEnd" + }, + "outputs": { + "path": "[\"NodeStart\", \"NodeM1\", \"NodeM2\", \"NodeM3\", \"NodeM4\", \"NodeEnd\"]", + "cost": "459102" + } + }, + "narrative": "This is The Leyline Map. An ancient parchment depicting the flowing magical currents of the realm." + }, + { + "id": "checksum_crc32_581f", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "6095a563" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "e6712a4a" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3866176074 + } + ], + "narrative": "This is The Bloodstone Gem. It requires input from The Spirit Prism to stabilize its deep, pulsing resonance." + }, + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "decrypted_archive_3.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "[\"NodeStart\", \"NodeM1\", \"NodeM2\", \"NodeM3\", \"NodeM4\", \"NodeEnd\"]" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_content_1.zip" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "extracted_content_1.zip" + } + }, + "narrative": "This is The Sealed Casket. It requires input from The Silver Coffer and The Leyline Map to break its heavy enchantments." + }, + { + "id": "calc_inv_mod", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "83746592019283746510" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": 845753685 + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "83746592019283746510" + } + ], + "init": { + "inputs": { + "a": "83746592019283746510" + }, + "outputs": {} + }, + "narrative": "This is The Mirror of Reversal. It requires input from The Soul Crystal to activate its reflective, reality-bending magic." + }, + { + "id": "item_16_b307", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "This is The Astral Sand. A handful of glowing silver sand that hums with celestial energy." + }, + { + "id": "graph_shortest_path_5d5b", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "map_network.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "PointA" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "PointB" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"PointA\", \"Point1\", \"Point2\", \"Point3\", \"Point4\", \"PointB\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "736184" + } + ], + "init": { + "inputs": { + "file_id": "map_network.json", + "src": "PointA", + "dst": "PointB" + }, + "outputs": { + "path": "[\"PointA\", \"Point1\", \"Point2\", \"Point3\", \"Point4\", \"PointB\"]", + "cost": "736184" + } + }, + "narrative": "This is The Star Chart. A delicate, crystalline parchment detailing the celestial constellations." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this terminal" + }, + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "Initialization parameters loaded" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "56473829104857692013" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "System diagnostic complete and secure." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "a1b2c3d4e5f67890" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": { + "slot_a": "Initialization parameters loaded", + "slot_b": "56473829104857692013" + }, + "outputs": { + "text_output": "System diagnostic complete and secure.", + "hex_output": "a1b2c3d4e5f67890" + } + }, + "narrative": "This is The Alchemist's Crucible. A heavy iron cauldron used for transmuting magical elements." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "This is The Shadow Essence. A small glass vial filled with swirling, dark smoke." + }, + { + "id": "container_1", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + }, + { + "name": "fingerprint_input", + "type": "Hex_String", + "description": "Fingerprint Hash", + "value": "6095a563" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is The Ancient Urn. It requires input from The Spirit Prism to unlock its forgotten seal." + }, + { + "id": "zip_unzip_file_0e7b", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "open_bundle_8.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "SuperSecretPassword99" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "decrypted_archive_3.zip" + } + ], + "init": { + "inputs": { + "password": "SuperSecretPassword99" + }, + "outputs": { + "files": "decrypted_archive_3.zip" + } + }, + "narrative": "This is The Silver Coffer. It requires input from The Bronze Chest to open its delicate, moon-silver clasp." + }, + { + "id": "zip_unzip_file_678d", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "locked_bundle_8.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Secondary terminal sequence executed." + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "open_bundle_8.zip" + } + ], + "init": { + "inputs": { + "zip_id": "locked_bundle_8.zip" + }, + "outputs": { + "files": "open_bundle_8.zip" + } + }, + "narrative": "This is The Bronze Chest. It requires input from The Divination Pedestal to reveal its concealed keyhole." + }, + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "10928374657483920192" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "58473628192837465748" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "4" + } + ], + "init": { + "inputs": { + "a": "10928374657483920192", + "b": "58473628192837465748" + }, + "outputs": {} + }, + "narrative": "This is The Scale of Balance. An elegant golden scale used to weigh truth and deception." + }, + { + "id": "terminal_2", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "768777" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "37465829104857692031" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Secondary terminal sequence executed." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "112233445566778899aabbccddeeff00" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": { + "num2": "37465829104857692031" + }, + "outputs": { + "text_result": "Secondary terminal sequence executed.", + "hex_result": "112233445566778899aabbccddeeff00" + } + }, + "narrative": "This is The Divination Pedestal. It requires input from The Sunstone Relic to project its scrying visions." + }, + { + "id": "base64_decode", + "name": "Base64 Decoder", + "description": "Decode base64 to hex bytes.", + "type": "Tool", + "template_id": "base64_decode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "data", + "type": "Text_Generic", + "description": "Base64 string", + "value": "VGhpcyBpcyBhIHRlc3QgbWVzc2FnZS4=" + } + ], + "outputs": [ + { + "name": "bytes_hex", + "type": "Hex_String", + "description": "Decoded bytes as Hex", + "value": "5468697320697320612074657374206d6573736167652e" + } + ], + "init": { + "inputs": { + "data": "VGhpcyBpcyBhIHRlc3QgbWVzc2FnZS4=" + }, + "outputs": {} + }, + "narrative": "This is The Rune Translator. A set of enchanted lenses that can seamlessly decipher ancient scripts." + }, + { + "id": "checksum_crc32_fe0b", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "1234567890abcdef" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "32692d55" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 845753685 + } + ], + "init": { + "inputs": { + "hex": "1234567890abcdef" + }, + "outputs": {} + }, + "narrative": "This is The Soul Crystal. A jagged amethyst that pulses with dormant spirit energy." + }, + { + "id": "item_8_f284", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "This is The Light Essence. A beautifully carved phial containing a few drops of liquid sunshine." + } + ], + "edges": [ + { + "source_id": "graph_shortest_path", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "s" + }, + { + "source_id": "calc_bigmul", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "from_base" + }, + { + "source_id": "calc_modexp", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "a" + }, + { + "source_id": "item_16", + "target_id": "calc_modexp", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "csv_query", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "rows", + "target_port": "src" + }, + { + "source_id": "calc_modexp_acf6", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "mod" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp_acf6", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "mod" + }, + { + "source_id": "calc_modexp_c8f3", + "target_id": "calc_modexp_acf6", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "base" + }, + { + "source_id": "graph_shortest_path_77db", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "dst" + }, + { + "source_id": "checksum_crc32_581f", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "exp" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "calc_inv_mod", + "target_id": "calc_modexp_c8f3", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "base" + }, + { + "source_id": "item_16_b307", + "target_id": "checksum_crc32", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "graph_shortest_path_77db", + "target_id": "csv_query", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "select" + }, + { + "source_id": "checksum_crc32", + "target_id": "checksum_crc32_581f", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "calc_modexp_acf6", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "to_base" + }, + { + "source_id": "graph_shortest_path_5d5b", + "target_id": "calc_modexp_c8f3", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "exp" + }, + { + "source_id": "terminal_1", + "target_id": "checksum_crc32_581f", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "trigger_item" + }, + { + "source_id": "item_8", + "target_id": "zip_unzip_file", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "graph_shortest_path_77db", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "base" + }, + { + "source_id": "container_1", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "zip_unzip_file_0e7b", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "zip_unzip_file_678d", + "target_id": "csv_query", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "b" + }, + { + "source_id": "checksum_crc32", + "target_id": "container_1", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "fingerprint_input" + }, + { + "source_id": "terminal_2", + "target_id": "zip_unzip_file_678d", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "password" + }, + { + "source_id": "base64_decode", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "bytes_hex", + "target_port": "hex" + }, + { + "source_id": "terminal_2", + "target_id": "csv_query", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "where" + }, + { + "source_id": "terminal_2", + "target_id": "terminal_1", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "trigger_item" + }, + { + "source_id": "zip_unzip_file_678d", + "target_id": "zip_unzip_file_0e7b", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "checksum_crc32_fe0b", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "mod" + }, + { + "source_id": "calc_modexp_c8f3", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "num1" + }, + { + "source_id": "graph_shortest_path_77db", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "password" + }, + { + "source_id": "item_8_f284", + "target_id": "calc_gcd", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-324d85de/solution/solve.sh b/tasks/agentescape-25-skeleton-324d85de/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-25-skeleton-324d85de/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-25-skeleton-324d85de/task.toml b/tasks/agentescape-25-skeleton-324d85de/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e2ba38f13cf7c201bd27f621254bcb3174ef4e9e --- /dev/null +++ b/tasks/agentescape-25-skeleton-324d85de/task.toml @@ -0,0 +1,38 @@ +schema_version = "1.4" +source = "https://github.com/AGI-Eval-Official/Repo-of-AgentEscapeBench" + +[[artifacts]] +source = "/evidence/final.json" +service = "puzzle" + +[[artifacts]] +source = "/evidence/trace.jsonl" +service = "puzzle" + +[task] +name = "edbeeching/agentescape-25-skeleton-324d85de" +version = "0.1.0" + +[metadata] +difficulty = 25 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "c08225bddd4108892b368b3e8e57b7160b63ac7ce48d3a59ae842275a4397025" +protocol = "harbor-cli-action-budget-v1" +max_actions = 500 + +[agent] +timeout_sec = 1200 + +[environment] +build_timeout_sec = 900 +cpus = 1 +memory_mb = 1024 + +[verifier] +environment_mode = "separate" +timeout_sec = 60 + +[[verifier.collect]] +service = "puzzle" +command = "python -I /app/export.py" +timeout_sec = 15 diff --git a/tasks/agentescape-25-skeleton-324d85de/tests/Dockerfile b/tasks/agentescape-25-skeleton-324d85de/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-25-skeleton-324d85de/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-25-skeleton-324d85de/tests/expected.json b/tasks/agentescape-25-skeleton-324d85de/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..41dc1f69fd6811c481e506c984e0253d7ad15c33 --- /dev/null +++ b/tasks/agentescape-25-skeleton-324d85de/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "c08225bddd4108892b368b3e8e57b7160b63ac7ce48d3a59ae842275a4397025", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-324d85de/tests/grade.py b/tasks/agentescape-25-skeleton-324d85de/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-25-skeleton-324d85de/tests/grade.py @@ -0,0 +1,21 @@ +"""Grade only Harbor-collected sidecar evidence in a fresh verifier container.""" + +import json +from pathlib import Path + +expected = json.loads(Path("/tests/expected.json").read_text()) +state = json.loads(Path("/evidence/final.json").read_text()) +assert state["collected_from_live_service"] is True, "Missing trusted service export" +assert state["scenario_sha256"] == expected["scenario_sha256"], ( + "Wrong scenario evidence" +) +assert state["max_actions"] == expected["max_actions"], "Wrong budget" +assert type(state["won"]) is bool +assert 0 <= state["action_count"] <= state["max_actions"] +assert state["termination_reason"] != "infrastructure_error", ( + "Infrastructure failure is not a puzzle failure" +) +assert not state["won"] or state["termination_reason"] == "success" +Path("/logs/verifier").mkdir(parents=True, exist_ok=True) +Path("/logs/verifier/state.json").write_text(json.dumps(state, indent=2)) +Path("/logs/verifier/reward.txt").write_text("1.0\n" if state["won"] else "0.0\n") diff --git a/tasks/agentescape-25-skeleton-324d85de/tests/test.sh b/tasks/agentescape-25-skeleton-324d85de/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-25-skeleton-324d85de/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-25-skeleton-356c0ae2/environment/Dockerfile b/tasks/agentescape-25-skeleton-356c0ae2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-25-skeleton-356c0ae2/environment/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-25-skeleton-356c0ae2/environment/agent/Dockerfile b/tasks/agentescape-25-skeleton-356c0ae2/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-25-skeleton-356c0ae2/environment/agent/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-25-skeleton-356c0ae2/environment/agent/cli.py b/tasks/agentescape-25-skeleton-356c0ae2/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-25-skeleton-356c0ae2/environment/agent/cli.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Public agent client; depends only on the Python standard library.""" + +import argparse +import json +import os +import sys +import urllib.error +import urllib.request + + +def main(): + parser = argparse.ArgumentParser(description="Interact with the escape room") + parser.add_argument( + "action", + choices=[ + "observe", + "state", + "investigate", + "tool-call", + "use-item", + "submit-answer", + ], + ) + parser.add_argument("value", nargs="?") + parser.add_argument("--arguments-json", default="{}") + args = parser.parse_args() + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000").rstrip("/") + if args.action in ("observe", "state"): + request = urllib.request.Request( + base + ("/observation" if args.action == "observe" else "/state") + ) + else: + if args.value is None: + parser.error("node ID or answer is required") + payload = {"action": args.action.replace("-", "_")} + if args.action == "submit-answer": + payload["answer"] = args.value + else: + payload["node_id"] = args.value + if args.action in ("tool-call", "use-item"): + payload["arguments"] = json.loads(args.arguments_json) + request = urllib.request.Request( + base + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=30) as response: + print(json.dumps(json.load(response), ensure_ascii=False)) + except (urllib.error.URLError, ValueError) as exc: + print(json.dumps({"ok": False, "error": str(exc)})) + sys.exit(2) + + +if __name__ == "__main__": + main() diff --git a/tasks/agentescape-25-skeleton-356c0ae2/environment/docker-compose.yaml b/tasks/agentescape-25-skeleton-356c0ae2/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b696a5e656c4ab7ae61c6deede52d048991de974 --- /dev/null +++ b/tasks/agentescape-25-skeleton-356c0ae2/environment/docker-compose.yaml @@ -0,0 +1,50 @@ +services: + main: + image: agentescapebench-agent:aab05a0a9ddb + build: + context: ./agent + networks: [default, puzzle] + security_opt: [no-new-privileges:true] + depends_on: + puzzle: + condition: service_healthy + puzzle: + image: agentescapebench-puzzle:agentescape-25-skeleton-356c0ae2-aab05a0a9ddb + build: + context: ./puzzle + networks: [puzzle, execution] + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 512m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"] + interval: 1s + timeout: 3s + retries: 30 + depends_on: + worker: + condition: service_healthy + worker: + image: agentescapebench-worker:aab05a0a9ddb + build: + context: ./puzzle + dockerfile: worker.Dockerfile + networks: [execution] + read_only: true + tmpfs: ["/tmp:size=64m,mode=1777"] + cap_drop: [ALL] + cap_add: [SETUID, SETGID, KILL, CHOWN, DAC_OVERRIDE] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 384m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8001/health')"] + interval: 1s + timeout: 3s + retries: 30 +networks: + puzzle: + internal: true + execution: + internal: true diff --git a/tasks/agentescape-25-skeleton-356c0ae2/environment/puzzle/Dockerfile b/tasks/agentescape-25-skeleton-356c0ae2/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-25-skeleton-356c0ae2/environment/puzzle/Dockerfile @@ -0,0 +1,9 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY upstream /app/upstream +COPY service.py export.py /app/ +COPY scenario.json /private/scenario.json +ENV SCENARIO_PATH=/private/scenario.json EVIDENCE_DIR=/evidence WORKER_URL=http://worker:8001 MAX_ACTIONS=500 +CMD ["uvicorn", "service:create_app", "--factory", "--host", "0.0.0.0", "--port", "8000", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-25-skeleton-356c0ae2/environment/puzzle/child.py b/tasks/agentescape-25-skeleton-356c0ae2/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-25-skeleton-356c0ae2/environment/puzzle/child.py @@ -0,0 +1,59 @@ +"""Run the original Python tool after reducing privileges and blocking networking.""" + +import ctypes +import errno +import json +import resource +import sys + +resource.setrlimit(resource.RLIMIT_CPU, (3, 3)) +resource.setrlimit(resource.RLIMIT_AS, (256 * 1024 * 1024, 256 * 1024 * 1024)) +resource.setrlimit(resource.RLIMIT_FSIZE, (65536, 65536)) +resource.setrlimit(resource.RLIMIT_NOFILE, (32, 32)) +resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + +# Filters survive fork/exec. Fail closed if seccomp cannot be loaded. +lib = ctypes.CDLL("libseccomp.so.2", use_errno=True) +lib.seccomp_init.argtypes = [ctypes.c_uint32] +lib.seccomp_init.restype = ctypes.c_void_p +lib.seccomp_rule_add.argtypes = [ + ctypes.c_void_p, + ctypes.c_uint32, + ctypes.c_int, + ctypes.c_uint, +] +lib.seccomp_syscall_resolve_name.argtypes = [ctypes.c_char_p] +lib.seccomp_load.argtypes = [ctypes.c_void_p] +lib.seccomp_release.argtypes = [ctypes.c_void_p] +ctx = lib.seccomp_init(0x7FFF0000) # SCMP_ACT_ALLOW +if not ctx: + raise RuntimeError("Cannot initialize execution isolation") +try: + for name in ( + "socket", + "socketpair", + "connect", + "ptrace", + "process_vm_readv", + "process_vm_writev", + "mount", + "unshare", + "setns", + "bpf", + ): + number = lib.seccomp_syscall_resolve_name(name.encode()) + if ( + number >= 0 + and lib.seccomp_rule_add(ctx, 0x00050000 | errno.EPERM, number, 0) != 0 + ): + raise RuntimeError("Cannot install execution isolation rule") + if lib.seccomp_load(ctx) != 0: + raise RuntimeError("Cannot activate execution isolation") +finally: + lib.seccomp_release(ctx) + +sys.path.insert(0, "/app") +from simulator import ToolSimulator # noqa: E402 + +request = json.load(sys.stdin) +json.dump(ToolSimulator().code_py_exec(request), sys.stdout) diff --git a/tasks/agentescape-25-skeleton-356c0ae2/environment/puzzle/export.py b/tasks/agentescape-25-skeleton-356c0ae2/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-25-skeleton-356c0ae2/environment/puzzle/export.py @@ -0,0 +1,13 @@ +"""Harbor invokes this inside the puzzle service after stopping the agent.""" + +import json +import pathlib +import urllib.request + +with urllib.request.urlopen("http://127.0.0.1:8000/state", timeout=10) as response: + state = json.load(response) +state["collected_from_live_service"] = True +target = pathlib.Path("/evidence/final.json") +temp = target.with_suffix(".tmp") +temp.write_text(json.dumps(state)) +temp.replace(target) diff --git a/tasks/agentescape-25-skeleton-356c0ae2/environment/puzzle/requirements.txt b/tasks/agentescape-25-skeleton-356c0ae2/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-25-skeleton-356c0ae2/environment/puzzle/requirements.txt @@ -0,0 +1,57 @@ +annotated-doc==0.0.5 + # via fastapi +annotated-types==0.8.0 + # via pydantic +anyio==4.16.0 + # via starlette +certifi==2026.10.23 + # via requests +cffi==2.1.1 ; platform_python_implementation != 'PyPy' + # via cryptography +charset-normalizer==3.5.2 + # via requests +click==8.5.0 + # via uvicorn +cryptography==50.0.2 + # via agentescapebench-harbor +fastapi==0.162.0 + # via agentescapebench-harbor +h11==0.16.0 + # via uvicorn +idna==3.20 + # via + # anyio + # requests +opentelemetry-api==1.45.2 + # via fastapi +pycparser==3.12 ; implementation_name != 'PyPy' and platform_python_implementation != 'PyPy' + # via cffi +pydantic==2.14.2 + # via + # agentescapebench-harbor + # fastapi +pydantic-core==2.50.2 + # via pydantic +pytz==2025.2 + # via agentescapebench-harbor +requests==2.34.2 + # via agentescapebench-harbor +starlette==1.10.0 + # via fastapi +typing-extensions==4.16.0 + # via + # anyio + # fastapi + # opentelemetry-api + # pydantic + # pydantic-core + # starlette + # typing-inspection +typing-inspection==0.4.4 + # via + # fastapi + # pydantic +urllib3==2.8.0 + # via requests +uvicorn==0.54.0 + # via agentescapebench-harbor diff --git a/tasks/agentescape-25-skeleton-356c0ae2/environment/puzzle/scenario.json b/tasks/agentescape-25-skeleton-356c0ae2/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..1777f91c2f64f4107c115c7749d5dc304c401ced --- /dev/null +++ b/tasks/agentescape-25-skeleton-356c0ae2/environment/puzzle/scenario.json @@ -0,0 +1,1638 @@ +{ + "metadata": { + "total_nodes": 25, + "total_edges": 32, + "win_node_id": "hex_encode", + "win_condition": { + "type": "tool_output", + "node_id": "hex_encode", + "output_port": "hex", + "output_type": "Hex_String", + "description": "Execute Text to Hex Encoder and get the output from port 'hex'" + }, + "source_init": { + "source_nodes": [ + "terminal_1", + "calc_modexp", + "graph_shortest_path", + "crypto_rsa_decrypt_hex", + "zip_unzip_file", + "calc_inv_mod", + "zip_unzip_file_bff1", + "zlib_deflate", + "graph_shortest_path_9029", + "terminal_1_9158", + "container_2_d2bd", + "text_xor_hex", + "calc_bigmul", + "zip_unzip_file_d0b8", + "checksum_crc32", + "base64_encode", + "calc_gcd" + ], + "by_node": { + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": { + "slot_a": { + "type": "Text_Generic", + "description": "Input Slot A" + } + }, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + } + } + }, + "calc_modexp": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "exp": { + "type": "Big_Int", + "description": "Exponent" + } + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": {}, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "crypto_rsa_decrypt_hex": { + "node_name": "RSA Decrypt", + "node_type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "init_inputs": { + "n": { + "type": "Big_Int", + "description": "Modulus n" + }, + "d": { + "type": "Big_Int", + "description": "Private exponent d" + } + }, + "init_outputs": {} + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "calc_inv_mod": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "Integer a" + } + }, + "init_outputs": {} + }, + "zip_unzip_file_bff1": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "zlib_deflate": { + "node_name": "Zlib Deflate", + "node_type": "Tool", + "template_id": "zlib_deflate", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text to compress" + } + }, + "init_outputs": {} + }, + "graph_shortest_path_9029": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "dst": { + "type": "Text_Generic", + "description": "Destination node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "terminal_1_9158": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": { + "slot_a": { + "type": "Text_Generic", + "description": "Input Slot A" + } + }, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + } + } + }, + "container_2_d2bd": { + "node_name": "", + "node_type": "Item", + "template_id": "container_2", + "init_inputs": { + "fingerprint_input": { + "type": "Hex_String", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + }, + "text_xor_hex": { + "node_name": "Hex XOR", + "node_type": "Tool", + "template_id": "text_xor_hex", + "init_inputs": { + "hex_a": { + "type": "Hex_String", + "description": "Hex A" + }, + "hex_b": { + "type": "Hex_String", + "description": "Hex B" + } + }, + "init_outputs": {} + }, + "calc_bigmul": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First large integer" + }, + "b": { + "type": "Big_Int", + "description": "Second large integer" + } + }, + "init_outputs": {} + }, + "zip_unzip_file_d0b8": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "checksum_crc32": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + }, + "base64_encode": { + "node_name": "Base64 Encoder", + "node_type": "Tool", + "template_id": "base64_encode", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex bytes" + } + }, + "init_outputs": {} + }, + "calc_gcd": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First integer" + }, + "b": { + "type": "Big_Int", + "description": "Second integer" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "terminal_1": { + "init_inputs": { + "slot_a": "Initialize primary boot sequence." + }, + "init_outputs": { + "text_output": "Terminal 1 sequence activated successfully.", + "hex_output": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "calc_modexp": { + "init_inputs": { + "exp": "847392817364829103948572" + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": {}, + "init_outputs": { + "path": "[\"node_A\", \"node_D\", \"node_K\", \"node_M\", \"node_Z\"]", + "cost": "384756" + } + }, + "crypto_rsa_decrypt_hex": { + "init_inputs": { + "n": "938475610293847561029384756102", + "d": "485729103847562910293847561029" + }, + "init_outputs": {} + }, + "zip_unzip_file": { + "init_inputs": {}, + "init_outputs": { + "files": "extracted_data_1.bin" + } + }, + "calc_inv_mod": { + "init_inputs": { + "a": "102938475610293847561029384756" + }, + "init_outputs": {} + }, + "zip_unzip_file_bff1": { + "init_inputs": { + "password": "SecurePa$$w0rd123!" + }, + "init_outputs": { + "files": "archive_payload_bff1.zip" + } + }, + "zlib_deflate": { + "init_inputs": { + "text": "Data payload intended for deflation algorithm compression." + }, + "init_outputs": {} + }, + "graph_shortest_path_9029": { + "init_inputs": { + "dst": "Target_Node_Omega" + }, + "init_outputs": { + "path": "[\"start\", \"waypoint1\", \"waypoint2\", \"waypoint3\", \"waypoint4\", \"Target_Node_Omega\"]", + "cost": "129485" + } + }, + "terminal_1_9158": { + "init_inputs": { + "slot_a": "Secondary diagnostic input string." + }, + "init_outputs": { + "text_output": "Diagnostic complete, no errors found.", + "hex_output": "deadbeefbaadc0dedeadbeefbaadc0de" + } + }, + "container_2_d2bd": { + "init_inputs": { + "fingerprint_input": "e3b0c44298fc1c149afbf4c8996fb924" + }, + "init_outputs": {} + }, + "text_xor_hex": { + "init_inputs": { + "hex_a": "0123456789abcdef0123456789abcdef", + "hex_b": "fedcba9876543210fedcba9876543210" + }, + "init_outputs": {} + }, + "calc_bigmul": { + "init_inputs": { + "a": "485720192837465019283746592019", + "b": "928374650192837465920192837465" + }, + "init_outputs": {} + }, + "zip_unzip_file_d0b8": { + "init_inputs": { + "zip_id": "encrypted_source_d0b8.zip" + }, + "init_outputs": { + "files": "decrypted_target_d0b8.dat" + } + }, + "checksum_crc32": { + "init_inputs": { + "hex": "48656c6c6f576f726c64" + }, + "init_outputs": {} + }, + "base64_encode": { + "init_inputs": { + "hex": "5365637265744d657373616765" + }, + "init_outputs": {} + }, + "calc_gcd": { + "init_inputs": { + "a": "657483920192837465019283746574", + "b": "102938475657483920192837465019" + }, + "init_outputs": {} + } + }, + "intro_narrative": "The grand airship 'Aethelgard' is plummeting toward the jagged peaks of the Rust Mountains. As the Chief Engineer, you've been locked inside the main engine room by a saboteur. The steam pressure is reaching critical mass, and the automated navigation systems are completely offline. You must repair the complex web of mechanical computers, brass gears, and pneumatic tubes scattered across the room. Your ultimate goal is to reboot the Main Engine Console before the ship crashes into the mountainside. Time is ticking, and the hissing of steam is your only companion.", + "narrative_style": "steampunk" + }, + "nodes": [ + { + "id": "hex_encode", + "name": "Text to Hex Encoder", + "description": "Encode UTF-8 text to hex.", + "type": "Tool", + "template_id": "hex_encode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "\u000bct`\u0016\u0006" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Encoded hex", + "value": "0b6374601606" + } + ], + "narrative": "The Main Engine Console. This is the master control unit for the airship's thrusters. It requires input from the Alignment Filter to initiate the final startup sequence." + }, + { + "id": "text_bidi_sanitize", + "name": "Bidi Sanitizer", + "description": "Strip bidi control chars.", + "type": "Tool", + "template_id": "text_bidi_sanitize", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "\u000bct`\u0016\u0006" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Sanitized text", + "value": "\u000bct`\u0016\u0006" + } + ], + "narrative": "The Alignment Filter. A brass filtration device with rapidly whirring blades. It requires input from the Cogwheel Purifier to process the signals." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "Initialize primary boot sequence." + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "384756" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Terminal 1 sequence activated successfully." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": { + "slot_a": "Initialize primary boot sequence." + }, + "outputs": { + "text_output": "Terminal 1 sequence activated successfully.", + "hex_output": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "narrative": "The Navigation Engine. A massive steam-powered analytical engine that handles flight trajectories. It requires input from the Coordinate Translator." + }, + { + "id": "num_base_convert", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "384756" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "0" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "102938475610293847561029384756" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "384756" + } + ], + "narrative": "The Coordinate Translator. A heavy board of rotating dials and clicking gears. It requires inputs from the Pressure Equalizer, the Route Plotter, and the Inversion Coil." + }, + { + "id": "calc_modexp", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "384756" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "847392817364829103948572" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "1" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "0" + } + ], + "init": { + "inputs": { + "exp": "847392817364829103948572" + }, + "outputs": {} + }, + "narrative": "The Pressure Equalizer. A large brass gauge setup meant to stabilize the boiler. It requires inputs from the Route Plotter and the Reverse Gear Mechanism." + }, + { + "id": "text_bidi_sanitize_a199", + "name": "Bidi Sanitizer", + "description": "Strip bidi control chars.", + "type": "Tool", + "template_id": "text_bidi_sanitize", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "\u000bct`\u0016\u0006" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Sanitized text", + "value": "\u000bct`\u0016\u0006" + } + ], + "narrative": "The Cogwheel Purifier. A spinning centrifuge for refining raw mechanical signals. It requires input from the Brass Cipher Box." + }, + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "extracted_data_1.bin" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "\u000bct`\u0016\u0006" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "\u000bct`\u0016\u0006" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"node_A\", \"node_D\", \"node_K\", \"node_M\", \"node_Z\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "384756" + } + ], + "init": { + "inputs": {}, + "outputs": { + "path": "[\"node_A\", \"node_D\", \"node_K\", \"node_M\", \"node_Z\"]", + "cost": "384756" + } + }, + "narrative": "The Route Plotter. A magnificent mechanical map of the skies. It requires inputs from the Brass Cipher Box, the Steam Valve Decoder, and the Cogwheel Purifier." + }, + { + "id": "crypto_rsa_decrypt_hex", + "name": "RSA Decrypt", + "description": "RSA decrypt (hex cipher) with n,d (decimal).", + "type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "hex_cipher", + "type": "Hex_String", + "description": "Ciphertext (Hex)", + "value": "789c0dc8c11180300804c056ae02abb0911b21ca0c810ce163f7bacf3dd9c4e2eb4981456b880a46164487b32d03f43bcbfa99b872aed2bdff3d3e80f31614" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Modulus n", + "value": "938475610293847561029384756102" + }, + { + "name": "d", + "type": "Big_Int", + "description": "Private exponent d", + "value": "485729103847562910293847561029" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decrypted text", + "value": "\u000bct`\u0016\u0006" + } + ], + "init": { + "inputs": { + "n": "938475610293847561029384756102", + "d": "485729103847562910293847561029" + }, + "outputs": {} + }, + "narrative": "The Brass Cipher Box. A heavy decryption machine with glowing vacuum tubes. It requires input from the Boiler Compressor." + }, + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "archive_payload_bff1.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "[\"start\", \"waypoint1\", \"waypoint2\", \"waypoint3\", \"waypoint4\", \"Target_Node_Omega\"]" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_data_1.bin" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "extracted_data_1.bin" + } + }, + "narrative": "The Steam Valve Decoder. A system of hissing pipes that decodes pressure signals. It requires inputs from the Mechanical Sorter and the Astrolabe Mapper." + }, + { + "id": "calc_inv_mod", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "102938475610293847561029384756" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "384756" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "102938475610293847561029384756" + } + ], + "init": { + "inputs": { + "a": "102938475610293847561029384756" + }, + "outputs": {} + }, + "narrative": "The Inversion Coil. A glowing copper coil wrapped around an iron core. It requires input from the Route Plotter." + }, + { + "id": "zip_unzip_file_bff1", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "decrypted_target_d0b8.dat" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "SecurePa$$w0rd123!" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "archive_payload_bff1.zip" + } + ], + "init": { + "inputs": { + "password": "SecurePa$$w0rd123!" + }, + "outputs": { + "files": "archive_payload_bff1.zip" + } + }, + "narrative": "The Mechanical Sorter. A sorting track for incoming pneumatic tubes. It requires input from the Archive Unsealer." + }, + { + "id": "calc_inv_mod_f41c", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "1" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": 2004290681 + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "1" + } + ], + "narrative": "The Reverse Gear Mechanism. A complex set of inverted cogs and flywheels. It requires inputs from the Ratio Analyzer and the Purity Gauge." + }, + { + "id": "zlib_deflate", + "name": "Zlib Deflate", + "description": "Deflate text to zlib bytes (hex).", + "type": "Tool", + "template_id": "zlib_deflate", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Text to compress", + "value": "Data payload intended for deflation algorithm compression." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Compressed hex", + "value": "789c0dc8c11180300804c056ae02abb0911b21ca0c810ce163f7bacf3dd9c4e2eb4981456b880a46164487b32d03f43bcbfa99b872aed2bdff3d3e80f31614" + } + ], + "init": { + "inputs": { + "text": "Data payload intended for deflation algorithm compression." + }, + "outputs": {} + }, + "narrative": "The Boiler Compressor. A heavy iron compressor directly connected to the main furnace." + }, + { + "id": "container_2", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Hex_String", + "description": "Fingerprint Hash", + "value": "ffffffffffffffffffffffffffffffff" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "The Safe Box. A secure steel lockbox embedded firmly in the reinforced wall. It requires input from the Dual Signal Mixer." + }, + { + "id": "graph_shortest_path_9029", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "decrypted_target_d0b8.dat" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "\u000bct`\u0016\u0006" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Target_Node_Omega" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"start\", \"waypoint1\", \"waypoint2\", \"waypoint3\", \"waypoint4\", \"Target_Node_Omega\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "129485" + } + ], + "init": { + "inputs": { + "dst": "Target_Node_Omega" + }, + "outputs": { + "path": "[\"start\", \"waypoint1\", \"waypoint2\", \"waypoint3\", \"waypoint4\", \"Target_Node_Omega\"]", + "cost": "129485" + } + }, + "narrative": "The Astrolabe Mapper. A celestial tracking globe covered in constellations. It requires inputs from the Cogwheel Purifier and the Archive Unsealer." + }, + { + "id": "terminal_1_9158", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this terminal" + }, + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "Secondary diagnostic input string." + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "1" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Diagnostic complete, no errors found." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "deadbeefbaadc0dedeadbeefbaadc0de" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": { + "slot_a": "Secondary diagnostic input string." + }, + "outputs": { + "text_output": "Diagnostic complete, no errors found.", + "hex_output": "deadbeefbaadc0dedeadbeefbaadc0de" + } + }, + "narrative": "The Auxiliary Terminal. A secondary command station for monitoring aft thrusters. It requires input from the Overdrive Regulator." + }, + { + "id": "container_2_d2bd", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Hex_String", + "description": "Fingerprint Hash", + "value": "e3b0c44298fc1c149afbf4c8996fb924" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "e3b0c44298fc1c149afbf4c8996fb924" + }, + "outputs": {} + }, + "narrative": "The Rusted Lockbox. An old, oxidized iron container sitting forgotten in the corner." + }, + { + "id": "calc_modexp_2606", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "1" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": 2004290681 + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "450930314117079145297835646860339632509724910300987333191835" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "1" + } + ], + "narrative": "The Overdrive Regulator. A complex system of safety valves. It requires inputs from the Gear Multiplier, the Purity Gauge, and the Reverse Gear Mechanism." + }, + { + "id": "text_xor_hex", + "name": "Hex XOR", + "description": "XOR two hex strings.", + "type": "Tool", + "template_id": "text_xor_hex", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex_a", + "type": "Hex_String", + "description": "Hex A", + "value": "0123456789abcdef0123456789abcdef" + }, + { + "name": "hex_b", + "type": "Hex_String", + "description": "Hex B", + "value": "fedcba9876543210fedcba9876543210" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "XOR Result Hex", + "value": "ffffffffffffffffffffffffffffffff" + } + ], + "init": { + "inputs": { + "hex_a": "0123456789abcdef0123456789abcdef", + "hex_b": "fedcba9876543210fedcba9876543210" + }, + "outputs": {} + }, + "narrative": "The Dual Signal Mixer. A control panel with crisscrossing copper wires." + }, + { + "id": "calc_bigmul", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "485720192837465019283746592019" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "928374650192837465920192837465" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "450930314117079145297835646860339632509724910300987333191835" + } + ], + "init": { + "inputs": { + "a": "485720192837465019283746592019", + "b": "928374650192837465920192837465" + }, + "outputs": {} + }, + "narrative": "The Gear Multiplier. A massive interlocking gear assembly that shakes the floor." + }, + { + "id": "zip_unzip_file_d0b8", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "encrypted_source_d0b8.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "U2VjcmV0TWVzc2FnZQ==" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "decrypted_target_d0b8.dat" + } + ], + "init": { + "inputs": { + "zip_id": "encrypted_source_d0b8.zip" + }, + "outputs": { + "files": "decrypted_target_d0b8.dat" + } + }, + "narrative": "The Archive Unsealer. A pneumatic tube station for reading old logs. It requires input from the Copper Wire Transmitter." + }, + { + "id": "checksum_crc32", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "48656c6c6f576f726c64" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "77770c79" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 2004290681 + } + ], + "init": { + "inputs": { + "hex": "48656c6c6f576f726c64" + }, + "outputs": {} + }, + "narrative": "The Purity Gauge. A precise measuring instrument with a single floating needle." + }, + { + "id": "base64_encode", + "name": "Base64 Encoder", + "description": "Encode hex bytes to base64.", + "type": "Tool", + "template_id": "base64_encode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "hex", + "type": "Hex_String", + "description": "Hex bytes", + "value": "5365637265744d657373616765" + } + ], + "outputs": [ + { + "name": "b64", + "type": "Text_Generic", + "description": "Base64 string", + "value": "U2VjcmV0TWVzc2FnZQ==" + } + ], + "init": { + "inputs": { + "hex": "5365637265744d657373616765" + }, + "outputs": {} + }, + "narrative": "The Copper Wire Transmitter. A telegraph-like device hooked up to an array of spark gaps." + }, + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "657483920192837465019283746574" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "102938475657483920192837465019" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "init": { + "inputs": { + "a": "657483920192837465019283746574", + "b": "102938475657483920192837465019" + }, + "outputs": {} + }, + "narrative": "The Ratio Analyzer. A set of delicate balancing scales and calibrated counterweights." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "The Chronometer Dial. A polished silver pocket watch component." + } + ], + "edges": [ + { + "source_id": "text_bidi_sanitize", + "target_id": "hex_encode", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "text" + }, + { + "source_id": "terminal_1", + "target_id": "text_bidi_sanitize", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "trigger_item" + }, + { + "source_id": "num_base_convert", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "slot_b" + }, + { + "source_id": "calc_modexp", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "from_base" + }, + { + "source_id": "text_bidi_sanitize_a199", + "target_id": "text_bidi_sanitize", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "text" + }, + { + "source_id": "graph_shortest_path", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "s" + }, + { + "source_id": "crypto_rsa_decrypt_hex", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "dst" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "base" + }, + { + "source_id": "calc_inv_mod", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "to_base" + }, + { + "source_id": "text_bidi_sanitize_a199", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "src" + }, + { + "source_id": "zip_unzip_file_bff1", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "calc_inv_mod_f41c", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "mod" + }, + { + "source_id": "zlib_deflate", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_cipher" + }, + { + "source_id": "container_2", + "target_id": "zip_unzip_file_bff1", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "mod" + }, + { + "source_id": "graph_shortest_path_9029", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "password" + }, + { + "source_id": "terminal_1_9158", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "trigger_item" + }, + { + "source_id": "container_2_d2bd", + "target_id": "text_bidi_sanitize_a199", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "crypto_rsa_decrypt_hex", + "target_id": "text_bidi_sanitize_a199", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "text" + }, + { + "source_id": "calc_modexp_2606", + "target_id": "terminal_1_9158", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "slot_b" + }, + { + "source_id": "text_xor_hex", + "target_id": "container_2", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "fingerprint_input" + }, + { + "source_id": "calc_bigmul", + "target_id": "calc_modexp_2606", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "mod" + }, + { + "source_id": "text_bidi_sanitize_a199", + "target_id": "graph_shortest_path_9029", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "src" + }, + { + "source_id": "zip_unzip_file_d0b8", + "target_id": "zip_unzip_file_bff1", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp_2606", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "exp" + }, + { + "source_id": "calc_inv_mod_f41c", + "target_id": "calc_modexp_2606", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "base" + }, + { + "source_id": "zip_unzip_file_d0b8", + "target_id": "graph_shortest_path_9029", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "base64_encode", + "target_id": "zip_unzip_file_d0b8", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "password" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_inv_mod_f41c", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "a" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_inv_mod_f41c", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "mod" + }, + { + "source_id": "item_16", + "target_id": "calc_bigmul", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-356c0ae2/environment/puzzle/service.py b/tasks/agentescape-25-skeleton-356c0ae2/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-25-skeleton-356c0ae2/environment/puzzle/service.py @@ -0,0 +1,212 @@ +"""Restricted facade over the unchanged, pinned upstream puzzle handlers.""" + +import hashlib +import json +import logging +import os +import sys +import threading +import urllib.request +import uuid +from pathlib import Path + +from fastapi import FastAPI, HTTPException +from fastapi.responses import JSONResponse +from pydantic import BaseModel, ConfigDict + +sys.path.insert(0, str(Path(__file__).parent / "upstream")) +import server as upstream # noqa: E402 + +log = logging.getLogger(__name__) + + +def public(value): + """Keep upstream agent-internal template hints out of the public response.""" + if isinstance(value, dict): + return {k: public(v) for k, v in value.items() if not k.startswith("_")} + if isinstance(value, list): + return [public(v) for v in value] + return value + + +class Action(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + action: str + node_id: str | None = None + arguments: dict | None = None + answer: str | None = None + + +class Episode: + def __init__( + self, scenario_path, max_actions=500, evidence_dir=None, worker_url=None + ): + if max_actions < 1: + raise ValueError("max_actions must be positive") + self.lock = threading.Lock() + self.max_actions = max_actions + self.count = 0 + self.won = False + self.reason = None + self.evidence_dir = Path(evidence_dir) if evidence_dir else None + self.scenario_hash = hashlib.sha256( + Path(scenario_path).read_bytes() + ).hexdigest() + self.initial = upstream.reset_case( + case_file_path=str(scenario_path), session_id=uuid.uuid4().hex + ) + self.case_id = self.initial["case_id"] + # Hide source file paths; no upstream reset/stats/routes are mounted. + self.initial.pop("message", None) + simulator = upstream.SIMULATORS[self.case_id] + if worker_url is None: + + def no_worker(_inputs): + self.reason = "infrastructure_error" + raise RuntimeError("isolated Python worker is not configured") + + simulator.tool_map["code_py_exec"] = no_worker + else: + + def execute_python(inputs): + request = urllib.request.Request( + worker_url + "/execute", + data=json.dumps({"code": inputs.get("code", "")}).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=12) as response: + result = json.load(response) + if not isinstance(result.get("stdout"), str): + raise RuntimeError("Invalid Python worker response") + return result + except Exception: + self.reason = "infrastructure_error" + raise + + simulator.tool_map["code_py_exec"] = execute_python + self.save() + if self.evidence_dir is not None: + (self.evidence_dir / "trace.jsonl").touch() + + def state(self): + return { + "scenario_sha256": self.scenario_hash, + "action_count": self.count, + "max_actions": self.max_actions, + "won": self.won, + "termination_reason": self.reason, + } + + def save(self, action=None, result=None): + if self.evidence_dir is None: + return + self.evidence_dir.mkdir(parents=True, exist_ok=True) + target = self.evidence_dir / "outcome.json" + temp = target.with_suffix(".tmp") + temp.write_text(json.dumps(self.state())) + temp.replace(target) + if action is not None: + with (self.evidence_dir / "trace.jsonl").open("a") as handle: + handle.write( + json.dumps( + {"index": self.count, "action": action, "result": result} + ) + + "\n" + ) + + def dispatch(self, payload): + with self.lock: + if self.reason is not None: + return { + "ok": False, + "error": "Episode has ended", + "episode": self.state(), + } + self.count += 1 + try: + action = Action.model_validate(payload) + if action.action == "submit_answer" and action.answer is not None: + result = upstream.submit_answer( + self.case_id, upstream.SubmitAnswerRequest(answer=action.answer) + ) + if result.get("is_win"): + self.won = True + self.reason = "success" + elif action.action == "investigate" and action.node_id is not None: + result = upstream.investigate( + self.case_id, + upstream.InvestigateRequest(node_id=action.node_id), + ) + elif ( + action.action in ("tool_call", "use_item") + and action.node_id is not None + ): + request_type, handler = ( + (upstream.ToolCallRequest, upstream.tool_call) + if action.action == "tool_call" + else (upstream.UseItemRequest, upstream.use_item) + ) + result = handler( + self.case_id, + request_type( + node_id=action.node_id, arguments=action.arguments or {} + ), + ) + else: + result = { + "ok": False, + "error": "Unknown action or missing action parameter", + } + except HTTPException as exc: + result = {"ok": False, "error": exc.detail} + except ValueError: + result = {"ok": False, "error": "Malformed action"} + except Exception: + log.exception("Puzzle service failure") + self.reason = "infrastructure_error" + self.save() + raise + if self.reason is None and self.count >= self.max_actions: + self.reason = "action_budget_exhausted" + result = public(result) + result["episode"] = self.state() + self.save(payload, result) + return result + + +def create_app( + scenario_path=None, max_actions=None, evidence_dir=None, worker_url=None +): + episode = Episode( + scenario_path or os.environ["SCENARIO_PATH"], + max_actions or int(os.environ.get("MAX_ACTIONS", "500")), + evidence_dir if evidence_dir is not None else os.environ.get("EVIDENCE_DIR"), + worker_url if worker_url is not None else os.environ.get("WORKER_URL"), + ) + app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) + app.state.episode = episode + + @app.get("/health") + def health(): + return {"ok": True} + + @app.get("/observation") + def observation(): + return {**public(episode.initial), "episode": episode.state()} + + @app.get("/state") + def state(): + return episode.state() + + @app.post("/action") + def action(payload: dict): + try: + return episode.dispatch(payload) + except Exception: + return JSONResponse( + status_code=503, + content={"ok": False, "error": "Puzzle infrastructure failure"}, + ) + + return app diff --git a/tasks/agentescape-25-skeleton-356c0ae2/environment/puzzle/upstream/models.py b/tasks/agentescape-25-skeleton-356c0ae2/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-25-skeleton-356c0ae2/environment/puzzle/upstream/models.py @@ -0,0 +1,108 @@ +from enum import Enum +from typing import List, Dict, Any, Optional +from pydantic import BaseModel, Field + +# 1. 细粒度接口类型定义 +class InterfaceType(str, Enum): + ''' + BIG_INT + TEXT_GENERIC + HEX_STRING + FILE_ID + HEX_STRING_KEY_AES + HEX_STRING_IV_AES + CODE_PYTHON + HIDDEN_ITEM + ITEM + ''' + # --- 基础类型 --- + TEXT_GENERIC = "Text_Generic" + BIG_INT = "Big_Int" + + # --- 编码/格式化字符串 --- + HEX_STRING = "Hex_String" # 通用 Hex + + # --- 特定用途的 Hex 字符串 (用于精确匹配) --- + HEX_STRING_KEY_AES = "Hex_String_Key_AES" + HEX_STRING_IV_AES = "Hex_String_IV_AES" + + # --- 文件类型 --- + FILE_ID = "File_Id" + + # --- 代码/脚本 --- + CODE_PYTHON = "Code_Python" + + # --- 实体交互类型 (严格命名) --- + ITEM = "Item" # 主动掉落接口 (Tool -> Item) + HIDDEN_ITEM = "Hidden_Item" # 被动掉落接口 (Item -> Item) + +# 3. 端口定义 +class Port(BaseModel): + name: str + type: InterfaceType + description: str + +# 4. 统一节点定义 (融合工具和物品) +class Node(BaseModel): + id: str + name: str + description: str + type: str # "Tool" or "Item" + + # 接口定义 + inputs: List[Port] = [] + outputs: List[Port] = [] + + # 状态字段 + content: Optional[Any] = None # 物品有内容,工具为None + if_success: Optional[bool] = None # 工具初始为False,物品为None + initial_visible: bool = False + + # 运行时状态 (Server维护) + is_revealed: bool = False + + # 标记该 Tool 节点是否有待触发的 HIDDEN_ITEM 掉落 + # 当 Tool 按照 golden_input 正确执行且有 HIDDEN_ITEM 输出边时设为 True + # 在 investigate 该 Tool 时触发掉落并重置为 False + has_hidden_item_ready: bool = False + + # 初始输入值 (metadata.initial_values.init_inputs,用于渐进式暴露判断) + init_input_values: Dict[str, Any] = {} + + # Golden 输入值 (nodes[].inputs[].value,用于评测验证) + golden_input_values: Dict[str, Any] = {} + + # Golden 输出值 (nodes[].outputs[].value,用于评测验证和 Item 节点的 content) + golden_output_values: Dict[str, Any] = {} + + # 实际获得的输出值历史 (工具每次执行后实际返回的输出列表,用于渐进式暴露判断) + # 格式: List[Dict[str, Any]],每个元素是一次执行的输出字典 + actual_outputs_history: List[Dict[str, Any]] = [] + + # 逻辑规则 (用于终端机等复杂物品) + logic_rules: Optional[Dict[str, Any]] = None + + def copy(self, **kwargs): + """Helper to create a copy with updated fields.""" + data = self.dict() + data.update(kwargs) + return Node(**data) + +# 5. 边定义 (拓扑结构) +class Edge(BaseModel): + source_id: str + target_id: str + connection_type: InterfaceType # 直接使用 InterfaceType + # 如果是 Data_Flow,指定端口对应关系 + source_port: Optional[str] = None + target_port: Optional[str] = None + +# 6. 完整图定义 +class GraphScenario(BaseModel): + case_id: str + title: str + intro_narrative: str + nodes: Dict[str, Node] + edges: List[Edge] + difficulty: int + win_node_id: str # 标记哪个节点是最终目标(通常是一个提交工具或最终物品) diff --git a/tasks/agentescape-25-skeleton-356c0ae2/environment/puzzle/upstream/server.py b/tasks/agentescape-25-skeleton-356c0ae2/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-25-skeleton-356c0ae2/environment/puzzle/upstream/server.py @@ -0,0 +1,1490 @@ +import json +import os +import time +import logging +import random +from pathlib import Path +from typing import Dict, Any, List, Optional +from datetime import datetime +from collections import defaultdict +from fastapi import FastAPI, HTTPException, Request +from fastapi.responses import JSONResponse +from fastapi.middleware.cors import CORSMiddleware +from pydantic import BaseModel, Field + +from models import GraphScenario, Node, InterfaceType +# from generator import ScenarioGenerator +from simulator import ToolSimulator +import uvicorn + +# 配置日志 +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler('server.log'), + logging.StreamHandler() + ] +) +logger = logging.getLogger(__name__) + +app = FastAPI( + title="AgentEscapeBench Universal Server", + version="1.0.0", + description="Industrial-grade evaluation server for escape room AI agents" +) + +# 添加 CORS 支持 +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# In-memory State +SCENARIOS: Dict[str, GraphScenario] = {} +SIMULATORS: Dict[str, ToolSimulator] = {} # case_id -> ToolSimulator +RAW_NODES_DATA: Dict[str, Dict[str, Any]] = {} # case_id -> node_id -> raw node data (for template_id) +FILE_METADATA: Dict[str, Dict[str, Any]] = {} # case_id -> metadata (for initial_values access) + +# Performance monitoring +STATS: Dict[str, Any] = { + "total_requests": 0, + "successful_requests": 0, + "failed_requests": 0, + "tool_calls": defaultdict(int), + "investigates": defaultdict(int), + "use_items": defaultdict(int), + "case_loads": 0, + "start_time": datetime.now() +} + +# Request timing middleware +@app.middleware("http") +async def add_process_time_header(request: Request, call_next): + start_time = time.time() + STATS["total_requests"] += 1 + + try: + response = await call_next(request) + STATS["successful_requests"] += 1 + process_time = time.time() - start_time + response.headers["X-Process-Time"] = str(process_time) + logger.info(f"{request.method} {request.url.path} - {response.status_code} - {process_time:.3f}s") + return response + except Exception as e: + STATS["failed_requests"] += 1 + logger.error(f"{request.method} {request.url.path} - Error: {str(e)}") + raise + +# Exception handler +@app.exception_handler(Exception) +async def global_exception_handler(request: Request, exc: Exception): + logger.error(f"Unhandled exception: {exc}", exc_info=True) + return JSONResponse( + status_code=500, + content={ + "ok": False, + "error": "Internal server error", + "detail": str(exc) if os.getenv("DEBUG") else "An error occurred" + } + ) + +# Health check endpoint +@app.get("/health") +def health_check(): + """健康检查端点""" + uptime = (datetime.now() - STATS["start_time"]).total_seconds() + return { + "status": "healthy", + "version": "1.0.0", + "uptime_seconds": uptime, + "loaded_cases": len(SCENARIOS), + "stats": { + "total_requests": STATS["total_requests"], + "successful_requests": STATS["successful_requests"], + "failed_requests": STATS["failed_requests"], + "success_rate": STATS["successful_requests"] / max(STATS["total_requests"], 1) + } + } + +# Statistics endpoint +@app.get("/stats") +def get_stats(): + """获取详细统计信息""" + return { + "stats": STATS, + "loaded_cases": list(SCENARIOS.keys()), + "uptime": str(datetime.now() - STATS["start_time"]) + } + +def _apply_progressive_reveal_at_init(scenario: GraphScenario): + """ + 在初始化时应用渐进式暴露机制(基于ITEM/HIDDEN_ITEM边) + + 新逻辑: + - 如果一个节点没有 ITEM/HIDDEN_ITEM 类型的入边,它就是初始可见的 + - 如果一个节点有 ITEM/HIDDEN_ITEM 类型的入边,它初始不可见,需要等待上游触发 + + Args: + scenario: 场景对象 + """ + # 收集所有有 ITEM/HIDDEN_ITEM 入边的节点 + nodes_with_item_edges = set() + for edge in scenario.edges: + if edge.connection_type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + nodes_with_item_edges.add(edge.target_id) + + logger.info(f"Nodes with ITEM/HIDDEN_ITEM incoming edges: {nodes_with_item_edges}") + + # 设置初始可见性:没有 ITEM/HIDDEN_ITEM 入边的节点初始可见 + initially_visible_count = 0 + for node_id, node in scenario.nodes.items(): + if node_id not in nodes_with_item_edges: + node.is_revealed = True + initially_visible_count += 1 + logger.info(f"Initial visible (no ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + else: + node.is_revealed = False + logger.debug(f"Initial hidden (has ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + + logger.info(f"Progressive reveal initialized: {initially_visible_count}/{len(scenario.nodes)} nodes initially visible") + + +def _check_inputs_match_golden(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> bool: + """ + 检查实际输入参数是否与 golden inputs 完全匹配 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + True 表示所有 golden inputs 都存在且值匹配 + """ + if not golden_inputs: + return True # 如果没有 golden inputs,认为匹配 + + for key, expected_value in golden_inputs.items(): + actual_value = arguments.get(key) + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) != str(expected_value): + logger.debug(f"Input mismatch for '{key}': expected '{expected_value}', got '{actual_value}'") + return False + + return True + + +def _get_parameter_validation_feedback(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> Dict[str, Any]: + """ + 对源头节点的参数进行详细验证,返回验证反馈 + + 注意:不返回期望值(expected),避免泄漏答案 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + 包含验证结果的字典: + - all_correct: bool - 所有参数是否正确 + - correct_params: List[str] - 正确的参数名列表 + - incorrect_params: List[str] - 错误的参数名列表(不包含期望值) + """ + if not golden_inputs: + return { + "all_correct": True, + "correct_params": [], + "incorrect_params": [] + } + + correct_params = [] + incorrect_params = [] + + for key, actual_value in arguments.items(): + # 只对用户实际提交的参数给反馈,未提交的参数不评价 + if key not in golden_inputs: + continue # 该参数不在 golden 中,跳过(如 _golden_inputs 等内部参数) + expected_value = golden_inputs[key] + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) == str(expected_value): + correct_params.append(key) + else: + # 只记录参数名,不包含期望值,避免泄漏答案 + incorrect_params.append(key) + + # all_correct:用户提交的所有参数都正确,且覆盖了全部 golden 参数 + all_provided_correct = len(incorrect_params) == 0 + all_golden_covered = all(k in arguments for k in golden_inputs) + return { + "all_correct": all_provided_correct and all_golden_covered, + "correct_params": correct_params, + "incorrect_params": incorrect_params + } + + +def _is_source_node(node_id: str, scenario: GraphScenario) -> bool: + """ + 判断节点是否是源头节点(完全没有任何入边的节点) + + 源头节点定义: + - 没有任何类型的入边(包括 DATA、ITEM、HIDDEN_ITEM) + - 即没有任何上游节点 + + Args: + node_id: 节点ID + scenario: 场景对象 + + Returns: + True 表示是源头节点 + """ + for edge in scenario.edges: + if edge.target_id == node_id: + # 只要有任何入边,就不是源头节点 + return False + + return True + + +def _check_and_reveal_ready_nodes(scenario: GraphScenario, recent_outputs: Dict[str, Any], source_node_id: str) -> List[Dict[str, Any]]: + """ + 检查并释放参数齐全的隐藏节点(渐进式暴露机制) + + 核心逻辑: + 1. 维护"可见值集合":包含所有被测模型当前可以看到的值 + - init_inputs 的值(初始可见) + - 工具执行后的实际输出值(运行时获得) + - 可见 Item 的输出值 + 2. 检查隐藏节点:该节点的所有 golden_input 值是否都在可见值集合中 + 3. 如果是,则释放该节点 + + Args: + scenario: 场景对象 + recent_outputs: 最近执行的工具的输出 + source_node_id: 刚执行的工具节点ID + + Returns: + 新释放的节点列表 + """ + newly_revealed = [] + + # 构建"可见值集合"(Set of visible values) + # 存储格式:set of values (转为字符串) + visible_values = set() + + # 1. 添加有意义的 init_inputs 值到可见值集合 + # Item 的 init_inputs 不应该加入,因为它们在密室中完全用不到 + for node_id, node in scenario.nodes.items(): + # 跳过源头 Item 节点(没有入边的 Item) + if node.type == "Item": + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,跳过其 init_inputs + continue + + # 添加其他节点的 init_inputs + for port_name, init_value in node.init_input_values.items(): + if init_value: + visible_values.add(str(init_value)) + + # 2. 添加已执行工具的所有历史输出值 + for node_id, node in scenario.nodes.items(): + if node.type == "Tool" and node.if_success and node.actual_outputs_history: + # 遍历所有历史执行记录 + for output_dict in node.actual_outputs_history: + for output_port_name, output_value in output_dict.items(): + if output_value: + visible_values.add(str(output_value)) + + # 3. 添加已被 investigate 的 Item 的 golden 输出值 + # 注意:Item 可见不等于其输出值可见,需要 investigate 后才能获得 + # 这里我们使用 actual_outputs_history 来标记 Item 是否已被 investigate + for node_id, node in scenario.nodes.items(): + if node.type == "Item" and node.is_revealed and node.actual_outputs_history: + # Item 通常只会被 investigate 一次,但为了一致性也使用历史列表 + for output_dict in node.actual_outputs_history: + for port_name, port_value in output_dict.items(): + if port_value: + visible_values.add(str(port_value)) + + # 遍历所有隐藏的节点,检查其 golden_input 是否都在可见值集合中 + for node_id, node in scenario.nodes.items(): + # 跳过已可见的节点 + if node.is_revealed: + continue + + # 只检查工具节点(物品节点由 ITEM 输出触发) + if node.type != "Tool": + continue + + # 检查该节点的所有 golden_input 值是否都在可见值集合中 + all_inputs_ready = True + missing_values = [] + + for input_port_name, golden_input_value in node.golden_input_values.items(): + # 检查这个 golden 值是否在可见值集合中 + if str(golden_input_value) not in visible_values: + all_inputs_ready = False + missing_values.append(f"{input_port_name}={golden_input_value}") + + # 如果所有 golden_input 值都在可见值集合中,释放该节点 + if all_inputs_ready and len(node.golden_input_values) > 0: + logger.info(f"All golden inputs ready for {node_id}: {list(node.golden_input_values.values())}") + + # 如果所有输入都齐全,释放该节点 + if all_inputs_ready: + node.is_revealed = True + + # 构建节点信息返回给模型 + node_info = { + "id": node.id, + "type": node.type, + "can_investigate": True, + "hint": "This tool's input parameters are now complete, you can use investigate to view detailed information" + } + + # if node.name: + # node_info["name"] = node.name + if node.description: + node_info["description"] = node.description + + newly_revealed.append(node_info) + logger.info(f"Progressive reveal: {node_id} is now ready (all inputs satisfied)") + + return newly_revealed + + +def _initialize_node_values(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]): + """ + Initialize node state and load values from port value fields. + 应用渐进式暴露机制:初始时只显示参数齐全的节点(源头节点) + + 重要区分: + 1. input_values: 只加载 metadata.initial_values 中的 init_inputs(真正的初始值) + 2. output_values: 加载 nodes[].outputs[].value(golden 输出,用于验证) + """ + # 第一步:加载所有节点的值,并将所有节点初始设为隐藏 + initial_values = metadata.get('initial_values', {}) + + for node_id, node in scenario.nodes.items(): + # 忽略 initial_visible 字段,初始全部隐藏 + # 由渐进式暴露机制根据参数齐全情况决定是否显示 + node.is_revealed = False + + if node.type == "Tool": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + elif node.type == "Item": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + + # 从 JSON 加载值 + if node_id in raw_nodes_data: + node_data = raw_nodes_data[node_id] # node_data是json文件中nodes中的字典 + + # 【重要】只加载 metadata.initial_values 中的初始输入值 + if node_id in initial_values: + init_data = initial_values[node_id] + # 加载初始输入值(用于渐进式暴露判断) + for port_name, port_value in init_data.get('init_inputs', {}).items(): + node.init_input_values[port_name] = port_value + + # 【评测用】加载 golden 输入值(用于验证模型传入的参数是否正确) + for input_port_data in node_data.get('inputs', []): + if 'value' in input_port_data: + node.golden_input_values[input_port_data['name']] = input_port_data['value'] + + # 【评测用】加载 golden 输出值(用于验证工具调用是否正确,以及 Item 节点的 content) + for output_port_data in node_data.get('outputs', []): + if 'value' in output_port_data: + node.golden_output_values[output_port_data['name']] = output_port_data['value'] + + # For Items, set content from golden_output_values + if node.type == "Item" and node.golden_output_values: + # Item 的 content 是其第一个 golden 输出值 + node.content = list(node.golden_output_values.values())[0] + + # 第二步:应用渐进式暴露机制 + # 检查所有节点,根据参数齐全情况释放源头节点(工具 + Item) + _apply_progressive_reveal_at_init(scenario) + +def _build_node_info(node: Node, raw_nodes_data: Dict[str, Any]) -> Dict[str, Any]: + """ + 构建节点信息(工具或物品) + + Args: + node: 节点对象 + raw_nodes_data: 原始节点数据(用于获取 template_id 等) + + Returns: + 节点信息字典 + """ + if node.type == "Tool": + # 过滤掉输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口) + # 这些端口仅用于控制掉落机制,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + tool_info = { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Tool", + "inputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.inputs if p.type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]], + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id(工具的标准名称) + if node.id in raw_nodes_data: + node_data = raw_nodes_data[node.id] + template_id = node_data.get('template_id') + if template_id: + tool_info['template_id'] = template_id + + return tool_info + + elif node.type == "Item": + return { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Item" + } + + else: + return { + "id": node.id, + # "name": node.name, + "type": node.type + } + +def _get_initial_observation(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]) -> Dict[str, Any]: + """ + Generate initial observation for the agent (what they see when entering the room). + + 策略: + - Tools: 只显示名称和描述,不显示接口定义。需要 investigate 才能获得详细接口信息。 + - Items: 只显示存在,不显示内容。需要 investigate 才能获得内容值。 + - init_inputs: 作为"可用信息"告诉模型,这些是可以用作工具参数的初始值。 + - init_outputs: 不告诉模型(这些是答案,需要模型通过调用工具获得)。 + """ + available_entities = [] # 统一的实体列表(Tools 和 Items) + available_information = [] # 可用的初始信息(来自 init_inputs) + + # 从 metadata.initial_values 提取 init_inputs 作为可用信息 + # 只提供值本身,不透露这些值对应哪个节点的哪个参数,让模型自己推理 + # 注意:跳过源头 Item(没有入边的 Item)的 init_inputs,因为它们在密室中完全用不到 + initial_values = metadata.get('initial_values', {}) + # initial_values字段的格式 + # "initial_values": { + # "terminal_1": { + # "init_inputs": {}, + # "init_outputs": { + # "text_output": "System initialization complete.", + # "hex_output": "48656c6c6f20576f726c64", + # "item_dispenser": "掉落了一张纸条,上面写着“请勿随意触摸终端”" + # } + # } + # } + for node_id, init_data in initial_values.items(): + # 获取节点信息,判断是否为源头 Item + node = scenario.nodes.get(node_id) + if node and node.type == "Item": + # 检查是否为源头 Item(没有入边) + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,检查是否有 init_inputs + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 有 init_inputs,需要暴露这些参数 + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + # 处理完后跳过后续的通用逻辑 + continue + + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 为每个 init_input 值创建一个信息条目(不包含 source_node 和 parameter 信息) + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + + for node in scenario.nodes.values(): + if node.is_revealed: + # Tools: 只显示基本信息,提示可以 investigate 查看详细接口 + if node.type == "Tool": + tool_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Tool", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the tool's detailed interface information for calling" + } + # 只在 name 非空时添加 + # if node.name: + # tool_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_info["description"] = node.description + + available_entities.append(tool_info) + + # Items: 只显示基本信息,提示可以 investigate 查看内容 + elif node.type == "Item": + item_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Item", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the item's content" + } + # 只在 name 非空时添加 + # if node.name: + # item_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + item_info["description"] = node.description + + available_entities.append(item_info) + + return { + "narrative": scenario.intro_narrative, + "available_entities": available_entities, # 使用统一的实体列表 + "available_information": available_information, # 可用的初始信息(只包含 init_inputs) + "win_node_id": scenario.win_node_id # 胜利节点ID,让模型知道需要关注哪个节点 + } + +@app.post("/env/reset") +def reset_case(case_id: str = None, case_file_path: str = None, session_id: str = None): + """Loads a specific case from file and resets it. + + Args: + case_id: Optional case ID for resetting an existing case + case_file_path: Path to case file for loading a new case + session_id: Optional session ID to ensure isolation between concurrent evaluations + """ + logger.info(f"Reset request - case_id: {case_id}, case_file_path: {case_file_path}, session_id: {session_id}") + STATS["case_loads"] += 1 + + if case_file_path: + if not os.path.exists(case_file_path): + logger.error(f"Case file not found: {case_file_path}") + raise HTTPException(status_code=404, detail=f"File not found: {case_file_path}") + try: + with open(case_file_path, "r", encoding="utf-8") as f: + file_data = json.load(f) + + # 转换格式:从 DAG executor 生成的格式转换为 GraphScenario 格式 + # 1. 提取 metadata + metadata = file_data.get('metadata', {}) + + # 2. 生成 case_id, title, intro_narrative + # 【修复】为每个评测会话生成唯一的 case_id,防止并发评测时状态污染 + base_name = os.path.basename(case_file_path).replace('.json', '').replace('_full', '').replace('_full2', '') + + if session_id: + # 如果提供了 session_id,使用它来确保唯一性 + case_id = f"{base_name}_{session_id}" + else: + # 否则使用时间戳和随机数确保唯一性 + unique_suffix = f"{int(time.time() * 1000)}_{random.randint(1000, 9999)}" + case_id = f"{base_name}_{unique_suffix}" + + file_data['case_id'] = case_id + logger.info(f"Generated unique case_id: {case_id} (base: {base_name}, session: {session_id})") + + if 'title' not in file_data: + file_data['title'] = f"Escape Room: {file_data['case_id']}" + + if 'intro_narrative' not in file_data: # 目前的json文件中已经有了intro_narrative字段,不会使用下面一行的内容,而是使用每个评测问题的json文件中的对应字段 + 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]".' + + # 3. 转换 nodes 列表为字典(DAG executor 生成的文件中 nodes 是列表格式) + nodes_dict = {} + for node_data in file_data['nodes']: + nodes_dict[node_data['id']] = node_data # 这里的id是template_id之后可能添加一个后缀 + file_data['nodes'] = nodes_dict # 把列表转成一个字典 + + # 4. 添加缺失的字段 + if 'difficulty' not in file_data: + file_data['difficulty'] = metadata.get('total_nodes', 5) + + if 'win_node_id' not in file_data: + file_data['win_node_id'] = metadata.get('win_node_id', '') + + scenario = GraphScenario(**file_data) + + # Extract raw nodes data for template_id access + # nodes 已经在上面转换为字典格式 + raw_nodes_data = file_data.get('nodes', {}) + RAW_NODES_DATA[scenario.case_id] = raw_nodes_data + + # Store metadata for initial values access + FILE_METADATA[scenario.case_id] = metadata + + logger.info(f"Successfully parsed case file: {scenario.case_id}, nodes: {len(scenario.nodes)}, edges: {len(scenario.edges)}") + except Exception as e: + logger.error(f"Failed to load case file: {str(e)}", exc_info=True) + raise HTTPException(status_code=500, detail=f"Failed to load case file: {str(e)}") + + # Initialize node state and load values + _initialize_node_values(scenario, raw_nodes_data, metadata) + + SCENARIOS[scenario.case_id] = scenario + simulator = ToolSimulator() + SIMULATORS[scenario.case_id] = simulator + + 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'])}") + + # 生成初始观察信息(进入密室后看到的环境) + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + ''' + initial_observation的格式: + { + "narrative": scenario.intro_narrative, + "available_entities": available_entities # 使用统一的实体列表 + "available_information": available_information # 可用的初始信息(只包含 init_inputs) + } + ''' + + return { + "ok": True, + "message": f"Case loaded from {case_file_path}", + "case_id": scenario.case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果没有提供 case_file_path,但提供了 case_id,则尝试从内存重置 + if case_id and case_id in SCENARIOS: + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + metadata = FILE_METADATA.get(case_id, {}) + + # Reset dynamic fields and re-apply progressive reveal + # 重新初始化节点状态(包括渐进式暴露) + _initialize_node_values(scenario, raw_nodes_data, metadata) + + 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'])}") + + # 生成初始观察信息 + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + + return { + "ok": True, + "message": f"Case {case_id} reset.", + "case_id": case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果既没有 case_file_path,也没有在内存中找到,返回错误 + raise HTTPException( + status_code=400, + detail="Must provide case_file_path to load a new case, or use case_id to reset an existing case." + ) + +class InvestigateRequest(BaseModel): + node_id: str + +@app.post("/env/{case_id}/investigate") +def investigate(case_id: str, req: InvestigateRequest): + """ + Investigates a Tool or Item to reveal detailed information. + + - For Tools: Returns detailed interface information (inputs/outputs) needed to call the tool + - For Items: Returns content value and triggers hidden item drops + """ + logger.info(f"Investigate request - case_id: {case_id}, node_id: {req.node_id}") + STATS["investigates"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + node = scenario.nodes[req.node_id] + + if not node.is_revealed: + logger.warning(f"Attempt to investigate hidden node: {req.node_id}") + return {"ok": False, "error": "Node is not visible yet."} + + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + newly_revealed = [] + + # 处理 Tool 的 investigate + if node.type == "Tool": + logger.info(f"Investigating tool: {req.node_id}") + + # 返回工具的详细接口信息 + # id 字段使用 node.id(节点唯一标识),agent 用这个字段识别和调用具体的节点 + # template_id 是工具类型标识符,Agent 内部用于判断工具特性(如 terminal 类工具参数可选) + # 注意:只过滤输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口),这些端口仅用于控制掉落,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + # 【端口上游依赖提示 & 初始值直接给出】 + # 针对参数语义模糊(全为数字类型)的工具,在 investigate 返回信息中标注 + # 哪个输入端口来自哪个上游节点(upstream_from)。 + # 对于所有工具:若该节点不是纯源头节点(有任意数据流入边), + # 且某个端口没有上游入边(值来自初始可见参数),则直接给出该端口的 golden input 值。 + AMBIGUOUS_TOOLS = { + "num_base_convert", "calc_modexp", "calc_modexp_int", + "calc_inv_mod", "calc_inv_mod_int", "crypto_rsa_decrypt_hex", "geo_haversine" + } + # Terminal 类工具自带参数对错反馈机制,玩家/模型可自行试错, + # 无需在 investigate 时直接暴露 init_value + SELF_FEEDBACK_TOOLS = { + "terminal_1", "terminal_2", + "Logic Terminal", "Math Terminal", "Encryption Terminal", "Sequence Terminal" + } + _template_id_for_hint = raw_nodes_data.get(node.id, {}).get("template_id", "") + # 构建数据流入边映射(对所有工具):{target_port -> (source_node_id, source_port)} + _upstream_map = {} + for _edge in scenario.edges: + if (_edge.target_id == node.id + and _edge.connection_type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM] + and _edge.target_port is not None): + _upstream_map[_edge.target_port] = (_edge.source_id, _edge.source_port) + # 判断该节点是否有任意数据流入边(即不是纯源头节点) + _has_any_upstream = len(_upstream_map) > 0 + # 判断该节点是否有任意入边(包括 ITEM/HIDDEN_ITEM 掉落边) + # 有任意入边(含掉落边)但无数据流入边的节点,其输入来自初始可见参数,应直接给出 + _has_any_edge = any(_edge.target_id == node.id for _edge in scenario.edges) + # 构建 inputs 列表 + _inputs_list = [] + for p in node.inputs: + if p.type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + continue + port_dict = {"name": p.name, "type": p.type, "description": p.description} + if p.name in _upstream_map: + # 该端口有上游数据流依赖,且属于语义模糊工具 → 标注来源 + if _template_id_for_hint in AMBIGUOUS_TOOLS: + src_node_id, src_port = _upstream_map[p.name] + port_dict["upstream_from"] = f"{src_node_id}.{src_port}" if src_port else src_node_id + elif _has_any_edge and _template_id_for_hint not in SELF_FEEDBACK_TOOLS: + # 该节点有任意入边,但此端口没有数据流入边 → 值来自初始可见参数,直接给出 + # 排除自带反馈机制的 terminal 类工具(它们通过执行结果反馈对错,无需提前暴露参数值) + golden_val = node.golden_input_values.get(p.name) + if golden_val is not None: + port_dict["init_value"] = golden_val + _inputs_list.append(port_dict) + + tool_details = { + "id": node.id, # 节点 ID,用于唯一标识和调用这个具体节点 + "type": "Tool", + "inputs": _inputs_list, + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id 用于 Agent 内部判断工具类型(不会展示给被测模型) + if node.id in raw_nodes_data: + template_id = raw_nodes_data[node.id].get('template_id') + if template_id: + tool_details["_template_id"] = template_id # 使用下划线前缀标记为内部字段 + + # 只在 name 非空时添加 + # if node.name: + # tool_details["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_details["description"] = node.description + + # 添加 narrative 字段(如果存在) + if node.id in raw_nodes_data: + narrative = raw_nodes_data[node.id].get('narrative') + if narrative: + tool_details['narrative'] = narrative + + # 不再返回 init_values,避免泄漏答案 + # investigate 只应该返回工具的接口定义,不应该暴露初始值 + + # 【新增】检查该 Tool 是否有待触发的 HIDDEN_ITEM 掉落 + # 如果该工具已按照 golden_input 正确执行,且有 HIDDEN_ITEM 输出边,则触发掉落 + if node.has_hidden_item_ready: + logger.info(f"Tool has HIDDEN_ITEM ready - triggering passive drop for: {req.node_id}") + + # 遍历该工具的所有 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + # 重置标志,已经触发过了,避免重复 + node.has_hidden_item_ready = False + + logger.info(f"Tool investigation successful - node: {req.node_id}, revealed: {len(newly_revealed)}") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Tool", + "details": tool_details + } + + # 如果有新掉落的节点,添加到响应中 + if newly_revealed: + result["newly_revealed"] = newly_revealed + + return result + + # 处理 Item 的 investigate + elif node.type == "Item": + logger.info(f"Investigating item: {req.node_id}") + + # 【第一步】检查该 Item 是否有需要参数的输入端口 + # 如果有,且尚未通过 use_item 验证,则不返回内容,只返回参数要求 + required_inputs = [] + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + inputs_info = raw_node.get('inputs', []) + required_inputs = [ + { + "name": inp.get("name"), + "type": inp.get("type"), + "description": inp.get("description", "") + } + for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + # 如果有 required_inputs 且尚未通过 use_item 验证(if_success == False) + # 则不返回内容,只返回参数要求提示 + if required_inputs and not node.if_success: + logger.info(f"Item has required inputs and not yet unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "required_inputs": required_inputs + } + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + param_names = ', '.join([inp['name'] for inp in required_inputs]) + 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}" + + return result + + # 【新增】如果有 required_inputs 且已经通过 use_item 验证(if_success == True) + # 则返回提示:该节点已经被成功解决 + if required_inputs and node.if_success: + logger.info(f"Item has required inputs and already unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "message": "This item has already been successfully unlocked by you." + } + return result + + # 【第二步】该 Item 没有 required_inputs 或已通过验证,返回内容 + # 1. 返回 Item 的 golden_output_values(即 Item 的内容) + # 注意:某些 Item 仅用于触发 HIDDEN_ITEM 掉落,没有实际内容 + has_actual_content = bool(node.golden_output_values) or node.content is not None + content = node.golden_output_values if node.golden_output_values else node.content + + # 【关键】将 golden_output_values 追加到 actual_outputs_history,标记该 Item 已被 investigate + # 这样在渐进式暴露时,这些值才会被加入可见值集合 + # 即使是空字典(仅触发 HIDDEN_ITEM 的 Item),也要记录,以便渐进式暴露逻辑知道该 Item 已被调查 + if node.golden_output_values is not None: + node.actual_outputs_history.append(dict(node.golden_output_values)) + + # 2. Trigger Hidden Item Drops (Passive Drop) + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + logger.info(f"Item investigation successful - node: {req.node_id}, has_content: {has_actual_content}, revealed: {len(newly_revealed)}") + + # 【渐进式暴露】旧机制(基于 golden_input)已禁用 + # 现在完全由 ITEM/HIDDEN_ITEM 边触发控制节点可见性 + # 上面的 HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, node.golden_output_values or {}, node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # logger.info(f"Progressive reveal after Item investigate: {len(progressive_revealed)} nodes now ready") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Item" + } + + # 只在有实际内容时才添加 content 字段 + # 对于仅触发 HIDDEN_ITEM 掉落的 Item,不返回 content 字段,避免返回 None 或空字典让模型困惑 + if has_actual_content: + result["content"] = content + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型通过 investigate 获得内容后,需要自己识别这是否是胜利字符串 + + return result + + else: + logger.warning(f"Attempt to investigate unknown node type: {req.node_id} (type: {node.type})") + return {"ok": False, "error": f"Cannot investigate node type: {node.type}"} + +class ToolCallRequest(BaseModel): + node_id: str # 使用 node_id 精确指定要调用的节点 + arguments: Dict[str, Any] + +@app.post("/env/{case_id}/tool_call") +def tool_call(case_id: str, req: ToolCallRequest): + """Executes a tool and triggers item drops.""" + logger.info(f"Tool call request - case_id: {case_id}, node_id: {req.node_id}, args: {list(req.arguments.keys())}") + STATS["tool_calls"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + + # 通过 node_id 精确查找节点 + node_id = req.node_id + if node_id not in scenario.nodes: + logger.error(f"Node not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + tool_node = scenario.nodes[node_id] + + if not tool_node: + logger.error(f"Tool not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Tool not found") + + if not tool_node.is_revealed: + logger.warning(f"Attempt to call hidden tool: {node_id}") + return {"ok": False, "error": "Tool is not visible yet."} + + if tool_node.type != "Tool": + logger.warning(f"Attempt to call non-tool node: {node_id} (type: {tool_node.type})") + return {"ok": False, "error": "Only tools can be called."} + + # 1. Execute Tool (Real Execution via Simulator) + simulator = SIMULATORS[case_id] + + # Get tool name from template_id if available, otherwise use node name + tool_name = tool_node.name + if case_id in RAW_NODES_DATA and node_id in RAW_NODES_DATA[case_id]: + template_id = RAW_NODES_DATA[case_id][node_id].get('template_id') + if template_id: + tool_name = template_id + + # 文件处理工具和 Terminal 需要验证输入并返回预先计算的输出 + # 传递节点的实际输入输出值(从 DAG 执行后填充的数据) + tool_arguments = dict(req.arguments) # Make a copy + + # 传递节点的 golden values(从 JSON 的 inputs[].value 和 outputs[].value 加载) + # 用于在评测阶段验证被测模型传入的参数是否正确 + if tool_node.golden_input_values: + tool_arguments['_golden_inputs'] = tool_node.golden_input_values + if tool_node.golden_output_values: + tool_arguments['_golden_outputs'] = tool_node.golden_output_values + + logger.debug(f"Executing tool {tool_name} (node: {tool_node.name}) with args {tool_arguments}") + + try: + output_values = simulator.execute(tool_name, tool_arguments) + logger.info(f"Tool invoked - {tool_name}: {list(output_values.keys())}") + except Exception as e: + logger.error(f"Tool execution failed - {tool_name}: {str(e)}", exc_info=True) + return {"ok": False, "error": f"Tool execution failed: {str(e)}"} + + # 检查验证结果(精细化错误反馈) + validation = output_values.pop("_validation", {"valid": True}) + + if not validation["valid"]: + # 根据错误类型构造友好的错误消息 + error_type = validation.get("error_type") + + if error_type == "missing_required": + missing = validation.get("missing_params", []) + error_msg = f"Error: Missing required parameters {', '.join(missing)}" + + elif error_type == "type_error": + param = validation.get("param_name") + message = validation.get("message", "Parameter type error") + error_msg = f"Error: {message}" + + elif error_type == "incomplete_optional": + provided = validation.get("provided_params", []) + missing = validation.get("missing_params", []) + error_msg = ( + f"Hint: You provided some parameters ({', '.join(provided)}), " + f"but may also need: {', '.join(missing)}.\n" + f"Trying to provide these parameters together might yield better results." + ) + + elif error_type == "value_mismatch": + param = validation.get("param_name") + hint = validation.get("hint", "Parameter value may be incorrect") + error_msg = f"Hint: {hint}.\nPlease check if this parameter value meets the requirements." + + else: + error_msg = validation.get("hint") or validation.get("message", "Parameter validation failed") + + logger.info(f"Tool validation failed - {tool_name}: {error_type}") + return { + "ok": False, + "error": error_msg, + "error_type": error_type + } + + # Simulate success + tool_node.if_success = True + + # 【关键】将本次执行的输出值追加到历史列表(用于渐进式暴露判断) + # 每次调用都会记录,不会覆盖之前的执行结果 + tool_node.actual_outputs_history.append(dict(output_values)) + + # 2. 检查是否应该触发掉落(只有输入参数正确时才掉落) + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, tool_node.golden_input_values) + + newly_revealed = [] + investigate_hints = [] # 提示模型哪些节点可以 investigate 来发现隐藏内容 + + if inputs_match_golden: + logger.info(f"✓ Tool inputs match golden - node: {node_id}, triggering drops") + + # 检查该工具是否有 ITEM 或 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == tool_node.id: + target_node = scenario.nodes[edge.target_id] + + # ITEM 边:立即掉落(主动掉落) + if edge.connection_type == InterfaceType.ITEM: + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from {node_id})") + + # HIDDEN_ITEM 边:不立即掉落,标记并提示(被动掉落) + elif edge.connection_type == InterfaceType.HIDDEN_ITEM: + # 标记该工具有待触发的 HIDDEN_ITEM 掉落 + tool_node.has_hidden_item_ready = True + + # 提示模型可以 investigate 这个工具来发现隐藏内容 + hint_info = { + "tool_id": tool_node.id, + "hint": f"Tool '{tool_node.id}' seems to hide something, try investigating it to discover more information" + } + # if tool_node.name: + # hint_info["tool_name"] = tool_node.name + + investigate_hints.append(hint_info) + logger.info(f"HIDDEN_ITEM ready: {tool_node.id} -> {target_node.id} (will drop on investigate)") + else: + logger.info(f"✗ Tool inputs do NOT match golden - node: {node_id}, no drops triggered") + + response = { + "ok": True, + "message": "Tool invoked", + "output_values": output_values # Return raw outputs to Agent + } + + # 【新增】对源头节点进行参数验证反馈 + # 源头节点:没有数据流入边的节点,这些节点的参数需要模型自己推理 + # 验证模型使用的参数是否正确,并提供明确的反馈 + if _is_source_node(node_id, scenario) and tool_node.golden_input_values: + validation_feedback = _get_parameter_validation_feedback(req.arguments, tool_node.golden_input_values) + + if validation_feedback["all_correct"]: + # 用户提交了全部 golden 参数且全部正确 + response["parameter_feedback"] = { + "status": "correct", + "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." + } + logger.info(f"✓ Source node parameters all correct - node: {node_id}") + elif validation_feedback["incorrect_params"]: + # 有提交了但值错误的参数,只对这些参数给出反馈 + incorrect_list = [] + for param_name in validation_feedback["incorrect_params"]: + incorrect_list.append(f" - Parameter '{param_name}' is incorrect") + + correct_info = "" + if validation_feedback["correct_params"]: + correct_info = f"\n✓ Correct parameters: {', '.join(validation_feedback['correct_params'])}" + + response["parameter_feedback"] = { + "status": "incorrect", + "message": ( + f"⚠️ Some parameters are incorrect:\n" + + "\n".join(incorrect_list) + + correct_info + + 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." + ), + "incorrect_params": validation_feedback["incorrect_params"], + "correct_params": validation_feedback["correct_params"] + } + logger.info(f"✗ Source node parameters incorrect - node: {node_id}, incorrect: {validation_feedback['incorrect_params']}") + # else: 部分提交且全部正确 → 不给任何 parameter_feedback,避免对未提交的参数发表意见 + + # 检查工具调用是否完全正确(输出与 golden outputs 匹配) + # 用于给模型正向反馈,让它知道这个工具已经正确调用过,避免重复调用 + # 注意:只有当输出完全匹配时才标记为 correct,不会在错误时提供具体错误信息 + # if tool_node.golden_output_values and output_values: + # is_correct = True + # for port_name, expected_value in tool_node.golden_output_values.items(): + # actual_value = output_values.get(port_name) + # if str(actual_value) != str(expected_value): + # is_correct = False + # break + + # if is_correct: + # response["tool_call_correct"] = True + # logger.info(f"✓ Tool called with correct result - node: {node_id}") + + # 只在有新内容掉落时才返回 newly_revealed + if newly_revealed: + response["newly_revealed"] = newly_revealed + + # 添加 investigate 提示(对于有待触发 HIDDEN_ITEM 掉落的工具) + if investigate_hints: + response["investigate_hints"] = investigate_hints + + # 3. 渐进式暴露机制 - 现在完全由 ITEM/HIDDEN_ITEM 边控制 + # 旧机制(基于 golden_input 检查)已被禁用 + # 新机制中,节点的可见性只由 ITEM/HIDDEN_ITEM 边触发决定 + # 上面的 ITEM/HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, output_values, tool_node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # response["newly_revealed"] = newly_revealed + # logger.info(f"Progressive reveal: {len(progressive_revealed)} nodes now ready") + + # Check if this is the win node + if node_id == scenario.win_node_id: + # 验证输出值是否等于预期的胜利值 + # 从节点的 golden_output_values 中获取预期值(在 _initialize_node_values 时从 JSON 加载) + expected_outputs = tool_node.golden_output_values + + # 检查实际输出是否与预期输出匹配 + is_correct = False + victory_string = None + mismatch_info = [] + + if expected_outputs and output_values: + # 检查每个预期输出端口的值是否匹配 + is_correct = True + for port_name, expected_value in expected_outputs.items(): + actual_value = output_values.get(port_name) + if actual_value != expected_value: + is_correct = False + mismatch_info.append(f"Port '{port_name}': expected '{expected_value}', actual '{actual_value}'") + logger.warning(f"Win node output mismatch - port: {port_name}, expected: {expected_value}, actual: {actual_value}") + + # 如果所有输出都匹配,使用第一个输出作为胜利字符串 + if is_correct and output_values: + victory_string = list(output_values.values())[0] + else: + logger.warning(f"Win node called but missing output values - expected: {expected_outputs}, actual: {output_values}") + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型调用工具获得输出后,需要自己识别这是否是胜利字符串并提交 + if is_correct: + logger.info(f"🎯 Win node called with correct output - case: {case_id}, node: {node_id}, victory: {victory_string}") + else: + logger.info(f"❌ Win node called with incorrect output - case: {case_id}, node: {node_id}") + + return response + +class UseItemRequest(BaseModel): + node_id: str = Field(..., description="The ID of the Item node to use (must be Item type)") + arguments: Dict[str, Any] = Field(default_factory=dict, description="Input arguments to provide to the item") + +@app.post("/env/{case_id}/use_item") +def use_item(case_id: str, req: UseItemRequest): + """ + Use an Item node by providing input arguments. + + This is specifically for Item nodes that require parameters to be "unlocked" or "activated", + such as containers that need a password/fingerprint. + + - Validates that the node is of type Item + - Checks if provided arguments match the item's golden_input_values + - If match: triggers ITEM-type edge drops and returns the item's content + - If not match: returns error message + """ + logger.info(f"Use item request - case_id: {case_id}, node_id: {req.node_id}, args: {req.arguments}") + STATS["use_items"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + item_node = scenario.nodes[req.node_id] + + if not item_node.is_revealed: + logger.warning(f"Attempt to use hidden item: {req.node_id}") + return {"ok": False, "error": "Item is not visible yet."} + + if item_node.type != "Item": + logger.warning(f"Attempt to use non-item node: {req.node_id} (type: {item_node.type})") + return {"ok": False, "error": "Only Item nodes can be used with use_item. Tools should be called with tool_call."} + + # 【新增】检查该 Item 是否已经被成功解锁 + # 如果已经被正确使用过,直接返回成功提示 + if item_node.if_success: + logger.info(f"Item already unlocked, returning success message: {req.node_id}") + return { + "ok": True, + "message": "This item has already been successfully unlocked by you." + } + + # 检查该 Item 是否真的需要通过 use_item 提供参数 + # 只有当 Item 有非 Item/Hidden_Item 类型的输入时,才应该使用 use_item + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + non_hidden_inputs = [ + inp for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + if not non_hidden_inputs: + # 该 Item 不需要参数,应该只使用 investigate + logger.warning(f"Attempt to use_item on a node that doesn't require parameters: {req.node_id}") + return { + "ok": False, + "error": "This item does not require parameters. Please use investigate to examine the item directly." + } + + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, item_node.golden_input_values) + + if not inputs_match_golden: + logger.info(f"✗ Item inputs do NOT match golden - node: {req.node_id}") + # 提供更详细的错误信息,帮助 Agent 理解问题 + # 只显示非 Item/Hidden_Item 类型的参数(Hidden_Item 由系统自动处理) + expected_params = [] + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + expected_params = [ + inp.get("name") for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + provided_params = list(req.arguments.keys()) if req.arguments else [] + + # 检查参数名是否匹配 + if set(expected_params) == set(provided_params): + # 参数名正确但值不匹配 - 不泄漏正确的值 + error_msg = f"Parameter names are correct, but the parameter values are incorrect. Please try using different parameter values." + else: + error_msg = f"Parameter names do not match. Expected parameter names: {expected_params}, you provided: {provided_params}." + + return { + "ok": False, + "error": error_msg + } + + logger.info(f"✓ Item inputs match golden - node: {req.node_id}, activating item") + + # 标记该 Item 已被正确使用 + item_node.if_success = True + + # 将 golden_output_values 追加到 actual_outputs_history + if item_node.golden_output_values: + item_node.actual_outputs_history.append(dict(item_node.golden_output_values)) + + # 触发 ITEM 类型边的掉落 + newly_revealed = [] + for edge in scenario.edges: + if edge.source_id == item_node.id and edge.connection_type == InterfaceType.ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from use_item on {req.node_id})") + + # 检查是否为 Win Node + win_node_id = scenario.win_node_id + is_win_node = (req.node_id == win_node_id) + + # 构建返回结果 + result = { + "ok": True, + "message": "Item used successfully.", + "content": item_node.golden_output_values if item_node.golden_output_values else None + } + + # 获取 narrative(如果存在) + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + narrative = raw_nodes_data[req.node_id].get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 如果是 Win Node,只记录日志 + if is_win_node: + logger.info(f"Win node (Item) unlocked via use_item - case: {case_id}, node: {req.node_id}") + + return result + + +class SubmitAnswerRequest(BaseModel): + answer: str = Field(..., description="The victory string to submit") + +@app.post("/env/{case_id}/submit_answer") +def submit_answer(case_id: str, req: SubmitAnswerRequest): + """ + 提交答案接口 + 被测模型在获得胜利字符串提示后,需要调用此接口提交答案 + """ + logger.info(f"Submit answer request - case_id: {case_id}, answer: {req.answer}") + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + + # 获取 win_node 的 golden_output_values + if not scenario.win_node_id: + logger.error(f"No win node defined for case: {case_id}") + return { + "ok": False, + "error": "This case has no victory node defined" + } + + win_node = scenario.nodes.get(scenario.win_node_id) + if not win_node: + logger.error(f"Win node not found: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node does not exist" + } + + # 获取正确的胜利字符串(取第一个 golden_output_value) + if win_node.golden_output_values: + correct_answer = list(win_node.golden_output_values.values())[0] + else: + logger.error(f"Win node has no golden_output_values: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node has no correct answer" + } + + # 验证提交的答案 + if req.answer == correct_answer: + logger.info(f"🎉 CORRECT ANSWER SUBMITTED - case: {case_id}, answer: {req.answer}") + return { + "ok": True, + "is_win": True, + "victory_message": f"🎉 Congratulations on successfully escaping the room! Your answer is correct: {req.answer}" + } + else: + logger.info(f"❌ INCORRECT ANSWER SUBMITTED - case: {case_id}, submitted: {req.answer}, correct: {correct_answer}") + return { + "ok": True, + "is_win": False, + "error": f"The submitted answer is incorrect. You submitted: {req.answer}" + } + +if __name__ == "__main__": + + uvicorn.run(app, host="0.0.0.0", port=8000) \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-356c0ae2/environment/puzzle/upstream/simulator.py b/tasks/agentescape-25-skeleton-356c0ae2/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-25-skeleton-356c0ae2/environment/puzzle/upstream/simulator.py @@ -0,0 +1,2911 @@ +import hashlib +import hmac +import base64 +import binascii +import zlib +import json +import uuid +import math +import re +from typing import Dict, Any, List + +class ToolSimulator: + def __init__(self): + """工具模拟器 + + 文件处理工具(zip_unzip, zip_unzip_file, zip_unzip_item, json_get, csv_query, + regex_search, graph_shortest_path)不需要真实文件系统。 + 这些工具只验证输入参数,然后返回预先初始化好的 golden_outputs。 + """ + self.tool_map = { + # 数论 + "calc_bigmul": self.calc_bigmul, + "calc_modexp": self.calc_modexp, + "calc_modexp_int": self.calc_modexp_int, + "calc_gcd": self.calc_gcd, + "calc_gcd_int": self.calc_gcd_int, + "calc_inv_mod": self.calc_inv_mod, + "calc_inv_mod_int": self.calc_inv_mod_int, + + # 哈希 + "hash_sha256": self.hash_sha256, + "hash_md5": self.hash_md5, + "hmac_sha256": self.hmac_sha256, + + # 编码 + "base64_decode": self.base64_decode, + "base64_encode": self.base64_encode, + "hex_decode": self.hex_decode, + "hex_encode": self.hex_encode, + "zlib_inflate": self.zlib_inflate, + "zlib_deflate": self.zlib_deflate, + + # 文件 + "zip_unzip": self.zip_unzip, + "zip_unzip_file": self.zip_unzip_file, + "zip_unzip_item": self.zip_unzip_item, + "regex_search": self.regex_search, + "json_get": self.json_get, + "csv_query": self.csv_query, + "code_py_exec": self.code_py_exec, + + # 图 + "graph_shortest_path": self.graph_shortest_path, + + # 加解密 (简化模拟) + "crypto_aes_cbc_decrypt": self.crypto_aes_cbc_decrypt, + "crypto_rsa_decrypt_hex": self.crypto_rsa_decrypt_hex, + + # 其他 + "num_base_convert": self.num_base_convert, + "time_convert": self.time_convert, + "checksum_crc32": self.checksum_crc32, + "geo_haversine": self.geo_haversine, + "otp_totp_generate": self.otp_totp_generate, + "unicode_norm": self.unicode_norm, + "text_bidi_sanitize": self.text_bidi_sanitize, + "text_xor_hex": self.text_xor_hex, + "text_rotN": self.text_rotN, + "luhn_check": self.luhn_check, + "iban_validate": self.iban_validate, + + # 物理 + "matter_synthesizer": self.matter_synthesizer, + + # 终端机 + "terminal_1": self.terminal_1, + "terminal_2": self.terminal_2, + "Logic Terminal": self.logic_terminal, + "Math Terminal": self.math_terminal, + "Encryption Terminal": self.crypt_terminal, + "Sequence Terminal": self.sequence_terminal + } + + def execute(self, tool_name: str, inputs: Dict[str, Any]) -> Dict[str, Any]: + if tool_name not in self.tool_map: + # Fallback for unknown tools: return dummy outputs based on expected output types + # This should ideally not happen if all tools are implemented + return {} + + try: + return self.tool_map[tool_name](inputs) + except Exception as e: + print(f"Error executing {tool_name}: {e}") + # Return empty or error indication? For generation, we might want to fail hard or return dummy. + # For now, return dummy to keep flow going, but log error. + return {} + + # --- Implementations --- + + def calc_bigmul(self, inputs): + # Check if required parameters are present + if "a" not in inputs or "b" not in inputs: + raise ValueError("Missing required parameters 'a' and/or 'b'") + + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + return {"product": str(a * b)} + except (ValueError, TypeError) as e: + raise ValueError(f"Failed to convert parameters to integers: {str(e)}") + + def calc_modexp(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + try: + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if isinstance(base, str): + base = int(base) + elif not isinstance(base, int): + raise ValueError("Parameter 'base' must be a string or integer") + + if isinstance(exp, str): + exp = int(exp) + elif not isinstance(exp, int): + raise ValueError("Parameter 'exp' must be a string or integer") + + if isinstance(mod, str): + mod = int(mod) + elif not isinstance(mod, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": str(pow(base, exp, mod))} + + def calc_modexp_int(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["base"], int): + raise ValueError("Parameter 'base' must be an integer") + if not isinstance(inputs["exp"], int): + raise ValueError("Parameter 'exp' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": pow(base, exp, mod)} + + def calc_gcd(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + # 计算 GCD 并返回字符串格式(符合 Big_Int 输出类型) + result = math.gcd(a, b) + return {"gcd": str(result)} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def calc_gcd_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["b"], int): + raise ValueError("Parameter 'b' must be an integer") + + # 获取参数 + a = inputs["a"] + b = inputs["b"] + + return {"gcd": math.gcd(a, b)} + + def calc_inv_mod(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + m = inputs["mod"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(m, str): + m = int(m) + elif not isinstance(m, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": str(pow(a, -1, m))} + except ValueError as e: + # 模逆不存在时,返回一个特殊值(用于数据传递) + # 在 DAG 生成阶段,这允许数据流继续 + return {"inv": str(a)} + + def calc_inv_mod_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + a = inputs["a"] + m = inputs["mod"] + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": pow(a, -1, m)} + except ValueError as e: + raise ValueError(f"Modular inverse does not exist: {str(e)}") + + def hash_sha256(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.sha256(text.encode()).hexdigest()} + + def hash_md5(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.md5(text.encode()).hexdigest()} + + def hmac_sha256(self, inputs): + # 参数检查 + if "hex_key" not in inputs: + raise ValueError("Missing required parameter: hex_key") + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["hex_key"], str): + raise ValueError("Parameter 'hex_key' must be a string") + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + try: + key = bytes.fromhex(inputs["hex_key"]) + text = inputs["text"].encode() + return {"hex": hmac.new(key, text, hashlib.sha256).hexdigest()} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def base64_decode(self, inputs): + # 参数检查 + if "data" not in inputs: + raise ValueError("Missing required parameter: data") + + # 类型检查 + if not isinstance(inputs["data"], str): + raise ValueError("Parameter 'data' must be a string") + + data = inputs["data"] + try: + return {"bytes_hex": binascii.hexlify(base64.b64decode(data)).decode()} + except Exception as e: + raise ValueError(f"Base64 decode error: {str(e)}") + + def base64_encode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"b64": base64.b64encode(bytes.fromhex(hex_data)).decode()} + except Exception as e: + raise ValueError(f"Base64 encode error: {str(e)}") + + def hex_decode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"text": bytes.fromhex(hex_data).decode('utf-8', errors='ignore')} + except Exception as e: + raise ValueError(f"Hex decode error: {str(e)}") + + def hex_encode(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + try: + return {"hex": text.encode().hex()} + except Exception as e: + raise ValueError(f"Hex encode error: {str(e)}") + + + # 到此处实现已经更新 + + def zlib_inflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("Parameter 'hex' must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("Missing required parameter: hex") + + try: + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空字符串 + if not hex_data: + raise ValueError("Empty hex string provided") + + # 检查十六进制字符串的有效性 + if len(hex_data) % 2 != 0: + raise ValueError("Hex string must have even length") + + # 检查是否只包含有效的十六进制字符 + if not all(c in '0123456789abcdefABCDEF' for c in hex_data): + raise ValueError("Invalid hex string provided") + + # 尝试解压缩 + return {"text": zlib.decompress(bytes.fromhex(hex_data)).decode('utf-8')} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hex string provided") from e + raise ValueError(f"Invalid zlib data: {e}") from e + except Exception as e: + raise RuntimeError(f"Failed to inflate data: {e}") from e + + def zlib_deflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("Parameter 'text' must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("Missing required parameter: text") + + try: + # 压缩文本 + return {"hex": zlib.compress(text.encode('utf-8')).hex()} + except Exception as e: + raise RuntimeError(f"Failed to deflate data: {e}") from e + + # --- File Operations --- + + def zip_unzip(self, inputs): + """ZIP 解压工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"files": golden_outputs.get("files", "")} + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return {"files": golden_outputs.get("files", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "files" in golden_outputs: + # 验证必需参数 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 检查类型 + if has_zip_id and not isinstance(zip_id, str): + return {"error": "Parameter 'zip_id' must be a string type"} + if has_password and not isinstance(password, str): + return {"error": "Parameter 'password' must be a string type"} + + # 验证输入是否与预期匹配 + if golden_inputs: + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return {"files": golden_outputs["files"]} + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + # 没有golden_inputs但有golden_outputs,直接返回输出 + return {"files": golden_outputs["files"]} + + # 如果没有预期输出,返回空结果 + return {"files": ""} + + def regex_search(self, inputs): + """正则搜索工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"matches": golden_outputs.get("matches", "[]")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "matches" in golden_outputs: + # 提取实际参数 + pattern = inputs.get("pattern") + file_id = inputs.get("file_id") + text = inputs.get("text") + + # 1. 检查必需参数 + if pattern is None: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["pattern"], + "message": "Missing required parameter 'pattern'" + } + } + + # 类型检查 + if not isinstance(pattern, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "pattern", + "message": "Parameter 'pattern' must be a string type" + } + } + if file_id is not None and not isinstance(file_id, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if text is not None and not isinstance(text, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "text", + "message": "Parameter 'text' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合 + provided_params = {} + if pattern is not None: + provided_params["pattern"] = pattern + if file_id is not None: + provided_params["file_id"] = file_id + if text is not None: + provided_params["text"] = text + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数(关键改进) + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_pattern = golden_inputs.get("pattern") + expected_file_id = golden_inputs.get("file_id") + expected_text = golden_inputs.get("text") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_pattern is not None: + if str(pattern) != str(expected_pattern): + incorrect_params.append("pattern") + else: + correct_params.append("pattern") + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_text is not None: + if str(text) != str(expected_text): + incorrect_params.append("text") + else: + correct_params.append("text") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "matches": "[]", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "matches": golden_outputs["matches"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空列表 + return {"matches": "[]"} + + def json_get(self, inputs): + """JSON 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"values": golden_outputs.get("values", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "values" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + jsonpath = inputs.get("jsonpath", "") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if jsonpath is not None and not isinstance(jsonpath, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "jsonpath", + "message": "Parameter 'jsonpath' must be a string type" + } + } + + # 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:jsonpath有默认值"") + provided_params = {} + if file_id is not None: + provided_params["file_id"] = file_id + if jsonpath != "": + provided_params["jsonpath"] = jsonpath + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_jsonpath = golden_inputs.get("jsonpath") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_jsonpath is not None: + if str(jsonpath) != str(expected_jsonpath): + incorrect_params.append("jsonpath") + else: + correct_params.append("jsonpath") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "values": "", + "_validation": validation_info + } + + # 所有验证通过,返回正确输出 + return { + "values": golden_outputs["values"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"values": ""} + + def csv_query(self, inputs): + """CSV 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"rows": golden_outputs.get("rows", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "rows" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + select_columns = inputs.get("select", "") + where_clause = inputs.get("where", "") + + # 1. 检查必需参数 + if file_id is None: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["file_id"], + "message": "Missing required parameter 'file_id'" + } + } + + # 类型检查 + if not isinstance(file_id, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if not isinstance(select_columns, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "select", + "message": "Parameter 'select' must be a string type" + } + } + if not isinstance(where_clause, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "where", + "message": "Parameter 'where' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:select和where有默认值"") + provided_params = {"file_id": file_id} + if select_columns != "": + provided_params["select"] = select_columns + if where_clause != "": + provided_params["where"] = where_clause + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_select = golden_inputs.get("select") + expected_where = golden_inputs.get("where") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_select is not None: + if str(select_columns) != str(expected_select): + incorrect_params.append("select") + else: + correct_params.append("select") + + if expected_where is not None: + if str(where_clause) != str(expected_where): + incorrect_params.append("where") + else: + correct_params.append("where") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "rows": "", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "rows": golden_outputs["rows"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"rows": ""} + + def graph_shortest_path(self, inputs): + """图最短路径工具 + + 如果有 _golden_outputs 或 _init_outputs,验证输入并返回预设输出。 + 否则执行真实的 Dijkstra 算法。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 检查是否在预设模式中(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + if golden_outputs and "path" in golden_outputs: + # 评测阶段但没有 golden_inputs,直接返回 outputs + if not golden_inputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 评测模式:验证输入参数是否匹配 golden 值 + src = inputs.get("src") + dst = inputs.get("dst") + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + + has_src = src is not None and src != "" + has_dst = dst is not None and dst != "" + + # 验证必需参数 + if not has_src or not has_dst: + missing = [] + if not has_src: + missing.append("src") + if not has_dst: + missing.append("dst") + return {"error": "Missing required parameters: " + ", ".join(missing)} + + # 类型检查 + if not isinstance(src, str): + return {"error": "Parameter 'src' must be a string"} + if not isinstance(dst, str): + return {"error": "Parameter 'dst' must be a string"} + + # 验证输入是否匹配期望值 + if golden_inputs: + expected_src = golden_inputs.get("src") + expected_dst = golden_inputs.get("dst") + expected_file_id = golden_inputs.get("file_id") + expected_graph_data = golden_inputs.get("graph_data") + + # 收集验证结果 + incorrect_params = [] + correct_params = [] + + # 检查必需参数是否匹配 + if expected_src is not None: + if str(src) != str(expected_src): + incorrect_params.append("src") + else: + correct_params.append("src") + + if expected_dst is not None: + if str(dst) != str(expected_dst): + incorrect_params.append("dst") + else: + correct_params.append("dst") + + # 检查可选参数(如果在 expected_inputs 中定义了) + if expected_file_id is not None: + if file_id != expected_file_id: + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_graph_data is not None: + if graph_data != expected_graph_data: + incorrect_params.append("graph_data") + else: + correct_params.append("graph_data") + + # 如果有参数不正确,返回详细的反馈 + if incorrect_params: + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 验证通过,返回预设的输出 + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 获取参数(真实执行路径) + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + # Support both src/dst (interface definition) and start/end (original implementation) + start = inputs.get("src") + end = inputs.get("dst") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + raise TypeError("file_id must be a string") + + if graph_data is not None and not isinstance(graph_data, str): + raise TypeError("graph_data must be a string") + + if start is not None and not isinstance(start, str): + raise TypeError("src/start must be a string") + + if end is not None and not isinstance(end, str): + raise TypeError("dst/end must be a string") + + # 检查必需参数 + if file_id is None and graph_data is None: + raise ValueError("Either file_id or graph_data must be provided") + + if start is None: + raise ValueError("src/start parameter is required") + + if end is None: + raise ValueError("dst/end parameter is required") + + # Get graph content + content = None + if file_id is not None: + # 尝试从 VFS 获取(如果存在) + if hasattr(self, 'vfs') and file_id in self.vfs: + content = self.vfs[file_id] + else: + # VFS 不存在或文件不在 VFS 中 + # 返回一个默认的空图结果,或者抛出错误提示需要 init_outputs + raise ValueError( + f"File '{file_id}' not found. For tools that require files, " + f"please provide init_outputs in the initial_values." + ) + elif graph_data is not None: + content = graph_data + + if content is None: + content = "{}" + + try: + # Parse graph data + graph = json.loads(content) + + # 类型检查 + if not isinstance(graph, dict): + raise TypeError("Graph data must be a dictionary") + + # If graph is not in the expected format, try to extract adjacency list + if "nodes" in graph and "edges" in graph: + # 验证nodes和edges的类型 + if not isinstance(graph["nodes"], list): + raise TypeError("Nodes must be a list") + + if not isinstance(graph["edges"], list): + raise TypeError("Edges must be a list") + + # Convert from nodes/edges format to adjacency list + adjacency_list = {} + for node in graph["nodes"]: + # 验证node类型 + if not isinstance(node, dict): + raise TypeError("Each node must be a dictionary") + + # Use node ID as key, not the entire node dictionary + node_id = node.get("id", "") + if node_id: + adjacency_list[node_id] = {} + + for edge in graph["edges"]: + # 验证edge类型 + if not isinstance(edge, dict): + raise TypeError("Each edge must be a dictionary") + + u = edge["from"] + v = edge["to"] + weight = edge.get("weight", 1) # Default to unweighted + + # 类型检查 + if not isinstance(u, str): + raise TypeError("Edge 'from' must be a string") + + if not isinstance(v, str): + raise TypeError("Edge 'to' must be a string") + + if not isinstance(weight, (int, float)): + raise TypeError("Edge weight must be a number") + + if u not in adjacency_list: + adjacency_list[u] = {} + if v not in adjacency_list: + adjacency_list[v] = {} + + adjacency_list[u][v] = weight + # If undirected, add reverse edge + if not edge.get("directed", False): + adjacency_list[v][u] = weight + elif isinstance(graph, dict): + # Already in adjacency list format + adjacency_list = graph + + # 验证邻接表结构 + for node, neighbors in adjacency_list.items(): + if not isinstance(neighbors, dict): + raise TypeError("Adjacency list must be a dictionary of dictionaries") + + for neighbor, weight in neighbors.items(): + if not isinstance(weight, (int, float)): + raise TypeError("Edge weights must be numbers") + else: + raise TypeError("Graph data must be a dictionary") + + # 检查起点和终点是否为空 + if not start: + raise ValueError("Start node cannot be empty") + + if not end: + raise ValueError("End node cannot be empty") + + # 检查起点和终点是否在图中 + if start not in adjacency_list: + raise ValueError(f"Start node '{start}' not found in graph") + + if end not in adjacency_list: + raise ValueError(f"End node '{end}' not found in graph") + + # Dijkstra's algorithm implementation + import heapq + + # Initialize distances and previous nodes + distances = {node: float('infinity') for node in adjacency_list} + previous = {node: None for node in adjacency_list} + distances[start] = 0 + + # Priority queue + pq = [(0, start)] + heapq.heapify(pq) + + while pq: + current_dist, current_node = heapq.heappop(pq) + + # If we've reached the end node, we can break early + if current_node == end: + break + + # Nodes can be added multiple times to the priority queue, but we only process them once + if current_dist > distances[current_node]: + continue + + # Explore neighbors + for neighbor, weight in adjacency_list[current_node].items(): + distance = current_dist + weight + + # If a shorter path is found + if distance < distances[neighbor]: + distances[neighbor] = distance + previous[neighbor] = current_node + heapq.heappush(pq, (distance, neighbor)) + + # Reconstruct the shortest path + path = [] + current = end + while current is not None: + path.append(current) + current = previous[current] + path.reverse() # Reverse to get from start to end + + # Check if path exists + if not path or path[0] != start: + return {"path": "[]", "cost": 0} + + return { + "path": json.dumps(path), + "cost": distances[end] + } + except json.JSONDecodeError as e: + raise ValueError(f"Invalid JSON in graph data: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in graph_shortest_path: {str(e)}") + + # --- Crypto (Simplified) --- + def crypto_aes_cbc_decrypt(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 (使用模板中定义的参数名) + hex_cipher = inputs.get("hex_cipher") + hex_key = inputs.get("hex_key") + hex_iv = inputs.get("hex_iv") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + + if hex_key is not None and not isinstance(hex_key, str): + raise TypeError("hex_key must be a string") + + if hex_iv is not None and not isinstance(hex_iv, str): + raise TypeError("hex_iv must be a string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + + if hex_key is None: + raise ValueError("hex_key parameter is required") + + if hex_iv is None: + raise ValueError("hex_iv parameter is required") + + from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes + from cryptography.hazmat.backends import default_backend + from cryptography.hazmat.primitives import padding + + try: + # Convert hex strings to bytes + ciphertext = bytes.fromhex(hex_cipher) + key = bytes.fromhex(hex_key) + iv = bytes.fromhex(hex_iv) + + # Validate key length (AES-128, AES-192, AES-256) + if len(key) not in [16, 24, 32]: + raise ValueError("Invalid key length. Must be 16, 24, or 32 bytes.") + + if len(iv) != 16: + raise ValueError("Invalid IV length. Must be 16 bytes.") + + # Create cipher object + cipher = Cipher( + algorithms.AES(key), + modes.CBC(iv), + backend=default_backend() + ) + + decryptor = cipher.decryptor() + + # Decrypt the ciphertext + padded_plaintext = decryptor.update(ciphertext) + decryptor.finalize() + + # Remove PKCS7 padding + unpadder = padding.PKCS7(128).unpadder() + plaintext = unpadder.update(padded_plaintext) + unpadder.finalize() + + # Return decrypted text + return {"text": plaintext.decode('utf-8', errors='ignore')} + except ValueError as e: + if "non-hexadecimal number found in fromhex()" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher, hex_key, or hex_iv") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in crypto_aes_cbc_decrypt: {str(e)}") + + def crypto_rsa_decrypt_hex(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_cipher = inputs.get("hex_cipher") + n = inputs.get("n") + d = inputs.get("d") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + if n is not None and not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + if d is not None and not isinstance(d, (int, str)): + raise TypeError("d must be an integer or string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + if n is None: + raise ValueError("n parameter is required") + if d is None: + raise ValueError("d parameter is required") + + try: + # Convert parameters to appropriate types + cipher_int = int(hex_cipher, 16) + n_int = int(n) if isinstance(n, str) else n + d_int = int(d) if isinstance(d, str) else d + + # RSA decryption: plaintext = ciphertext^d mod n + plaintext_int = pow(cipher_int, d_int, n_int) + + # Convert result to hex and then to text + plaintext_hex = hex(plaintext_int)[2:] + + # Pad with leading zero if odd length + if len(plaintext_hex) % 2 != 0: + plaintext_hex = '0' + plaintext_hex + + # Convert hex to bytes and then to text + try: + plaintext_bytes = bytes.fromhex(plaintext_hex) + plaintext_text = plaintext_bytes.decode('utf-8', errors='ignore') + except: + # If decoding fails, return hex representation + plaintext_text = plaintext_hex + + return {"text": plaintext_text} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in crypto_rsa_decrypt_hex: {str(e)}") + + # --- Others --- + def num_base_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + s = inputs.get("s") + from_base = inputs.get("from_base") + to_base = inputs.get("to_base") + + # 类型检查 - 接受 str 或 int + if s is not None and not isinstance(s, (str, int)): + raise TypeError("s must be a string or integer") + + if from_base is not None and not isinstance(from_base, (int, str)): + raise TypeError("from_base must be an integer") + + if to_base is not None and not isinstance(to_base, (int, str)): + raise TypeError("to_base must be an integer") + + # 检查必需参数 + if s is None: + raise ValueError("s parameter is required") + + if from_base is None: + raise ValueError("from_base parameter is required") + + if to_base is None: + raise ValueError("to_base parameter is required") + + try: + # Convert to int if needed + from_base = int(from_base) if isinstance(from_base, str) else from_base + to_base = int(to_base) if isinstance(to_base, str) else to_base + s_str = str(s) + + # 验证基数范围 + if from_base < 2 or from_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + if to_base < 2 or to_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + # Convert from source base to decimal + val = int(s_str, from_base) + + # Convert from decimal to target base + if to_base == 10: + result = str(val) + elif to_base == 16: + result = hex(val)[2:] + elif to_base == 8: + result = oct(val)[2:] + elif to_base == 2: + result = bin(val)[2:] + else: + # Generic base conversion for other bases + if val == 0: + result = "0" + else: + digits = "0123456789abcdefghijklmnopqrstuvwxyz" + result = "" + n = abs(val) + while n: + result = digits[n % to_base] + result + n //= to_base + if val < 0: + result = "-" + result + + return {"str": result} + except ValueError as e: + raise ValueError(f"Invalid number format: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in num_base_convert: {str(e)}") + + def time_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iso = inputs.get("iso") + timestamp = inputs.get("timestamp") + datetime_str = inputs.get("datetime") + from_tz = inputs.get("from_tz") + to_tz = inputs.get("to_tz") + format_str = inputs.get("format") + + # 类型检查 + if iso is not None and not isinstance(iso, str): + raise TypeError("iso must be a string") + + if timestamp is not None and not isinstance(timestamp, (str, int, float)): + raise TypeError("timestamp must be a string, integer, or float") + + if datetime_str is not None and not isinstance(datetime_str, str): + raise TypeError("datetime must be a string") + + if from_tz is not None and not isinstance(from_tz, str): + raise TypeError("from_tz must be a string") + + if to_tz is not None and not isinstance(to_tz, str): + raise TypeError("to_tz must be a string") + + if format_str is not None and not isinstance(format_str, str): + raise TypeError("format must be a string") + + # 设置默认值 + if from_tz is None: + from_tz = "UTC" + + if to_tz is None: + to_tz = "UTC" + + import datetime + import pytz + + # 验证时区参数 + try: + if from_tz: + pytz.timezone(from_tz) + if to_tz: + pytz.timezone(to_tz) + except Exception: + raise ValueError("Invalid timezone provided") + + try: + # Parse input time + dt = None + + if iso is not None: + # Parse ISO 8601 format + dt = datetime.datetime.fromisoformat(iso.replace('Z', '+00:00')) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=pytz.UTC) + elif timestamp is not None: + # Parse Unix timestamp + timestamp = float(timestamp) + dt = datetime.datetime.fromtimestamp(timestamp, pytz.UTC) + elif datetime_str is not None: + # Parse datetime string + # Try common formats + formats_to_try = [ + "%Y-%m-%d %H:%M:%S", + "%Y-%m-%d %H:%M:%S.%f", + "%Y-%m-%d", + "%m/%d/%Y %H:%M:%S", + "%m/%d/%Y" + ] + + parse_success = False + for fmt in formats_to_try: + try: + dt = datetime.datetime.strptime(datetime_str, fmt) + dt = pytz.timezone(from_tz).localize(dt) + parse_success = True + break + except ValueError: + continue + + if not parse_success: + raise ValueError("Unable to parse datetime string with common formats") + else: + # 如果没有提供任何时间参数,则使用当前时间 + dt = datetime.datetime.now(pytz.UTC) + except ValueError as e: + raise ValueError(f"Error parsing time input: {str(e)}") + except Exception as e: + raise RuntimeError(f"Unexpected error parsing time input: {str(e)}") + + try: + # Convert timezone + if from_tz != to_tz: + dt = dt.astimezone(pytz.timezone(to_tz)) + + # Format outputs + result = { + "iso": dt.isoformat(), + "timestamp": str(dt.timestamp()), + "datetime": dt.strftime("%Y-%m-%d %H:%M:%S"), + "date": dt.strftime("%Y-%m-%d"), + "time": dt.strftime("%H:%M:%S"), + "timezone": to_tz + } + + # Add custom format if requested + if format_str: + try: + result["formatted"] = dt.strftime(format_str) + except ValueError as e: + raise ValueError(f"Invalid format string: {str(e)}") + + return result + except Exception as e: + raise RuntimeError(f"Error in time_convert: {str(e)}") + + def checksum_crc32(self, inputs): + import zlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("hex must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("hex parameter is required") + + try: + # 验证十六进制字符串 + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空 + if not hex_data: + raise ValueError("hex data cannot be empty") + + # 检查是否为有效的十六进制字符串 + if not all(c in "0123456789abcdefABCDEF" for c in hex_data): + raise ValueError("hex must be a valid hexadecimal string") + + # 检查长度是否为偶数 + if len(hex_data) % 2 != 0: + raise ValueError("hex must have even number of characters") + + val = zlib.crc32(bytes.fromhex(hex_data)) + # 确保 hex 输出是 8 位,前导补 0 + return {"hex": f"{val:08x}", "int": val} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in checksum_crc32: {str(e)}") + + def geo_haversine(self, inputs): + import math + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + lat1 = inputs.get("lat1") + lon1 = inputs.get("lon1") + lat2 = inputs.get("lat2") + lon2 = inputs.get("lon2") + + # 类型检查 + if lat1 is not None and not isinstance(lat1, (int, float, str)): + raise TypeError("lat1 must be a number or string") + if lon1 is not None and not isinstance(lon1, (int, float, str)): + raise TypeError("lon1 must be a number or string") + if lat2 is not None and not isinstance(lat2, (int, float, str)): + raise TypeError("lat2 must be a number or string") + if lon2 is not None and not isinstance(lon2, (int, float, str)): + raise TypeError("lon2 must be a number or string") + + # 检查必需参数 + if lat1 is None: + raise ValueError("lat1 parameter is required") + if lon1 is None: + raise ValueError("lon1 parameter is required") + if lat2 is None: + raise ValueError("lat2 parameter is required") + if lon2 is None: + raise ValueError("lon2 parameter is required") + + try: + # 转换为浮点数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(lat1, str): + lat1 = float(lat1) + elif not isinstance(lat1, (int, float)): + raise TypeError("lat1 must be a number or string") + else: + lat1 = float(lat1) + + if isinstance(lon1, str): + lon1 = float(lon1) + elif not isinstance(lon1, (int, float)): + raise TypeError("lon1 must be a number or string") + else: + lon1 = float(lon1) + + if isinstance(lat2, str): + lat2 = float(lat2) + elif not isinstance(lat2, (int, float)): + raise TypeError("lat2 must be a number or string") + else: + lat2 = float(lat2) + + if isinstance(lon2, str): + lon2 = float(lon2) + elif not isinstance(lon2, (int, float)): + raise TypeError("lon2 must be a number or string") + else: + lon2 = float(lon2) + + # Validate coordinates (approximate range check) + if not (-90 <= lat1 <= 90): + raise ValueError("lat1 must be between -90 and 90") + if not (-90 <= lat2 <= 90): + raise ValueError("lat2 must be between -90 and 90") + if not (-180 <= lon1 <= 180): + raise ValueError("lon1 must be between -180 and 180") + if not (-180 <= lon2 <= 180): + raise ValueError("lon2 must be between -180 and 180") + + # Earth radius in meters + R = 6371000 # Approximate radius of Earth + + # Convert degrees to radians + lat1_rad = math.radians(lat1) + lon1_rad = math.radians(lon1) + lat2_rad = math.radians(lat2) + lon2_rad = math.radians(lon2) + + # Calculate differences + delta_lat = lat2_rad - lat1_rad + delta_lon = lon2_rad - lon1_rad + + # Haversine formula + a = math.sin(delta_lat / 2) ** 2 + \ + math.cos(lat1_rad) * math.cos(lat2_rad) * \ + math.sin(delta_lon / 2) ** 2 + c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) + distance_m = R * c + + # Return distance in meters + return {"meters": round(distance_m, 2)} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in geo_haversine: {str(e)}") + + def otp_totp_generate(self, inputs): + import hmac + import hashlib + import base64 + import time + import struct + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + base32_secret = inputs.get("base32_secret") + step = inputs.get("step", 30) # Default to 30 seconds + digits = inputs.get("digits", 6) # Default to 6 digits + timestamp_iso = inputs.get("timestamp_iso", "") + algo = inputs.get("algo", "sha1") # Default to sha1 as current implementation only supports this + + # 类型检查 + if base32_secret is not None and not isinstance(base32_secret, str): + raise TypeError("base32_secret must be a string") + if not isinstance(step, (int, str)): + raise TypeError("step must be an integer or string") + if not isinstance(digits, (int, str)): + raise TypeError("digits must be an integer or string") + if not isinstance(timestamp_iso, str): + raise TypeError("timestamp_iso must be a string") + if not isinstance(algo, str): + raise TypeError("algo must be a string") + + # 检查必需参数 + if base32_secret is None: + raise ValueError("base32_secret parameter is required") + + try: + # Convert step and digits to appropriate types + step = int(step) + digits = int(digits) + if digits < 6 or digits > 8: + raise ValueError("Digits must be between 6 and 8") + + # Convert timestamp_iso to integer timestamp + if timestamp_iso: + import datetime + dt = datetime.datetime.fromisoformat(timestamp_iso.replace('Z', '+00:00')) + timestamp = int(dt.timestamp()) + else: + timestamp = int(time.time()) + + # Calculate counter value (T = floor(timestamp / step)) + counter = timestamp // step + + # Decode the base32 secret + # Add padding if necessary (base64 requires padding to be multiple of 8) + base32_secret = base32_secret.upper().replace(' ', '') + if len(base32_secret) % 8 != 0: + base32_secret += '=' * (8 - (len(base32_secret) % 8)) + key = base64.b32decode(base32_secret, casefold=True) + + # Calculate HMAC-SHA1 + counter_bytes = struct.pack('>Q', counter) # Big-endian 8-byte integer + hmac_hash = hmac.new(key, counter_bytes, hashlib.sha1).digest() + + # Dynamic truncation + offset = hmac_hash[-1] & 0xF + code = struct.unpack('>I', hmac_hash[offset:offset+4])[0] & 0x7FFFFFFF + + # Generate the OTP + otp = str(code % (10 ** digits)).zfill(digits) + + # Calculate remaining time until next OTP change + remaining_time = step - (timestamp % step) + + return {"totp": otp, "remaining_time": remaining_time, "time_step": step} + except ValueError as e: + if "invalid literal for int()" in str(e): + raise ValueError("step and digits must be valid integers") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in otp_totp_generate: {str(e)}") + + def unicode_norm(self, inputs): + import unicodedata + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + form = inputs.get("form", "NFC") # Default to NFC + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if form is not None and not isinstance(form, str): + raise TypeError("form must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Normalize form (NFC, NFD, NFKC, NFKD) + form = form.upper().strip() + + if form not in ['NFC', 'NFD', 'NFKC', 'NFKD']: + raise ValueError(f"Invalid normalization form: {form}. Must be one of: NFC, NFD, NFKC, NFKD") + + # Apply Unicode normalization + normalized_text = unicodedata.normalize(form, text) + + return {"text": normalized_text} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in unicode_norm: {str(e)}") + + def text_bidi_sanitize(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Bidi control characters to remove + bidi_controls = [ + '\u200E', # LEFT-TO-RIGHT MARK + '\u200F', # RIGHT-TO-LEFT MARK + '\u202A', # LEFT-TO-RIGHT EMBEDDING + '\u202B', # RIGHT-TO-LEFT EMBEDDING + '\u202C', # POP DIRECTIONAL FORMATTING + '\u202D', # LEFT-TO-RIGHT OVERRIDE + '\u202E', # RIGHT-TO-LEFT OVERRIDE + '\u2066', # LEFT-TO-RIGHT ISOLATE + '\u2067', # RIGHT-TO-LEFT ISOLATE + '\u2068', # FIRST STRONG ISOLATE + '\u2069', # POP DIRECTIONAL ISOLATE + ] + + # Remove all Bidi control characters + sanitized_text = text + for control_char in bidi_controls: + sanitized_text = sanitized_text.replace(control_char, '') + + return {"text": sanitized_text} + except Exception as e: + raise RuntimeError(f"Error in text_bidi_sanitize: {str(e)}") + + def text_xor_hex(self, inputs): + import binascii + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_a = inputs.get("hex_a") + hex_b = inputs.get("hex_b") + + # 类型检查 + if hex_a is not None and not isinstance(hex_a, str): + raise TypeError("hex_a must be a string") + if hex_b is not None and not isinstance(hex_b, str): + raise TypeError("hex_b must be a string") + + # 检查必需参数 + if hex_a is None: + raise ValueError("hex_a parameter is required") + if hex_b is None: + raise ValueError("hex_b parameter is required") + + try: + # Remove any whitespace + hex_a = hex_a.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + hex_b = hex_b.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + + # Validate hex strings + if not (all(c in "0123456789abcdefABCDEF" for c in hex_a) and len(hex_a) % 2 == 0): + raise ValueError("hex_a must be a valid hexadecimal string with even length") + if not (all(c in "0123456789abcdefABCDEF" for c in hex_b) and len(hex_b) % 2 == 0): + raise ValueError("hex_b must be a valid hexadecimal string with even length") + + # Convert hex strings to bytes + bytes_a = binascii.unhexlify(hex_a) + bytes_b = binascii.unhexlify(hex_b) + + # Make the byte arrays the same length by padding the shorter one with zeros + max_len = max(len(bytes_a), len(bytes_b)) + bytes_a = bytes_a.ljust(max_len, b'\x00') + bytes_b = bytes_b.ljust(max_len, b'\x00') + + # Perform XOR operation + result_bytes = bytes(a ^ b for a, b in zip(bytes_a, bytes_b)) + + # Convert result back to hex + result_hex = binascii.hexlify(result_bytes).decode('utf-8') + + return {"hex": result_hex} + except ValueError as e: + if "Non-hexadecimal digit found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in text_xor_hex: {str(e)}") + + def text_rotN(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + n = inputs.get("n", 0) + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + n = int(n) + except ValueError: + raise ValueError("n must be a valid integer") + + result = [] + for char in text: + if char.isupper(): + # Rotate uppercase letters + result_char = chr((ord(char) - ord('A') + n) % 26 + ord('A')) + result.append(result_char) + elif char.islower(): + # Rotate lowercase letters + result_char = chr((ord(char) - ord('a') + n) % 26 + ord('a')) + result.append(result_char) + else: + # Keep non-alphabetic characters unchanged + result.append(char) + + return {"text": ''.join(result)} + + def luhn_check(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数(支持 card_number 和 number 两个参数名) + card_number = inputs.get("number") or inputs.get("card_number") + + # 类型检查 + if card_number is not None and not isinstance(card_number, str): + raise TypeError("number must be a string") + + # 检查必需参数 + if card_number is None: + raise ValueError("number parameter is required") + + try: + # 如果输入是JSON数组或其他非数字字符串,返回该字符串本身(用于数据传递) + # 这种情况发生在DAG设计中类型不匹配时 + if card_number.startswith('[') or card_number.startswith('{'): + # 输入是JSON,直接返回原值(用于传递) + return {"valid": card_number} + + # Remove whitespace from card number + card_number = card_number.replace(" ", "").replace("-", "") + + # Check if card number is all digits + if not card_number.isdigit() or len(card_number) < 13: + return {"valid": "false"} + + # Implement Luhn algorithm + total = 0 + reverse_digits = card_number[::-1] # Reverse the number for easier processing + + for i, digit in enumerate(reverse_digits): + num = int(digit) + if i % 2 == 1: # Every second digit starting from the right (which is first in reversed string) + num *= 2 + if num > 9: + num -= 9 # Equivalent to sum of digits for 2-digit numbers + total += num + + # Check if total is divisible by 10 + is_valid = total % 10 == 0 + return {"valid": "true" if is_valid else "false"} + except Exception as e: + raise RuntimeError(f"Error in luhn_check: {str(e)}") + + def iban_validate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iban = inputs.get("iban") + + # 类型检查 + if iban is not None and not isinstance(iban, str): + raise TypeError("iban must be a string") + + # 检查必需参数 + if iban is None: + raise ValueError("iban parameter is required") + + try: + # Remove whitespace from IBAN + iban = iban.replace(" ", "") + + # Basic length and format check + if not (len(iban) >= 15 and len(iban) <= 34): + return {"valid": "False"} + + if not (iban[:2].isalpha() and iban[2:].isdigit()): + return {"valid": "False"} + + # Move first four characters to the end + rearranged = iban[4:] + iban[:4] + + # Replace letters with numbers (A=10, B=11, ..., Z=35) + numeric_iban = '' + for char in rearranged: + if char.isdigit(): + numeric_iban += char + else: + numeric_iban += str(ord(char.upper()) - ord('A') + 10) + + # Perform modulo 97 check + # Use step-by-step approach for very large numbers + remainder = 0 + for char in numeric_iban: + remainder = (remainder * 10 + int(char)) % 97 + + is_valid = remainder == 1 + return {"valid": "True" if is_valid else "False"} + except Exception as e: + raise RuntimeError(f"Error in iban_validate: {str(e)}") + + def matter_synthesizer(self, inputs): + import hashlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + blueprint = inputs.get("blueprint") + + # 类型检查 + if blueprint is not None and not isinstance(blueprint, str): + raise TypeError("blueprint must be a string") + + try: + # Get blueprint parameter as defined in interface + if blueprint is None: + blueprint = "" + + # Generate a unique item ID based on the blueprint + # This ensures the same blueprint always produces the same item + blueprint_hash = hashlib.sha256(blueprint.encode()).hexdigest()[:16] + + # Create a synthesized item with a deterministic ID based on blueprint + synthesized_item = f"synthesized_item_{blueprint_hash}" + + return {"output_slot": synthesized_item} + except Exception as e: + raise RuntimeError(f"Error in matter_synthesizer: {str(e)}") + + # --- Terminal Implementations --- + def terminal_1(self, inputs): + """ + terminal_1: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 只返回 text_output + - 只输入正确的 slot_b → 只返回 hex_output + - 同时输入正确的 slot_a 和 slot_b → 返回 item_dispenser(物品掉落) + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + # 检查哪些输入被提供了 + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值是否正确(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + expected_a = golden_inputs["slot_a"] + a_valid = str(slot_a) == str(expected_a) + + if has_b and "slot_b" in golden_inputs: + expected_b = golden_inputs["slot_b"] + b_valid = str(slot_b) == str(expected_b) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 item_dispenser + if has_a and has_b: + if a_valid and b_valid: + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 text_output + if has_a and not has_b: + if a_valid: + if "text_output" in golden_outputs: + result["text_output"] = golden_outputs["text_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 hex_output + if has_b and not has_a: + if b_valid: + if "hex_output" in golden_outputs: + result["hex_output"] = golden_outputs["hex_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def terminal_2(self, inputs): + """ + terminal_2: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 text_result + - 同时输入正确的 num1 和 num2 → 返回 hex_result 和 math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + # 检查哪些输入被提供了 + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值是否正确(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + expected_num1 = golden_inputs["num1"] + num1_valid = str(num1) == str(expected_num1) + + if has_num2 and "num2" in golden_inputs: + expected_num2 = golden_inputs["num2"] + num2_valid = str(num2) == str(expected_num2) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 hex_result 和 math_token + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 text_result + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "text_result" in golden_outputs: + result["text_result"] = golden_outputs["text_result"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def logic_terminal(self, inputs): + """ + Logic Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 返回 screen(部分输出) + - 只输入正确的 slot_b → 返回 screen 和 secondary_output + - 同时输入正确的 slot_a 和 slot_b → 返回 screen, secondary_output, item_dispenser + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + a_valid = str(slot_a) == str(golden_inputs["slot_a"]) + + if has_b and "slot_b" in golden_inputs: + b_valid = str(slot_b) == str(golden_inputs["slot_b"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出(包括 item_dispenser) + if has_a and has_b: + if a_valid and b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 screen(部分输出) + if has_a and not has_b: + if a_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 screen 和 secondary_output + if has_b and not has_a: + if b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def math_terminal(self, inputs): + """ + Math Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 result_display + - 同时输入正确的 num1 和 num2 → 返回 result_display, hex_result, math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + num1_valid = str(num1) == str(golden_inputs["num1"]) + + if has_num2 and "num2" in golden_inputs: + num2_valid = str(num2) == str(golden_inputs["num2"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 result_display + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def crypt_terminal(self, inputs): + """ + Encryption Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 plaintext → 返回 status(部分输出) + - 同时输入正确的 plaintext 和 key → 返回 status, encrypted_hex, encryption_chip + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + plaintext = inputs.get("plaintext") + key = inputs.get("key") + + has_plaintext = plaintext is not None and plaintext != "" + has_key = key is not None and key != "" + + # 验证输入值(与 golden values 比较) + plaintext_valid = False + key_valid = False + + if has_plaintext and "plaintext" in golden_inputs: + plaintext_valid = str(plaintext) == str(golden_inputs["plaintext"]) + + if has_key and "key" in golden_inputs: + key_valid = str(key) == str(golden_inputs["key"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_plaintext and has_key: + if plaintext_valid and key_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + if "encrypted_hex" in golden_outputs: + result["encrypted_hex"] = golden_outputs["encrypted_hex"] + if "encryption_chip" in golden_outputs: + result["encryption_chip"] = golden_outputs["encryption_chip"] + return result + else: + incorrect_params = [] + correct_params = [] + if not plaintext_valid: + incorrect_params.append("plaintext") + else: + correct_params.append("plaintext") + if not key_valid: + incorrect_params.append("key") + else: + correct_params.append("key") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 plaintext 且正确 → 返回 status(部分输出) + if has_plaintext and not has_key: + if plaintext_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: plaintext"} + + # 只提供 key 但没有 plaintext + if has_key and not has_plaintext: + return {"error": "plaintext required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + def sequence_terminal(self, inputs): + """ + Sequence Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 sequence → 返回 verification(部分输出) + - 同时输入正确的 sequence 和 checksum → 返回 verification, auth_code, access_card + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + sequence = inputs.get("sequence") + checksum = inputs.get("checksum") + + has_sequence = sequence is not None and sequence != "" + has_checksum = checksum is not None and checksum != "" + + # 验证输入值(与 golden values 比较) + sequence_valid = False + checksum_valid = False + + if has_sequence and "sequence" in golden_inputs: + sequence_valid = str(sequence) == str(golden_inputs["sequence"]) + + if has_checksum and "checksum" in golden_inputs: + checksum_valid = str(checksum) == str(golden_inputs["checksum"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_sequence and has_checksum: + if sequence_valid and checksum_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + if "auth_code" in golden_outputs: + result["auth_code"] = golden_outputs["auth_code"] + if "access_card" in golden_outputs: + result["access_card"] = golden_outputs["access_card"] + return result + else: + incorrect_params = [] + correct_params = [] + if not sequence_valid: + incorrect_params.append("sequence") + else: + correct_params.append("sequence") + if not checksum_valid: + incorrect_params.append("checksum") + else: + correct_params.append("checksum") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 sequence 且正确 → 返回 verification(部分输出) + if has_sequence and not has_checksum: + if sequence_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: sequence"} + + # 只提供 checksum 但没有 sequence + if has_checksum and not has_sequence: + return {"error": "sequence required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + # --- Additional File Tools --- + + def zip_unzip_file(self, inputs): + """ZIP 解压文件工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def zip_unzip_item(self, inputs): + """ZIP 解压道具工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def code_py_exec(self, inputs): + """Python 代码执行工具 + + 这是一个真实执行的工具,在 DAG 生成阶段和运行时评测阶段都会执行代码。 + 输入: code (Python 代码字符串) + 输出: stdout (标准输出,包含执行结果和错误信息) + + 特殊行为: + - 如果代码定义了 main() 函数,会自动调用它 + - 如果执行出错,错误信息会包含在 stdout 中 + """ + code = inputs.get("code", "") + + if not code: + return {"stdout": "Error: No code provided"} + + try: + # 创建一个受限的执行环境 + import io + import sys + + # 捕获标准输出和标准错误 + old_stdout = sys.stdout + old_stderr = sys.stderr + sys.stdout = io.StringIO() + sys.stderr = io.StringIO() + + # 执行代码 + exec_globals = {"__builtins__": __builtins__} + exec_locals = {} + exec(code, exec_globals, exec_locals) + + # 如果定义了 main() 函数,自动调用它 + if 'main' in exec_locals and callable(exec_locals['main']): + exec_locals['main']() + + # 获取输出 + stdout_value = sys.stdout.getvalue() + stderr_value = sys.stderr.getvalue() + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 合并 stdout 和 stderr + output = stdout_value + if stderr_value: + output += ("\n" if output else "") + f"[stderr] {stderr_value}" + + # 如果没有任何输出,尝试返回 result 变量的值 + if not output: + result = exec_locals.get("_result") or exec_locals.get("result") + if result is not None: + output = str(result) + + return {"stdout": output if output else "(no output)"} + + except Exception as e: + # 恢复标准输出和错误输出 + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 返回错误信息 + return {"stdout": f"Error: {type(e).__name__}: {str(e)}"} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-356c0ae2/environment/puzzle/worker.Dockerfile b/tasks/agentescape-25-skeleton-356c0ae2/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-25-skeleton-356c0ae2/environment/puzzle/worker.Dockerfile @@ -0,0 +1,8 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends libseccomp2 && rm -rf /var/lib/apt/lists/* +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY worker.py child.py /app/ +COPY upstream/simulator.py /app/simulator.py +CMD ["uvicorn", "worker:app", "--host", "0.0.0.0", "--port", "8001", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-25-skeleton-356c0ae2/environment/puzzle/worker.py b/tasks/agentescape-25-skeleton-356c0ae2/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-25-skeleton-356c0ae2/environment/puzzle/worker.py @@ -0,0 +1,73 @@ +"""Stateless Python tool worker. Never receives a scenario or reference values.""" + +import json +import os +import signal +import subprocess +import sys +import tempfile +import threading + +from fastapi import FastAPI +from pydantic import BaseModel, ConfigDict + +app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) +lock = threading.Lock() + + +class Execution(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + code: str + + +@app.get("/health") +def health(): + return {"ok": True} + + +@app.post("/execute") +def execute(request: Execution): + if len(request.code.encode()) > 65536: + return {"stdout": "Error: code exceeds 64 KiB limit"} + with lock, tempfile.TemporaryDirectory(prefix="escape-code-") as directory: + os.chown(directory, 65534, 65534) + with tempfile.TemporaryFile() as output: + process = subprocess.Popen( + [sys.executable, "-I", "/app/child.py"], + stdin=subprocess.PIPE, + stdout=output, + stderr=subprocess.DEVNULL, + cwd=directory, + user=65534, + group=65534, + extra_groups=[], + start_new_session=True, + env={"PATH": "/usr/local/bin:/usr/bin:/bin"}, + ) + try: + process.communicate( + json.dumps({"code": request.code}).encode(), timeout=5 + ) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + return {"stdout": "Error: Python execution timed out"} + finally: + # Also remove children still in the process group after normal exit. + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + output.seek(0) + value = output.read(65537) + if len(value) > 65536 or process.returncode != 0: + return { + "stdout": "Error: Python execution exceeded a resource limit or failed" + } + try: + result = json.loads(value) + if not isinstance(result.get("stdout"), str): + raise ValueError("Invalid worker response") + return result + except (ValueError, AttributeError): + return {"stdout": "Error: Python execution returned invalid output"} diff --git a/tasks/agentescape-25-skeleton-356c0ae2/instruction.md b/tasks/agentescape-25-skeleton-356c0ae2/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-25-skeleton-356c0ae2/instruction.md @@ -0,0 +1,18 @@ +# Escape the room + +Discover the victory string and submit it with `escape submit-answer`. +Start with `escape observe`. This returns the room, available information, visible entities, and victory node ID. + +Use these commands (JSON responses): + +```sh +escape investigate NODE_ID +escape tool-call NODE_ID --arguments-json '{"parameter": "value"}' +escape use-item NODE_ID --arguments-json '{"parameter": "value"}' +escape submit-answer 'exact victory string' +escape state +``` + +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. + +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. diff --git a/tasks/agentescape-25-skeleton-356c0ae2/solution/oracle.py b/tasks/agentescape-25-skeleton-356c0ae2/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-25-skeleton-356c0ae2/solution/oracle.py @@ -0,0 +1,133 @@ +"""Reference solver: use trusted inputs, but obtain the answer through public actions.""" + +import json +import urllib.request +from pathlib import Path + + +def http_action(base_url, payload): + request = urllib.request.Request( + base_url + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(request, timeout=30) as response: + return json.load(response) + + +def solve(scenario, act, observe): + nodes = {node["id"]: node for node in scenario["nodes"]} + visible = {entity["id"] for entity in observe["available_entities"]} + solved = set() + seen_outputs = {} + action_count = 0 + + def call(payload): + nonlocal action_count + action_count += 1 + response = act(payload) + visible.update(entity["id"] for entity in response.get("newly_revealed", [])) + if ( + response.get("episode", {}).get("termination_reason") + == "infrastructure_error" + ): + raise RuntimeError("Infrastructure failure") + return response + + for _round in range(len(nodes) + 2): + progress = False + for node_id, node in nodes.items(): + if node_id not in visible or node_id in solved: + continue + # Preserve graph order for data inputs; trigger/drop edges express visibility. + predecessors = [ + edge["source_id"] + for edge in scenario["edges"] + if edge["target_id"] == node_id + and edge["connection_type"] not in ("Item", "Hidden_Item") + ] + if any(pred not in solved for pred in predecessors): + continue + info = call({"action": "investigate", "node_id": node_id}) + if not info.get("ok"): + raise RuntimeError(f"Investigation failed: {node_id}: {info}") + inputs = { + port["name"]: port["value"] + for port in node.get("inputs", []) + if "value" in port + } + if node["type"] == "Tool": + result = call( + {"action": "tool_call", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok") or result.get("output_values", {}).get("error"): + raise RuntimeError(f"Tool failed: {node_id}: {result}") + output = result.get("output_values", {}) + if node.get("template_id") in ("terminal_1", "terminal_2"): + slots = { + port["name"]: inputs[port["name"]] + for port in node["inputs"] + if port["type"] not in ("Item", "Hidden_Item") + and port["name"] in inputs + } + triggers = { + key: value for key, value in inputs.items() if key not in slots + } + for key, value in slots.items(): + partial = call( + { + "action": "tool_call", + "node_id": node_id, + "arguments": {**triggers, key: value}, + } + ) + if partial.get("ok"): + output.update(partial.get("output_values", {})) + # HIDDEN_ITEM tool drops only occur on subsequent investigation. + call({"action": "investigate", "node_id": node_id}) + elif info.get("required_inputs"): + result = call( + {"action": "use_item", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok"): + raise RuntimeError(f"Item failed: {node_id}: {result}") + output = result.get("content") + else: + output = info.get("content") + seen_outputs[node_id] = output + solved.add(node_id) + progress = True + win_id = scenario["metadata"]["win_node_id"] + if win_id in solved and (len(solved) == len(nodes) or not progress): + outputs = seen_outputs[win_id] + if not outputs: + raise RuntimeError(f"Victory node returned no output: {win_id}") + # Upstream grades its first stored output port, independent of response order. + victory_port = next( + port["name"] for port in nodes[win_id]["outputs"] if "value" in port + ) + answer = outputs[victory_port] if isinstance(outputs, dict) else outputs + result = call({"action": "submit_answer", "answer": answer}) + if not result.get("is_win"): + raise RuntimeError(f"Victory submission failed: {result}") + return {"won": True, "actions": action_count, "visited_nodes": len(solved)} + if not progress: + raise RuntimeError(f"No progress: visible={visible}, solved={solved}") + raise RuntimeError("Reference solver exceeded graph traversal limit") + + +if __name__ == "__main__": + import os + + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000") + with urllib.request.urlopen(base + "/observation", timeout=20) as response: + observation = json.load(response) + print( + json.dumps( + solve( + json.loads(Path("/solution/scenario.json").read_text()), + lambda payload: http_action(base, payload), + observation, + ) + ) + ) diff --git a/tasks/agentescape-25-skeleton-356c0ae2/solution/scenario.json b/tasks/agentescape-25-skeleton-356c0ae2/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..1777f91c2f64f4107c115c7749d5dc304c401ced --- /dev/null +++ b/tasks/agentescape-25-skeleton-356c0ae2/solution/scenario.json @@ -0,0 +1,1638 @@ +{ + "metadata": { + "total_nodes": 25, + "total_edges": 32, + "win_node_id": "hex_encode", + "win_condition": { + "type": "tool_output", + "node_id": "hex_encode", + "output_port": "hex", + "output_type": "Hex_String", + "description": "Execute Text to Hex Encoder and get the output from port 'hex'" + }, + "source_init": { + "source_nodes": [ + "terminal_1", + "calc_modexp", + "graph_shortest_path", + "crypto_rsa_decrypt_hex", + "zip_unzip_file", + "calc_inv_mod", + "zip_unzip_file_bff1", + "zlib_deflate", + "graph_shortest_path_9029", + "terminal_1_9158", + "container_2_d2bd", + "text_xor_hex", + "calc_bigmul", + "zip_unzip_file_d0b8", + "checksum_crc32", + "base64_encode", + "calc_gcd" + ], + "by_node": { + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": { + "slot_a": { + "type": "Text_Generic", + "description": "Input Slot A" + } + }, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + } + } + }, + "calc_modexp": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "exp": { + "type": "Big_Int", + "description": "Exponent" + } + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": {}, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "crypto_rsa_decrypt_hex": { + "node_name": "RSA Decrypt", + "node_type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "init_inputs": { + "n": { + "type": "Big_Int", + "description": "Modulus n" + }, + "d": { + "type": "Big_Int", + "description": "Private exponent d" + } + }, + "init_outputs": {} + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "calc_inv_mod": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "Integer a" + } + }, + "init_outputs": {} + }, + "zip_unzip_file_bff1": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "zlib_deflate": { + "node_name": "Zlib Deflate", + "node_type": "Tool", + "template_id": "zlib_deflate", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text to compress" + } + }, + "init_outputs": {} + }, + "graph_shortest_path_9029": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "dst": { + "type": "Text_Generic", + "description": "Destination node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "terminal_1_9158": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": { + "slot_a": { + "type": "Text_Generic", + "description": "Input Slot A" + } + }, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + } + } + }, + "container_2_d2bd": { + "node_name": "", + "node_type": "Item", + "template_id": "container_2", + "init_inputs": { + "fingerprint_input": { + "type": "Hex_String", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + }, + "text_xor_hex": { + "node_name": "Hex XOR", + "node_type": "Tool", + "template_id": "text_xor_hex", + "init_inputs": { + "hex_a": { + "type": "Hex_String", + "description": "Hex A" + }, + "hex_b": { + "type": "Hex_String", + "description": "Hex B" + } + }, + "init_outputs": {} + }, + "calc_bigmul": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First large integer" + }, + "b": { + "type": "Big_Int", + "description": "Second large integer" + } + }, + "init_outputs": {} + }, + "zip_unzip_file_d0b8": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "checksum_crc32": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + }, + "base64_encode": { + "node_name": "Base64 Encoder", + "node_type": "Tool", + "template_id": "base64_encode", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex bytes" + } + }, + "init_outputs": {} + }, + "calc_gcd": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First integer" + }, + "b": { + "type": "Big_Int", + "description": "Second integer" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "terminal_1": { + "init_inputs": { + "slot_a": "Initialize primary boot sequence." + }, + "init_outputs": { + "text_output": "Terminal 1 sequence activated successfully.", + "hex_output": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "calc_modexp": { + "init_inputs": { + "exp": "847392817364829103948572" + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": {}, + "init_outputs": { + "path": "[\"node_A\", \"node_D\", \"node_K\", \"node_M\", \"node_Z\"]", + "cost": "384756" + } + }, + "crypto_rsa_decrypt_hex": { + "init_inputs": { + "n": "938475610293847561029384756102", + "d": "485729103847562910293847561029" + }, + "init_outputs": {} + }, + "zip_unzip_file": { + "init_inputs": {}, + "init_outputs": { + "files": "extracted_data_1.bin" + } + }, + "calc_inv_mod": { + "init_inputs": { + "a": "102938475610293847561029384756" + }, + "init_outputs": {} + }, + "zip_unzip_file_bff1": { + "init_inputs": { + "password": "SecurePa$$w0rd123!" + }, + "init_outputs": { + "files": "archive_payload_bff1.zip" + } + }, + "zlib_deflate": { + "init_inputs": { + "text": "Data payload intended for deflation algorithm compression." + }, + "init_outputs": {} + }, + "graph_shortest_path_9029": { + "init_inputs": { + "dst": "Target_Node_Omega" + }, + "init_outputs": { + "path": "[\"start\", \"waypoint1\", \"waypoint2\", \"waypoint3\", \"waypoint4\", \"Target_Node_Omega\"]", + "cost": "129485" + } + }, + "terminal_1_9158": { + "init_inputs": { + "slot_a": "Secondary diagnostic input string." + }, + "init_outputs": { + "text_output": "Diagnostic complete, no errors found.", + "hex_output": "deadbeefbaadc0dedeadbeefbaadc0de" + } + }, + "container_2_d2bd": { + "init_inputs": { + "fingerprint_input": "e3b0c44298fc1c149afbf4c8996fb924" + }, + "init_outputs": {} + }, + "text_xor_hex": { + "init_inputs": { + "hex_a": "0123456789abcdef0123456789abcdef", + "hex_b": "fedcba9876543210fedcba9876543210" + }, + "init_outputs": {} + }, + "calc_bigmul": { + "init_inputs": { + "a": "485720192837465019283746592019", + "b": "928374650192837465920192837465" + }, + "init_outputs": {} + }, + "zip_unzip_file_d0b8": { + "init_inputs": { + "zip_id": "encrypted_source_d0b8.zip" + }, + "init_outputs": { + "files": "decrypted_target_d0b8.dat" + } + }, + "checksum_crc32": { + "init_inputs": { + "hex": "48656c6c6f576f726c64" + }, + "init_outputs": {} + }, + "base64_encode": { + "init_inputs": { + "hex": "5365637265744d657373616765" + }, + "init_outputs": {} + }, + "calc_gcd": { + "init_inputs": { + "a": "657483920192837465019283746574", + "b": "102938475657483920192837465019" + }, + "init_outputs": {} + } + }, + "intro_narrative": "The grand airship 'Aethelgard' is plummeting toward the jagged peaks of the Rust Mountains. As the Chief Engineer, you've been locked inside the main engine room by a saboteur. The steam pressure is reaching critical mass, and the automated navigation systems are completely offline. You must repair the complex web of mechanical computers, brass gears, and pneumatic tubes scattered across the room. Your ultimate goal is to reboot the Main Engine Console before the ship crashes into the mountainside. Time is ticking, and the hissing of steam is your only companion.", + "narrative_style": "steampunk" + }, + "nodes": [ + { + "id": "hex_encode", + "name": "Text to Hex Encoder", + "description": "Encode UTF-8 text to hex.", + "type": "Tool", + "template_id": "hex_encode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "\u000bct`\u0016\u0006" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Encoded hex", + "value": "0b6374601606" + } + ], + "narrative": "The Main Engine Console. This is the master control unit for the airship's thrusters. It requires input from the Alignment Filter to initiate the final startup sequence." + }, + { + "id": "text_bidi_sanitize", + "name": "Bidi Sanitizer", + "description": "Strip bidi control chars.", + "type": "Tool", + "template_id": "text_bidi_sanitize", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "\u000bct`\u0016\u0006" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Sanitized text", + "value": "\u000bct`\u0016\u0006" + } + ], + "narrative": "The Alignment Filter. A brass filtration device with rapidly whirring blades. It requires input from the Cogwheel Purifier to process the signals." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "Initialize primary boot sequence." + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "384756" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Terminal 1 sequence activated successfully." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": { + "slot_a": "Initialize primary boot sequence." + }, + "outputs": { + "text_output": "Terminal 1 sequence activated successfully.", + "hex_output": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "narrative": "The Navigation Engine. A massive steam-powered analytical engine that handles flight trajectories. It requires input from the Coordinate Translator." + }, + { + "id": "num_base_convert", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "384756" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "0" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "102938475610293847561029384756" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "384756" + } + ], + "narrative": "The Coordinate Translator. A heavy board of rotating dials and clicking gears. It requires inputs from the Pressure Equalizer, the Route Plotter, and the Inversion Coil." + }, + { + "id": "calc_modexp", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "384756" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "847392817364829103948572" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "1" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "0" + } + ], + "init": { + "inputs": { + "exp": "847392817364829103948572" + }, + "outputs": {} + }, + "narrative": "The Pressure Equalizer. A large brass gauge setup meant to stabilize the boiler. It requires inputs from the Route Plotter and the Reverse Gear Mechanism." + }, + { + "id": "text_bidi_sanitize_a199", + "name": "Bidi Sanitizer", + "description": "Strip bidi control chars.", + "type": "Tool", + "template_id": "text_bidi_sanitize", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "\u000bct`\u0016\u0006" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Sanitized text", + "value": "\u000bct`\u0016\u0006" + } + ], + "narrative": "The Cogwheel Purifier. A spinning centrifuge for refining raw mechanical signals. It requires input from the Brass Cipher Box." + }, + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "extracted_data_1.bin" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "\u000bct`\u0016\u0006" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "\u000bct`\u0016\u0006" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"node_A\", \"node_D\", \"node_K\", \"node_M\", \"node_Z\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "384756" + } + ], + "init": { + "inputs": {}, + "outputs": { + "path": "[\"node_A\", \"node_D\", \"node_K\", \"node_M\", \"node_Z\"]", + "cost": "384756" + } + }, + "narrative": "The Route Plotter. A magnificent mechanical map of the skies. It requires inputs from the Brass Cipher Box, the Steam Valve Decoder, and the Cogwheel Purifier." + }, + { + "id": "crypto_rsa_decrypt_hex", + "name": "RSA Decrypt", + "description": "RSA decrypt (hex cipher) with n,d (decimal).", + "type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "hex_cipher", + "type": "Hex_String", + "description": "Ciphertext (Hex)", + "value": "789c0dc8c11180300804c056ae02abb0911b21ca0c810ce163f7bacf3dd9c4e2eb4981456b880a46164487b32d03f43bcbfa99b872aed2bdff3d3e80f31614" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Modulus n", + "value": "938475610293847561029384756102" + }, + { + "name": "d", + "type": "Big_Int", + "description": "Private exponent d", + "value": "485729103847562910293847561029" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decrypted text", + "value": "\u000bct`\u0016\u0006" + } + ], + "init": { + "inputs": { + "n": "938475610293847561029384756102", + "d": "485729103847562910293847561029" + }, + "outputs": {} + }, + "narrative": "The Brass Cipher Box. A heavy decryption machine with glowing vacuum tubes. It requires input from the Boiler Compressor." + }, + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "archive_payload_bff1.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "[\"start\", \"waypoint1\", \"waypoint2\", \"waypoint3\", \"waypoint4\", \"Target_Node_Omega\"]" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_data_1.bin" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "extracted_data_1.bin" + } + }, + "narrative": "The Steam Valve Decoder. A system of hissing pipes that decodes pressure signals. It requires inputs from the Mechanical Sorter and the Astrolabe Mapper." + }, + { + "id": "calc_inv_mod", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "102938475610293847561029384756" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "384756" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "102938475610293847561029384756" + } + ], + "init": { + "inputs": { + "a": "102938475610293847561029384756" + }, + "outputs": {} + }, + "narrative": "The Inversion Coil. A glowing copper coil wrapped around an iron core. It requires input from the Route Plotter." + }, + { + "id": "zip_unzip_file_bff1", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "decrypted_target_d0b8.dat" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "SecurePa$$w0rd123!" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "archive_payload_bff1.zip" + } + ], + "init": { + "inputs": { + "password": "SecurePa$$w0rd123!" + }, + "outputs": { + "files": "archive_payload_bff1.zip" + } + }, + "narrative": "The Mechanical Sorter. A sorting track for incoming pneumatic tubes. It requires input from the Archive Unsealer." + }, + { + "id": "calc_inv_mod_f41c", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "1" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": 2004290681 + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "1" + } + ], + "narrative": "The Reverse Gear Mechanism. A complex set of inverted cogs and flywheels. It requires inputs from the Ratio Analyzer and the Purity Gauge." + }, + { + "id": "zlib_deflate", + "name": "Zlib Deflate", + "description": "Deflate text to zlib bytes (hex).", + "type": "Tool", + "template_id": "zlib_deflate", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Text to compress", + "value": "Data payload intended for deflation algorithm compression." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Compressed hex", + "value": "789c0dc8c11180300804c056ae02abb0911b21ca0c810ce163f7bacf3dd9c4e2eb4981456b880a46164487b32d03f43bcbfa99b872aed2bdff3d3e80f31614" + } + ], + "init": { + "inputs": { + "text": "Data payload intended for deflation algorithm compression." + }, + "outputs": {} + }, + "narrative": "The Boiler Compressor. A heavy iron compressor directly connected to the main furnace." + }, + { + "id": "container_2", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Hex_String", + "description": "Fingerprint Hash", + "value": "ffffffffffffffffffffffffffffffff" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "The Safe Box. A secure steel lockbox embedded firmly in the reinforced wall. It requires input from the Dual Signal Mixer." + }, + { + "id": "graph_shortest_path_9029", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "decrypted_target_d0b8.dat" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "\u000bct`\u0016\u0006" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Target_Node_Omega" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"start\", \"waypoint1\", \"waypoint2\", \"waypoint3\", \"waypoint4\", \"Target_Node_Omega\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "129485" + } + ], + "init": { + "inputs": { + "dst": "Target_Node_Omega" + }, + "outputs": { + "path": "[\"start\", \"waypoint1\", \"waypoint2\", \"waypoint3\", \"waypoint4\", \"Target_Node_Omega\"]", + "cost": "129485" + } + }, + "narrative": "The Astrolabe Mapper. A celestial tracking globe covered in constellations. It requires inputs from the Cogwheel Purifier and the Archive Unsealer." + }, + { + "id": "terminal_1_9158", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this terminal" + }, + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "Secondary diagnostic input string." + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "1" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Diagnostic complete, no errors found." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "deadbeefbaadc0dedeadbeefbaadc0de" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": { + "slot_a": "Secondary diagnostic input string." + }, + "outputs": { + "text_output": "Diagnostic complete, no errors found.", + "hex_output": "deadbeefbaadc0dedeadbeefbaadc0de" + } + }, + "narrative": "The Auxiliary Terminal. A secondary command station for monitoring aft thrusters. It requires input from the Overdrive Regulator." + }, + { + "id": "container_2_d2bd", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Hex_String", + "description": "Fingerprint Hash", + "value": "e3b0c44298fc1c149afbf4c8996fb924" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "e3b0c44298fc1c149afbf4c8996fb924" + }, + "outputs": {} + }, + "narrative": "The Rusted Lockbox. An old, oxidized iron container sitting forgotten in the corner." + }, + { + "id": "calc_modexp_2606", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "1" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": 2004290681 + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "450930314117079145297835646860339632509724910300987333191835" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "1" + } + ], + "narrative": "The Overdrive Regulator. A complex system of safety valves. It requires inputs from the Gear Multiplier, the Purity Gauge, and the Reverse Gear Mechanism." + }, + { + "id": "text_xor_hex", + "name": "Hex XOR", + "description": "XOR two hex strings.", + "type": "Tool", + "template_id": "text_xor_hex", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex_a", + "type": "Hex_String", + "description": "Hex A", + "value": "0123456789abcdef0123456789abcdef" + }, + { + "name": "hex_b", + "type": "Hex_String", + "description": "Hex B", + "value": "fedcba9876543210fedcba9876543210" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "XOR Result Hex", + "value": "ffffffffffffffffffffffffffffffff" + } + ], + "init": { + "inputs": { + "hex_a": "0123456789abcdef0123456789abcdef", + "hex_b": "fedcba9876543210fedcba9876543210" + }, + "outputs": {} + }, + "narrative": "The Dual Signal Mixer. A control panel with crisscrossing copper wires." + }, + { + "id": "calc_bigmul", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "485720192837465019283746592019" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "928374650192837465920192837465" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "450930314117079145297835646860339632509724910300987333191835" + } + ], + "init": { + "inputs": { + "a": "485720192837465019283746592019", + "b": "928374650192837465920192837465" + }, + "outputs": {} + }, + "narrative": "The Gear Multiplier. A massive interlocking gear assembly that shakes the floor." + }, + { + "id": "zip_unzip_file_d0b8", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "encrypted_source_d0b8.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "U2VjcmV0TWVzc2FnZQ==" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "decrypted_target_d0b8.dat" + } + ], + "init": { + "inputs": { + "zip_id": "encrypted_source_d0b8.zip" + }, + "outputs": { + "files": "decrypted_target_d0b8.dat" + } + }, + "narrative": "The Archive Unsealer. A pneumatic tube station for reading old logs. It requires input from the Copper Wire Transmitter." + }, + { + "id": "checksum_crc32", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "48656c6c6f576f726c64" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "77770c79" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 2004290681 + } + ], + "init": { + "inputs": { + "hex": "48656c6c6f576f726c64" + }, + "outputs": {} + }, + "narrative": "The Purity Gauge. A precise measuring instrument with a single floating needle." + }, + { + "id": "base64_encode", + "name": "Base64 Encoder", + "description": "Encode hex bytes to base64.", + "type": "Tool", + "template_id": "base64_encode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "hex", + "type": "Hex_String", + "description": "Hex bytes", + "value": "5365637265744d657373616765" + } + ], + "outputs": [ + { + "name": "b64", + "type": "Text_Generic", + "description": "Base64 string", + "value": "U2VjcmV0TWVzc2FnZQ==" + } + ], + "init": { + "inputs": { + "hex": "5365637265744d657373616765" + }, + "outputs": {} + }, + "narrative": "The Copper Wire Transmitter. A telegraph-like device hooked up to an array of spark gaps." + }, + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "657483920192837465019283746574" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "102938475657483920192837465019" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "init": { + "inputs": { + "a": "657483920192837465019283746574", + "b": "102938475657483920192837465019" + }, + "outputs": {} + }, + "narrative": "The Ratio Analyzer. A set of delicate balancing scales and calibrated counterweights." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "The Chronometer Dial. A polished silver pocket watch component." + } + ], + "edges": [ + { + "source_id": "text_bidi_sanitize", + "target_id": "hex_encode", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "text" + }, + { + "source_id": "terminal_1", + "target_id": "text_bidi_sanitize", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "trigger_item" + }, + { + "source_id": "num_base_convert", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "slot_b" + }, + { + "source_id": "calc_modexp", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "from_base" + }, + { + "source_id": "text_bidi_sanitize_a199", + "target_id": "text_bidi_sanitize", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "text" + }, + { + "source_id": "graph_shortest_path", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "s" + }, + { + "source_id": "crypto_rsa_decrypt_hex", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "dst" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "base" + }, + { + "source_id": "calc_inv_mod", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "to_base" + }, + { + "source_id": "text_bidi_sanitize_a199", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "src" + }, + { + "source_id": "zip_unzip_file_bff1", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "calc_inv_mod_f41c", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "mod" + }, + { + "source_id": "zlib_deflate", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_cipher" + }, + { + "source_id": "container_2", + "target_id": "zip_unzip_file_bff1", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "mod" + }, + { + "source_id": "graph_shortest_path_9029", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "password" + }, + { + "source_id": "terminal_1_9158", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "trigger_item" + }, + { + "source_id": "container_2_d2bd", + "target_id": "text_bidi_sanitize_a199", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "crypto_rsa_decrypt_hex", + "target_id": "text_bidi_sanitize_a199", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "text" + }, + { + "source_id": "calc_modexp_2606", + "target_id": "terminal_1_9158", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "slot_b" + }, + { + "source_id": "text_xor_hex", + "target_id": "container_2", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "fingerprint_input" + }, + { + "source_id": "calc_bigmul", + "target_id": "calc_modexp_2606", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "mod" + }, + { + "source_id": "text_bidi_sanitize_a199", + "target_id": "graph_shortest_path_9029", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "src" + }, + { + "source_id": "zip_unzip_file_d0b8", + "target_id": "zip_unzip_file_bff1", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp_2606", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "exp" + }, + { + "source_id": "calc_inv_mod_f41c", + "target_id": "calc_modexp_2606", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "base" + }, + { + "source_id": "zip_unzip_file_d0b8", + "target_id": "graph_shortest_path_9029", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "base64_encode", + "target_id": "zip_unzip_file_d0b8", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "password" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_inv_mod_f41c", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "a" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_inv_mod_f41c", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "mod" + }, + { + "source_id": "item_16", + "target_id": "calc_bigmul", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-356c0ae2/solution/solve.sh b/tasks/agentescape-25-skeleton-356c0ae2/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-25-skeleton-356c0ae2/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-25-skeleton-356c0ae2/task.toml b/tasks/agentescape-25-skeleton-356c0ae2/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..82a09bad40154763e1d231738143489680cb97c2 --- /dev/null +++ b/tasks/agentescape-25-skeleton-356c0ae2/task.toml @@ -0,0 +1,38 @@ +schema_version = "1.4" +source = "https://github.com/AGI-Eval-Official/Repo-of-AgentEscapeBench" + +[[artifacts]] +source = "/evidence/final.json" +service = "puzzle" + +[[artifacts]] +source = "/evidence/trace.jsonl" +service = "puzzle" + +[task] +name = "edbeeching/agentescape-25-skeleton-356c0ae2" +version = "0.1.0" + +[metadata] +difficulty = 25 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "8ac574328b1f2a9a54cc8093ee3b4267403e326660a4b478e83102b0ee63537c" +protocol = "harbor-cli-action-budget-v1" +max_actions = 500 + +[agent] +timeout_sec = 1200 + +[environment] +build_timeout_sec = 900 +cpus = 1 +memory_mb = 1024 + +[verifier] +environment_mode = "separate" +timeout_sec = 60 + +[[verifier.collect]] +service = "puzzle" +command = "python -I /app/export.py" +timeout_sec = 15 diff --git a/tasks/agentescape-25-skeleton-356c0ae2/tests/Dockerfile b/tasks/agentescape-25-skeleton-356c0ae2/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-25-skeleton-356c0ae2/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-25-skeleton-356c0ae2/tests/expected.json b/tasks/agentescape-25-skeleton-356c0ae2/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..ec8e74fbc36a02ac1319c50d7109eff8cb2e4b79 --- /dev/null +++ b/tasks/agentescape-25-skeleton-356c0ae2/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "8ac574328b1f2a9a54cc8093ee3b4267403e326660a4b478e83102b0ee63537c", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-356c0ae2/tests/grade.py b/tasks/agentescape-25-skeleton-356c0ae2/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-25-skeleton-356c0ae2/tests/grade.py @@ -0,0 +1,21 @@ +"""Grade only Harbor-collected sidecar evidence in a fresh verifier container.""" + +import json +from pathlib import Path + +expected = json.loads(Path("/tests/expected.json").read_text()) +state = json.loads(Path("/evidence/final.json").read_text()) +assert state["collected_from_live_service"] is True, "Missing trusted service export" +assert state["scenario_sha256"] == expected["scenario_sha256"], ( + "Wrong scenario evidence" +) +assert state["max_actions"] == expected["max_actions"], "Wrong budget" +assert type(state["won"]) is bool +assert 0 <= state["action_count"] <= state["max_actions"] +assert state["termination_reason"] != "infrastructure_error", ( + "Infrastructure failure is not a puzzle failure" +) +assert not state["won"] or state["termination_reason"] == "success" +Path("/logs/verifier").mkdir(parents=True, exist_ok=True) +Path("/logs/verifier/state.json").write_text(json.dumps(state, indent=2)) +Path("/logs/verifier/reward.txt").write_text("1.0\n" if state["won"] else "0.0\n") diff --git a/tasks/agentescape-25-skeleton-356c0ae2/tests/test.sh b/tasks/agentescape-25-skeleton-356c0ae2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-25-skeleton-356c0ae2/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-25-skeleton-3597bfa8/environment/Dockerfile b/tasks/agentescape-25-skeleton-3597bfa8/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3597bfa8/environment/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-25-skeleton-3597bfa8/environment/agent/Dockerfile b/tasks/agentescape-25-skeleton-3597bfa8/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3597bfa8/environment/agent/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-25-skeleton-3597bfa8/environment/agent/cli.py b/tasks/agentescape-25-skeleton-3597bfa8/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-25-skeleton-3597bfa8/environment/agent/cli.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Public agent client; depends only on the Python standard library.""" + +import argparse +import json +import os +import sys +import urllib.error +import urllib.request + + +def main(): + parser = argparse.ArgumentParser(description="Interact with the escape room") + parser.add_argument( + "action", + choices=[ + "observe", + "state", + "investigate", + "tool-call", + "use-item", + "submit-answer", + ], + ) + parser.add_argument("value", nargs="?") + parser.add_argument("--arguments-json", default="{}") + args = parser.parse_args() + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000").rstrip("/") + if args.action in ("observe", "state"): + request = urllib.request.Request( + base + ("/observation" if args.action == "observe" else "/state") + ) + else: + if args.value is None: + parser.error("node ID or answer is required") + payload = {"action": args.action.replace("-", "_")} + if args.action == "submit-answer": + payload["answer"] = args.value + else: + payload["node_id"] = args.value + if args.action in ("tool-call", "use-item"): + payload["arguments"] = json.loads(args.arguments_json) + request = urllib.request.Request( + base + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=30) as response: + print(json.dumps(json.load(response), ensure_ascii=False)) + except (urllib.error.URLError, ValueError) as exc: + print(json.dumps({"ok": False, "error": str(exc)})) + sys.exit(2) + + +if __name__ == "__main__": + main() diff --git a/tasks/agentescape-25-skeleton-3597bfa8/environment/docker-compose.yaml b/tasks/agentescape-25-skeleton-3597bfa8/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9177498b2b6e19fab5d39c0c070c63404cc102c3 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3597bfa8/environment/docker-compose.yaml @@ -0,0 +1,50 @@ +services: + main: + image: agentescapebench-agent:aab05a0a9ddb + build: + context: ./agent + networks: [default, puzzle] + security_opt: [no-new-privileges:true] + depends_on: + puzzle: + condition: service_healthy + puzzle: + image: agentescapebench-puzzle:agentescape-25-skeleton-3597bfa8-aab05a0a9ddb + build: + context: ./puzzle + networks: [puzzle, execution] + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 512m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"] + interval: 1s + timeout: 3s + retries: 30 + depends_on: + worker: + condition: service_healthy + worker: + image: agentescapebench-worker:aab05a0a9ddb + build: + context: ./puzzle + dockerfile: worker.Dockerfile + networks: [execution] + read_only: true + tmpfs: ["/tmp:size=64m,mode=1777"] + cap_drop: [ALL] + cap_add: [SETUID, SETGID, KILL, CHOWN, DAC_OVERRIDE] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 384m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8001/health')"] + interval: 1s + timeout: 3s + retries: 30 +networks: + puzzle: + internal: true + execution: + internal: true diff --git a/tasks/agentescape-25-skeleton-3597bfa8/environment/puzzle/Dockerfile b/tasks/agentescape-25-skeleton-3597bfa8/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3597bfa8/environment/puzzle/Dockerfile @@ -0,0 +1,9 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY upstream /app/upstream +COPY service.py export.py /app/ +COPY scenario.json /private/scenario.json +ENV SCENARIO_PATH=/private/scenario.json EVIDENCE_DIR=/evidence WORKER_URL=http://worker:8001 MAX_ACTIONS=500 +CMD ["uvicorn", "service:create_app", "--factory", "--host", "0.0.0.0", "--port", "8000", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-25-skeleton-3597bfa8/environment/puzzle/child.py b/tasks/agentescape-25-skeleton-3597bfa8/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3597bfa8/environment/puzzle/child.py @@ -0,0 +1,59 @@ +"""Run the original Python tool after reducing privileges and blocking networking.""" + +import ctypes +import errno +import json +import resource +import sys + +resource.setrlimit(resource.RLIMIT_CPU, (3, 3)) +resource.setrlimit(resource.RLIMIT_AS, (256 * 1024 * 1024, 256 * 1024 * 1024)) +resource.setrlimit(resource.RLIMIT_FSIZE, (65536, 65536)) +resource.setrlimit(resource.RLIMIT_NOFILE, (32, 32)) +resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + +# Filters survive fork/exec. Fail closed if seccomp cannot be loaded. +lib = ctypes.CDLL("libseccomp.so.2", use_errno=True) +lib.seccomp_init.argtypes = [ctypes.c_uint32] +lib.seccomp_init.restype = ctypes.c_void_p +lib.seccomp_rule_add.argtypes = [ + ctypes.c_void_p, + ctypes.c_uint32, + ctypes.c_int, + ctypes.c_uint, +] +lib.seccomp_syscall_resolve_name.argtypes = [ctypes.c_char_p] +lib.seccomp_load.argtypes = [ctypes.c_void_p] +lib.seccomp_release.argtypes = [ctypes.c_void_p] +ctx = lib.seccomp_init(0x7FFF0000) # SCMP_ACT_ALLOW +if not ctx: + raise RuntimeError("Cannot initialize execution isolation") +try: + for name in ( + "socket", + "socketpair", + "connect", + "ptrace", + "process_vm_readv", + "process_vm_writev", + "mount", + "unshare", + "setns", + "bpf", + ): + number = lib.seccomp_syscall_resolve_name(name.encode()) + if ( + number >= 0 + and lib.seccomp_rule_add(ctx, 0x00050000 | errno.EPERM, number, 0) != 0 + ): + raise RuntimeError("Cannot install execution isolation rule") + if lib.seccomp_load(ctx) != 0: + raise RuntimeError("Cannot activate execution isolation") +finally: + lib.seccomp_release(ctx) + +sys.path.insert(0, "/app") +from simulator import ToolSimulator # noqa: E402 + +request = json.load(sys.stdin) +json.dump(ToolSimulator().code_py_exec(request), sys.stdout) diff --git a/tasks/agentescape-25-skeleton-3597bfa8/environment/puzzle/export.py b/tasks/agentescape-25-skeleton-3597bfa8/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3597bfa8/environment/puzzle/export.py @@ -0,0 +1,13 @@ +"""Harbor invokes this inside the puzzle service after stopping the agent.""" + +import json +import pathlib +import urllib.request + +with urllib.request.urlopen("http://127.0.0.1:8000/state", timeout=10) as response: + state = json.load(response) +state["collected_from_live_service"] = True +target = pathlib.Path("/evidence/final.json") +temp = target.with_suffix(".tmp") +temp.write_text(json.dumps(state)) +temp.replace(target) diff --git a/tasks/agentescape-25-skeleton-3597bfa8/environment/puzzle/requirements.txt b/tasks/agentescape-25-skeleton-3597bfa8/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3597bfa8/environment/puzzle/requirements.txt @@ -0,0 +1,57 @@ +annotated-doc==0.0.5 + # via fastapi +annotated-types==0.8.0 + # via pydantic +anyio==4.16.0 + # via starlette +certifi==2026.10.23 + # via requests +cffi==2.1.1 ; platform_python_implementation != 'PyPy' + # via cryptography +charset-normalizer==3.5.2 + # via requests +click==8.5.0 + # via uvicorn +cryptography==50.0.2 + # via agentescapebench-harbor +fastapi==0.162.0 + # via agentescapebench-harbor +h11==0.16.0 + # via uvicorn +idna==3.20 + # via + # anyio + # requests +opentelemetry-api==1.45.2 + # via fastapi +pycparser==3.12 ; implementation_name != 'PyPy' and platform_python_implementation != 'PyPy' + # via cffi +pydantic==2.14.2 + # via + # agentescapebench-harbor + # fastapi +pydantic-core==2.50.2 + # via pydantic +pytz==2025.2 + # via agentescapebench-harbor +requests==2.34.2 + # via agentescapebench-harbor +starlette==1.10.0 + # via fastapi +typing-extensions==4.16.0 + # via + # anyio + # fastapi + # opentelemetry-api + # pydantic + # pydantic-core + # starlette + # typing-inspection +typing-inspection==0.4.4 + # via + # fastapi + # pydantic +urllib3==2.8.0 + # via requests +uvicorn==0.54.0 + # via agentescapebench-harbor diff --git a/tasks/agentescape-25-skeleton-3597bfa8/environment/puzzle/scenario.json b/tasks/agentescape-25-skeleton-3597bfa8/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..746ab409adfb12c2dd44192f19026b35d8a42aae --- /dev/null +++ b/tasks/agentescape-25-skeleton-3597bfa8/environment/puzzle/scenario.json @@ -0,0 +1,1864 @@ +{ + "metadata": { + "total_nodes": 25, + "total_edges": 30, + "win_node_id": "zip_unzip_item", + "win_condition": { + "type": "tool_output", + "node_id": "zip_unzip_item", + "output_port": "item", + "output_type": "Item", + "description": "Execute Zip Unzipper and get the output from port 'item'" + }, + "source_init": { + "source_nodes": [ + "zip_unzip_item", + "regex_search", + "text_rotN", + "hex_decode", + "zip_unzip_file", + "zip_unzip_file_a989", + "text_bidi_sanitize", + "zip_unzip_file_9915", + "zip_unzip_file_6e53", + "zip_unzip_file_46a0", + "crypto_rsa_decrypt_hex", + "graph_shortest_path", + "terminal_1", + "text_xor_hex", + "terminal_2", + "regex_search_2a22", + "calc_modexp", + "graph_shortest_path_fd8d", + "zip_unzip_file_54e1", + "num_base_convert", + "zip_unzip_file_1e39", + "hex_decode_ab54", + "container_1", + "calc_bigmul" + ], + "by_node": { + "zip_unzip_item": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_item", + "init_inputs": {}, + "init_outputs": { + "item": { + "type": "Item", + "description": "item in the zip" + } + } + }, + "regex_search": { + "node_name": "Regex Search", + "node_type": "Tool", + "template_id": "regex_search", + "init_inputs": {}, + "init_outputs": { + "matches": { + "type": "Text_Generic", + "description": "Found matches (List)" + } + } + }, + "text_rotN": { + "node_name": "ROT-N Cipher", + "node_type": "Tool", + "template_id": "text_rotN", + "init_inputs": { + "n": { + "type": "Big_Int", + "description": "Shift N" + } + }, + "init_outputs": {} + }, + "hex_decode": { + "node_name": "Hex to Text Decoder", + "node_type": "Tool", + "template_id": "hex_decode", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex string" + } + }, + "init_outputs": {} + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "zip_unzip_file_a989": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "text_bidi_sanitize": { + "node_name": "Bidi Sanitizer", + "node_type": "Tool", + "template_id": "text_bidi_sanitize", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text" + } + }, + "init_outputs": {} + }, + "zip_unzip_file_9915": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "zip_unzip_file_6e53": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "zip_unzip_file_46a0": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "crypto_rsa_decrypt_hex": { + "node_name": "RSA Decrypt", + "node_type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "init_inputs": { + "d": { + "type": "Big_Int", + "description": "Private exponent d" + } + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "Graph JSON file ID" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": {}, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + } + } + }, + "text_xor_hex": { + "node_name": "Hex XOR", + "node_type": "Tool", + "template_id": "text_xor_hex", + "init_inputs": { + "hex_a": { + "type": "Hex_String", + "description": "Hex A" + } + }, + "init_outputs": {} + }, + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": { + "num1": { + "type": "Big_Int", + "description": "First Number" + } + }, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + } + } + }, + "regex_search_2a22": { + "node_name": "Regex Search", + "node_type": "Tool", + "template_id": "regex_search", + "init_inputs": { + "pattern": { + "type": "Text_Generic", + "description": "Regex pattern" + } + }, + "init_outputs": { + "matches": { + "type": "Text_Generic", + "description": "Found matches (List)" + } + } + }, + "calc_modexp": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "base": { + "type": "Big_Int", + "description": "Base" + }, + "exp": { + "type": "Big_Int", + "description": "Exponent" + }, + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "graph_shortest_path_fd8d": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "Graph JSON file ID" + }, + "src": { + "type": "Text_Generic", + "description": "Source node" + }, + "dst": { + "type": "Text_Generic", + "description": "Destination node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "zip_unzip_file_54e1": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + }, + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "num_base_convert": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "to_base": { + "type": "Big_Int", + "description": "To base" + } + }, + "init_outputs": {} + }, + "zip_unzip_file_1e39": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + }, + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "hex_decode_ab54": { + "node_name": "Hex to Text Decoder", + "node_type": "Tool", + "template_id": "hex_decode", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex string" + } + }, + "init_outputs": {} + }, + "container_1": { + "node_name": "", + "node_type": "Item", + "template_id": "container_1", + "init_inputs": { + "fingerprint_input": { + "type": "Hex_String", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + }, + "calc_bigmul": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First large integer" + }, + "b": { + "type": "Big_Int", + "description": "Second large integer" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "zip_unzip_item": { + "init_inputs": {}, + "init_outputs": { + "item": "Blue, Yellow, Black, Green, Red — any five interlocking rings" + } + }, + "regex_search": { + "init_inputs": {}, + "init_outputs": { + "matches": "[\"pattern_01\", \"pattern_02\", \"pattern_03\", \"pattern_04\", \"pattern_05\"]" + } + }, + "text_rotN": { + "init_inputs": { + "n": "84729485729384758291" + }, + "init_outputs": {} + }, + "hex_decode": { + "init_inputs": { + "hex": "48656c6c6f20576f726c642066726f6d20686578206465636f6465" + }, + "init_outputs": {} + }, + "zip_unzip_file": { + "init_inputs": {}, + "init_outputs": { + "files": "extracted_data_1.zip" + } + }, + "zip_unzip_file_a989": { + "init_inputs": {}, + "init_outputs": { + "files": "extracted_data_2.zip" + } + }, + "text_bidi_sanitize": { + "init_inputs": { + "text": "Text containing ‮ right-to-left ‬ override characters." + }, + "init_outputs": {} + }, + "zip_unzip_file_9915": { + "init_inputs": { + "password": "secure_password_9915" + }, + "init_outputs": { + "files": "extracted_data_3.zip" + } + }, + "zip_unzip_file_6e53": { + "init_inputs": {}, + "init_outputs": { + "files": "extracted_data_4.zip" + } + }, + "zip_unzip_file_46a0": { + "init_inputs": { + "password": "secure_password_46a0" + }, + "init_outputs": { + "files": "extracted_data_5.zip" + } + }, + "crypto_rsa_decrypt_hex": { + "init_inputs": { + "d": "4982734982739485729384759283749283749283" + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": { + "file_id": "graph_network.json" + }, + "init_outputs": { + "path": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\"]", + "cost": "458391" + } + }, + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "Terminal one execution completed successfully with data.", + "hex_output": "deadbeefcafebabe1234567890abcdef" + } + }, + "text_xor_hex": { + "init_inputs": { + "hex_a": "112233445566778899aabbccddeeff00" + }, + "init_outputs": {} + }, + "terminal_2": { + "init_inputs": { + "num1": "192837465019283746501928" + }, + "init_outputs": { + "text_result": "Terminal two partial computation result generated successfully.", + "hex_result": "abcdef1234567890abcdef1234567890" + } + }, + "regex_search_2a22": { + "init_inputs": { + "pattern": "[A-Z0-9]{16}" + }, + "init_outputs": { + "matches": "[\"result_A1\", \"result_B2\", \"result_C3\", \"result_D4\", \"result_E5\"]" + } + }, + "calc_modexp": { + "init_inputs": { + "base": "17", + "exp": "938475829384758293847", + "mod": "999983" + }, + "init_outputs": {} + }, + "graph_shortest_path_fd8d": { + "init_inputs": { + "file_id": "city_routes.json", + "src": "City_Origin", + "dst": "City_Destination" + }, + "init_outputs": { + "path": "[\"City_Origin\", \"City_A\", \"City_B\", \"City_C\", \"City_Destination\"]", + "cost": "105938" + } + }, + "zip_unzip_file_54e1": { + "init_inputs": { + "zip_id": "archive_54e1.zip", + "password": "pass_54e1_secure" + }, + "init_outputs": { + "files": "extracted_data_6.zip" + } + }, + "num_base_convert": { + "init_inputs": { + "to_base": "10" + }, + "init_outputs": {} + }, + "zip_unzip_file_1e39": { + "init_inputs": { + "zip_id": "archive_1e39.zip", + "password": "pass_1e39_secure" + }, + "init_outputs": { + "files": "extracted_data_7.zip" + } + }, + "hex_decode_ab54": { + "init_inputs": { + "hex": "536563726574204d6573736167652031" + }, + "init_outputs": {} + }, + "container_1": { + "init_inputs": { + "fingerprint_input": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + }, + "init_outputs": {} + }, + "calc_bigmul": { + "init_inputs": { + "a": "485729384758293847582938", + "b": "938475829384758293847582" + }, + "init_outputs": {} + } + }, + "intro_narrative": "The neon lights of the city flicker through the blinds of your dimly lit detective agency. A notorious cyber-syndicate has been operating in the shadows, leaving behind a trail of encrypted files, locked terminals, and fragmented evidence. You've managed to intercept a massive cache of their digital tools and data, but everything is heavily interconnected and protected. The police are relying on you to piece together the evidence before the syndicate's leader skips town. Your primary objective is to unlock the final evidence locker, which holds the definitive proof needed to put them away for good. To do this, you must carefully examine each piece of software and hardware in your office. Trace the data trails, decrypt the hidden messages, and figure out how these devices feed into one another. Time is ticking, and the syndicate's servers are programmed to wipe themselves by dawn. You need to focus, use your deductive skills, and uncover the truth hidden within the code.", + "narrative_style": "detective" + }, + "nodes": [ + { + "id": "zip_unzip_item", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_item", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "extracted_data_4.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "[\"pattern_01\", \"pattern_02\", \"pattern_03\", \"pattern_04\", \"pattern_05\"]" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip", + "value": "Blue, Yellow, Black, Green, Red — any five interlocking rings" + } + ], + "init": { + "inputs": {}, + "outputs": { + "item": "Blue, Yellow, Black, Green, Red — any five interlocking rings" + } + }, + "narrative": "This is the final evidence locker. It requires inputs from the suspect database and the surveillance archive." + }, + { + "id": "regex_search", + "name": "Regex Search", + "description": "Search regex in either raw text or a file.", + "type": "Tool", + "template_id": "regex_search", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "pattern", + "type": "Text_Generic", + "description": "Regex pattern", + "value": "\u0001" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "File ID (optional)", + "value": "extracted_data_1.zip" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text (optional)", + "value": "Khoor Zruog iurp kha ghfrgh" + } + ], + "outputs": [ + { + "name": "matches", + "type": "Text_Generic", + "description": "Found matches (List)", + "value": "[\"pattern_01\", \"pattern_02\", \"pattern_03\", \"pattern_04\", \"pattern_05\"]" + } + ], + "init": { + "inputs": {}, + "outputs": { + "matches": "[\"pattern_01\", \"pattern_02\", \"pattern_03\", \"pattern_04\", \"pattern_05\"]" + } + }, + "narrative": "This is the suspect database. It requires inputs from the anagram cipher tool, the corrupted archive, and the advanced decryption module." + }, + { + "id": "text_rotN", + "name": "ROT-N Cipher", + "description": "Caesar shift by N.", + "type": "Tool", + "template_id": "text_rotN", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "Hello World from hex decode" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Shift N", + "value": "84729485729384758291" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Rotated text", + "value": "Khoor Zruog iurp kha ghfrgh" + } + ], + "init": { + "inputs": { + "n": "84729485729384758291" + }, + "outputs": {} + }, + "narrative": "This is the anagram cipher tool. It requires input from the raw memory dump." + }, + { + "id": "hex_decode", + "name": "Hex to Text Decoder", + "description": "Decode hex to UTF-8 text.", + "type": "Tool", + "template_id": "hex_decode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex string", + "value": "48656c6c6f20576f726c642066726f6d20686578206465636f6465" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decoded text", + "value": "Hello World from hex decode" + } + ], + "init": { + "inputs": { + "hex": "48656c6c6f20576f726c642066726f6d20686578206465636f6465" + }, + "outputs": {} + }, + "narrative": "A raw memory dump file extracted directly from a suspect's laptop." + }, + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "extracted_data_2.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Text containing right-to-left override characters." + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_data_1.zip" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "extracted_data_1.zip" + } + }, + "narrative": "This is the corrupted archive. It requires inputs from the blackmail folder and the text cleaner program." + }, + { + "id": "zip_unzip_file_a989", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "extracted_data_3.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "[\"City_Origin\", \"City_A\", \"City_B\", \"City_C\", \"City_Destination\"]" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_data_2.zip" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "extracted_data_2.zip" + } + }, + "narrative": "This is the blackmail folder. It requires inputs from the financial records and the map navigation system." + }, + { + "id": "text_bidi_sanitize", + "name": "Bidi Sanitizer", + "description": "Strip bidi control chars.", + "type": "Tool", + "template_id": "text_bidi_sanitize", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "Text containing ‮ right-to-left ‬ override characters." + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Sanitized text", + "value": "Text containing right-to-left override characters." + } + ], + "init": { + "inputs": { + "text": "Text containing ‮ right-to-left ‬ override characters." + }, + "outputs": {} + }, + "narrative": "A text cleaner program used by the forensics lab to strip out invisible control characters." + }, + { + "id": "zip_unzip_file_9915", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "extracted_data_5.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "secure_password_9915" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_data_3.zip" + } + ], + "init": { + "inputs": { + "password": "secure_password_9915" + }, + "outputs": { + "files": "extracted_data_3.zip" + } + }, + "narrative": "This is the financial records. It requires input from the burner phone backup." + }, + { + "id": "zip_unzip_file_6e53", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "extracted_data_6.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Text containing right-to-left override characters." + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_data_4.zip" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "extracted_data_4.zip" + } + }, + "narrative": "This is the surveillance archive. It requires inputs from the text cleaner program and the interrogation records." + }, + { + "id": "zip_unzip_file_46a0", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "extracted_data_7.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "secure_password_46a0" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_data_5.zip" + } + ], + "init": { + "inputs": { + "password": "secure_password_46a0" + }, + "outputs": { + "files": "extracted_data_5.zip" + } + }, + "narrative": "This is the burner phone backup. It requires input from the initial crime scene file." + }, + { + "id": "crypto_rsa_decrypt_hex", + "name": "RSA Decrypt", + "description": "RSA decrypt (hex cipher) with n,d (decimal).", + "type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "hex_cipher", + "type": "Hex_String", + "description": "Ciphertext (Hex)", + "value": "cf8f8dab9f98cd368b9eedb44d4532ef" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Modulus n", + "value": "458391" + }, + { + "name": "d", + "type": "Big_Int", + "description": "Private exponent d", + "value": "4982734982739485729384759283749283749283" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decrypted text", + "value": "\u0001" + } + ], + "init": { + "inputs": { + "d": "4982734982739485729384759283749283749283" + }, + "outputs": {} + }, + "narrative": "This is the advanced decryption module. It requires inputs from the route analyzer and the digital comparator." + }, + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "graph_network.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "[\"result_A1\", \"result_B2\", \"result_C3\", \"result_D4\", \"result_E5\"]" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Secret Message 1" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "458391" + } + ], + "init": { + "inputs": { + "file_id": "graph_network.json" + }, + "outputs": { + "path": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\"]", + "cost": "458391" + } + }, + "narrative": "This is the route analyzer. It requires inputs from the license plate scanner and the GPS log decoder." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "Terminal two partial computation result generated successfully." + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "105938" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Terminal one execution completed successfully with data." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "deadbeefcafebabe1234567890abcdef" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "Terminal one execution completed successfully with data.", + "hex_output": "deadbeefcafebabe1234567890abcdef" + } + }, + "narrative": "This is the mainframe terminal. It requires inputs from the number conversion tool and the accounting terminal." + }, + { + "id": "text_xor_hex", + "name": "Hex XOR", + "description": "XOR two hex strings.", + "type": "Tool", + "template_id": "text_xor_hex", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex_a", + "type": "Hex_String", + "description": "Hex A", + "value": "112233445566778899aabbccddeeff00" + }, + { + "name": "hex_b", + "type": "Hex_String", + "description": "Hex B", + "value": "deadbeefcafebabe1234567890abcdef" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "XOR Result Hex", + "value": "cf8f8dab9f98cd368b9eedb44d4532ef" + } + ], + "init": { + "inputs": { + "hex_a": "112233445566778899aabbccddeeff00" + }, + "outputs": {} + }, + "narrative": "This is the digital comparator. It requires input from the mainframe terminal." + }, + { + "id": "terminal_2", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this terminal" + }, + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "192837465019283746501928" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "252178" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Terminal two partial computation result generated successfully." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "abcdef1234567890abcdef1234567890" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": { + "num1": "192837465019283746501928" + }, + "outputs": { + "text_result": "Terminal two partial computation result generated successfully.", + "hex_result": "abcdef1234567890abcdef1234567890" + } + }, + "narrative": "This is the accounting terminal. It requires input from the cryptographic calculator." + }, + { + "id": "regex_search_2a22", + "name": "Regex Search", + "description": "Search regex in either raw text or a file.", + "type": "Tool", + "template_id": "regex_search", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "pattern", + "type": "Text_Generic", + "description": "Regex pattern", + "value": "[A-Z0-9]{16}" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "File ID (optional)", + "value": "extracted_data_5.zip" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text (optional)", + "value": "[\"City_Origin\", \"City_A\", \"City_B\", \"City_C\", \"City_Destination\"]" + } + ], + "outputs": [ + { + "name": "matches", + "type": "Text_Generic", + "description": "Found matches (List)", + "value": "[\"result_A1\", \"result_B2\", \"result_C3\", \"result_D4\", \"result_E5\"]" + } + ], + "init": { + "inputs": { + "pattern": "[A-Z0-9]{16}" + }, + "outputs": { + "matches": "[\"result_A1\", \"result_B2\", \"result_C3\", \"result_D4\", \"result_E5\"]" + } + }, + "narrative": "This is the license plate scanner. It requires inputs from the map navigation system and the burner phone backup." + }, + { + "id": "calc_modexp", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "17" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "938475829384758293847" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "999983" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "252178" + } + ], + "init": { + "inputs": { + "base": "17", + "exp": "938475829384758293847", + "mod": "999983" + }, + "outputs": {} + }, + "narrative": "A cryptographic calculator found on the suspect's desk, designed for complex math." + }, + { + "id": "graph_shortest_path_fd8d", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "city_routes.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "City_Origin" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "City_Destination" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"City_Origin\", \"City_A\", \"City_B\", \"City_C\", \"City_Destination\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "105938" + } + ], + "init": { + "inputs": { + "file_id": "city_routes.json", + "src": "City_Origin", + "dst": "City_Destination" + }, + "outputs": { + "path": "[\"City_Origin\", \"City_A\", \"City_B\", \"City_C\", \"City_Destination\"]", + "cost": "105938" + } + }, + "narrative": "A map navigation system used by the local cab company to track all vehicle routes." + }, + { + "id": "zip_unzip_file_54e1", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "archive_54e1.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "pass_54e1_secure" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_data_6.zip" + } + ], + "init": { + "inputs": { + "zip_id": "archive_54e1.zip", + "password": "pass_54e1_secure" + }, + "outputs": { + "files": "extracted_data_6.zip" + } + }, + "narrative": "The interrogation records from the precinct's secure server, locked in a digital vault." + }, + { + "id": "num_base_convert", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "105938" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "455845287217588192587234227586219616726875755916" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "10" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "105938" + } + ], + "init": { + "inputs": { + "to_base": "10" + }, + "outputs": {} + }, + "narrative": "This is the number conversion tool. It requires inputs from the map navigation system and the forensic multiplier." + }, + { + "id": "zip_unzip_file_1e39", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "archive_1e39.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "pass_1e39_secure" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_data_7.zip" + } + ], + "init": { + "inputs": { + "zip_id": "archive_1e39.zip", + "password": "pass_1e39_secure" + }, + "outputs": { + "files": "extracted_data_7.zip" + } + }, + "narrative": "The initial crime scene file, containing the first responder's digital report." + }, + { + "id": "hex_decode_ab54", + "name": "Hex to Text Decoder", + "description": "Decode hex to UTF-8 text.", + "type": "Tool", + "template_id": "hex_decode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex string", + "value": "536563726574204d6573736167652031" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decoded text", + "value": "Secret Message 1" + } + ], + "init": { + "inputs": { + "hex": "536563726574204d6573736167652031" + }, + "outputs": {} + }, + "narrative": "A GPS log decoder utility designed to translate cryptic location data." + }, + { + "id": "container_1", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + }, + { + "name": "fingerprint_input", + "type": "Hex_String", + "description": "Fingerprint Hash", + "value": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + }, + "outputs": {} + }, + "narrative": "The detective's briefcase, secured with a heavy-duty biometric lock mechanism." + }, + { + "id": "calc_bigmul", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "485729384758293847582938" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "938475829384758293847582" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "455845287217588192587234227586219616726875755916" + } + ], + "init": { + "inputs": { + "a": "485729384758293847582938", + "b": "938475829384758293847582" + }, + "outputs": {} + }, + "narrative": "A forensic multiplier used specifically for processing extremely large numeric variables." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A forgotten evidence bag covered in dust, sitting quietly in the corner of the room." + } + ], + "edges": [ + { + "source_id": "regex_search", + "target_id": "zip_unzip_item", + "connection_type": "Text_Generic", + "source_port": "matches", + "target_port": "password" + }, + { + "source_id": "text_rotN", + "target_id": "regex_search", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "text" + }, + { + "source_id": "hex_decode", + "target_id": "text_rotN", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "text" + }, + { + "source_id": "zip_unzip_file", + "target_id": "regex_search", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "zip_unzip_file_a989", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "text_bidi_sanitize", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "password" + }, + { + "source_id": "zip_unzip_file_9915", + "target_id": "zip_unzip_file_a989", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "zip_unzip_file_6e53", + "target_id": "zip_unzip_item", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "zip_unzip_file_46a0", + "target_id": "zip_unzip_file_9915", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "crypto_rsa_decrypt_hex", + "target_id": "regex_search", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "pattern" + }, + { + "source_id": "graph_shortest_path", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "n" + }, + { + "source_id": "text_bidi_sanitize", + "target_id": "zip_unzip_file_6e53", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "password" + }, + { + "source_id": "terminal_1", + "target_id": "regex_search", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "trigger_item" + }, + { + "source_id": "text_xor_hex", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_cipher" + }, + { + "source_id": "terminal_2", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "trigger_item" + }, + { + "source_id": "terminal_1", + "target_id": "text_xor_hex", + "connection_type": "Hex_String", + "source_port": "hex_output", + "target_port": "hex_b" + }, + { + "source_id": "regex_search_2a22", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "matches", + "target_port": "src" + }, + { + "source_id": "calc_modexp", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "num2" + }, + { + "source_id": "graph_shortest_path_fd8d", + "target_id": "regex_search_2a22", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "text" + }, + { + "source_id": "zip_unzip_file_54e1", + "target_id": "zip_unzip_file_6e53", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "graph_shortest_path_fd8d", + "target_id": "zip_unzip_file_a989", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "password" + }, + { + "source_id": "num_base_convert", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "slot_b" + }, + { + "source_id": "zip_unzip_file_1e39", + "target_id": "zip_unzip_file_46a0", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "graph_shortest_path_fd8d", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "s" + }, + { + "source_id": "terminal_2", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "slot_a" + }, + { + "source_id": "hex_decode_ab54", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "dst" + }, + { + "source_id": "zip_unzip_file_46a0", + "target_id": "regex_search_2a22", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "container_1", + "target_id": "zip_unzip_file_46a0", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "calc_bigmul", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "from_base" + }, + { + "source_id": "item_16", + "target_id": "zip_unzip_file_54e1", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-3597bfa8/environment/puzzle/service.py b/tasks/agentescape-25-skeleton-3597bfa8/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-25-skeleton-3597bfa8/environment/puzzle/service.py @@ -0,0 +1,212 @@ +"""Restricted facade over the unchanged, pinned upstream puzzle handlers.""" + +import hashlib +import json +import logging +import os +import sys +import threading +import urllib.request +import uuid +from pathlib import Path + +from fastapi import FastAPI, HTTPException +from fastapi.responses import JSONResponse +from pydantic import BaseModel, ConfigDict + +sys.path.insert(0, str(Path(__file__).parent / "upstream")) +import server as upstream # noqa: E402 + +log = logging.getLogger(__name__) + + +def public(value): + """Keep upstream agent-internal template hints out of the public response.""" + if isinstance(value, dict): + return {k: public(v) for k, v in value.items() if not k.startswith("_")} + if isinstance(value, list): + return [public(v) for v in value] + return value + + +class Action(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + action: str + node_id: str | None = None + arguments: dict | None = None + answer: str | None = None + + +class Episode: + def __init__( + self, scenario_path, max_actions=500, evidence_dir=None, worker_url=None + ): + if max_actions < 1: + raise ValueError("max_actions must be positive") + self.lock = threading.Lock() + self.max_actions = max_actions + self.count = 0 + self.won = False + self.reason = None + self.evidence_dir = Path(evidence_dir) if evidence_dir else None + self.scenario_hash = hashlib.sha256( + Path(scenario_path).read_bytes() + ).hexdigest() + self.initial = upstream.reset_case( + case_file_path=str(scenario_path), session_id=uuid.uuid4().hex + ) + self.case_id = self.initial["case_id"] + # Hide source file paths; no upstream reset/stats/routes are mounted. + self.initial.pop("message", None) + simulator = upstream.SIMULATORS[self.case_id] + if worker_url is None: + + def no_worker(_inputs): + self.reason = "infrastructure_error" + raise RuntimeError("isolated Python worker is not configured") + + simulator.tool_map["code_py_exec"] = no_worker + else: + + def execute_python(inputs): + request = urllib.request.Request( + worker_url + "/execute", + data=json.dumps({"code": inputs.get("code", "")}).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=12) as response: + result = json.load(response) + if not isinstance(result.get("stdout"), str): + raise RuntimeError("Invalid Python worker response") + return result + except Exception: + self.reason = "infrastructure_error" + raise + + simulator.tool_map["code_py_exec"] = execute_python + self.save() + if self.evidence_dir is not None: + (self.evidence_dir / "trace.jsonl").touch() + + def state(self): + return { + "scenario_sha256": self.scenario_hash, + "action_count": self.count, + "max_actions": self.max_actions, + "won": self.won, + "termination_reason": self.reason, + } + + def save(self, action=None, result=None): + if self.evidence_dir is None: + return + self.evidence_dir.mkdir(parents=True, exist_ok=True) + target = self.evidence_dir / "outcome.json" + temp = target.with_suffix(".tmp") + temp.write_text(json.dumps(self.state())) + temp.replace(target) + if action is not None: + with (self.evidence_dir / "trace.jsonl").open("a") as handle: + handle.write( + json.dumps( + {"index": self.count, "action": action, "result": result} + ) + + "\n" + ) + + def dispatch(self, payload): + with self.lock: + if self.reason is not None: + return { + "ok": False, + "error": "Episode has ended", + "episode": self.state(), + } + self.count += 1 + try: + action = Action.model_validate(payload) + if action.action == "submit_answer" and action.answer is not None: + result = upstream.submit_answer( + self.case_id, upstream.SubmitAnswerRequest(answer=action.answer) + ) + if result.get("is_win"): + self.won = True + self.reason = "success" + elif action.action == "investigate" and action.node_id is not None: + result = upstream.investigate( + self.case_id, + upstream.InvestigateRequest(node_id=action.node_id), + ) + elif ( + action.action in ("tool_call", "use_item") + and action.node_id is not None + ): + request_type, handler = ( + (upstream.ToolCallRequest, upstream.tool_call) + if action.action == "tool_call" + else (upstream.UseItemRequest, upstream.use_item) + ) + result = handler( + self.case_id, + request_type( + node_id=action.node_id, arguments=action.arguments or {} + ), + ) + else: + result = { + "ok": False, + "error": "Unknown action or missing action parameter", + } + except HTTPException as exc: + result = {"ok": False, "error": exc.detail} + except ValueError: + result = {"ok": False, "error": "Malformed action"} + except Exception: + log.exception("Puzzle service failure") + self.reason = "infrastructure_error" + self.save() + raise + if self.reason is None and self.count >= self.max_actions: + self.reason = "action_budget_exhausted" + result = public(result) + result["episode"] = self.state() + self.save(payload, result) + return result + + +def create_app( + scenario_path=None, max_actions=None, evidence_dir=None, worker_url=None +): + episode = Episode( + scenario_path or os.environ["SCENARIO_PATH"], + max_actions or int(os.environ.get("MAX_ACTIONS", "500")), + evidence_dir if evidence_dir is not None else os.environ.get("EVIDENCE_DIR"), + worker_url if worker_url is not None else os.environ.get("WORKER_URL"), + ) + app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) + app.state.episode = episode + + @app.get("/health") + def health(): + return {"ok": True} + + @app.get("/observation") + def observation(): + return {**public(episode.initial), "episode": episode.state()} + + @app.get("/state") + def state(): + return episode.state() + + @app.post("/action") + def action(payload: dict): + try: + return episode.dispatch(payload) + except Exception: + return JSONResponse( + status_code=503, + content={"ok": False, "error": "Puzzle infrastructure failure"}, + ) + + return app diff --git a/tasks/agentescape-25-skeleton-3597bfa8/environment/puzzle/upstream/models.py b/tasks/agentescape-25-skeleton-3597bfa8/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3597bfa8/environment/puzzle/upstream/models.py @@ -0,0 +1,108 @@ +from enum import Enum +from typing import List, Dict, Any, Optional +from pydantic import BaseModel, Field + +# 1. 细粒度接口类型定义 +class InterfaceType(str, Enum): + ''' + BIG_INT + TEXT_GENERIC + HEX_STRING + FILE_ID + HEX_STRING_KEY_AES + HEX_STRING_IV_AES + CODE_PYTHON + HIDDEN_ITEM + ITEM + ''' + # --- 基础类型 --- + TEXT_GENERIC = "Text_Generic" + BIG_INT = "Big_Int" + + # --- 编码/格式化字符串 --- + HEX_STRING = "Hex_String" # 通用 Hex + + # --- 特定用途的 Hex 字符串 (用于精确匹配) --- + HEX_STRING_KEY_AES = "Hex_String_Key_AES" + HEX_STRING_IV_AES = "Hex_String_IV_AES" + + # --- 文件类型 --- + FILE_ID = "File_Id" + + # --- 代码/脚本 --- + CODE_PYTHON = "Code_Python" + + # --- 实体交互类型 (严格命名) --- + ITEM = "Item" # 主动掉落接口 (Tool -> Item) + HIDDEN_ITEM = "Hidden_Item" # 被动掉落接口 (Item -> Item) + +# 3. 端口定义 +class Port(BaseModel): + name: str + type: InterfaceType + description: str + +# 4. 统一节点定义 (融合工具和物品) +class Node(BaseModel): + id: str + name: str + description: str + type: str # "Tool" or "Item" + + # 接口定义 + inputs: List[Port] = [] + outputs: List[Port] = [] + + # 状态字段 + content: Optional[Any] = None # 物品有内容,工具为None + if_success: Optional[bool] = None # 工具初始为False,物品为None + initial_visible: bool = False + + # 运行时状态 (Server维护) + is_revealed: bool = False + + # 标记该 Tool 节点是否有待触发的 HIDDEN_ITEM 掉落 + # 当 Tool 按照 golden_input 正确执行且有 HIDDEN_ITEM 输出边时设为 True + # 在 investigate 该 Tool 时触发掉落并重置为 False + has_hidden_item_ready: bool = False + + # 初始输入值 (metadata.initial_values.init_inputs,用于渐进式暴露判断) + init_input_values: Dict[str, Any] = {} + + # Golden 输入值 (nodes[].inputs[].value,用于评测验证) + golden_input_values: Dict[str, Any] = {} + + # Golden 输出值 (nodes[].outputs[].value,用于评测验证和 Item 节点的 content) + golden_output_values: Dict[str, Any] = {} + + # 实际获得的输出值历史 (工具每次执行后实际返回的输出列表,用于渐进式暴露判断) + # 格式: List[Dict[str, Any]],每个元素是一次执行的输出字典 + actual_outputs_history: List[Dict[str, Any]] = [] + + # 逻辑规则 (用于终端机等复杂物品) + logic_rules: Optional[Dict[str, Any]] = None + + def copy(self, **kwargs): + """Helper to create a copy with updated fields.""" + data = self.dict() + data.update(kwargs) + return Node(**data) + +# 5. 边定义 (拓扑结构) +class Edge(BaseModel): + source_id: str + target_id: str + connection_type: InterfaceType # 直接使用 InterfaceType + # 如果是 Data_Flow,指定端口对应关系 + source_port: Optional[str] = None + target_port: Optional[str] = None + +# 6. 完整图定义 +class GraphScenario(BaseModel): + case_id: str + title: str + intro_narrative: str + nodes: Dict[str, Node] + edges: List[Edge] + difficulty: int + win_node_id: str # 标记哪个节点是最终目标(通常是一个提交工具或最终物品) diff --git a/tasks/agentescape-25-skeleton-3597bfa8/environment/puzzle/upstream/server.py b/tasks/agentescape-25-skeleton-3597bfa8/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-25-skeleton-3597bfa8/environment/puzzle/upstream/server.py @@ -0,0 +1,1490 @@ +import json +import os +import time +import logging +import random +from pathlib import Path +from typing import Dict, Any, List, Optional +from datetime import datetime +from collections import defaultdict +from fastapi import FastAPI, HTTPException, Request +from fastapi.responses import JSONResponse +from fastapi.middleware.cors import CORSMiddleware +from pydantic import BaseModel, Field + +from models import GraphScenario, Node, InterfaceType +# from generator import ScenarioGenerator +from simulator import ToolSimulator +import uvicorn + +# 配置日志 +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler('server.log'), + logging.StreamHandler() + ] +) +logger = logging.getLogger(__name__) + +app = FastAPI( + title="AgentEscapeBench Universal Server", + version="1.0.0", + description="Industrial-grade evaluation server for escape room AI agents" +) + +# 添加 CORS 支持 +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# In-memory State +SCENARIOS: Dict[str, GraphScenario] = {} +SIMULATORS: Dict[str, ToolSimulator] = {} # case_id -> ToolSimulator +RAW_NODES_DATA: Dict[str, Dict[str, Any]] = {} # case_id -> node_id -> raw node data (for template_id) +FILE_METADATA: Dict[str, Dict[str, Any]] = {} # case_id -> metadata (for initial_values access) + +# Performance monitoring +STATS: Dict[str, Any] = { + "total_requests": 0, + "successful_requests": 0, + "failed_requests": 0, + "tool_calls": defaultdict(int), + "investigates": defaultdict(int), + "use_items": defaultdict(int), + "case_loads": 0, + "start_time": datetime.now() +} + +# Request timing middleware +@app.middleware("http") +async def add_process_time_header(request: Request, call_next): + start_time = time.time() + STATS["total_requests"] += 1 + + try: + response = await call_next(request) + STATS["successful_requests"] += 1 + process_time = time.time() - start_time + response.headers["X-Process-Time"] = str(process_time) + logger.info(f"{request.method} {request.url.path} - {response.status_code} - {process_time:.3f}s") + return response + except Exception as e: + STATS["failed_requests"] += 1 + logger.error(f"{request.method} {request.url.path} - Error: {str(e)}") + raise + +# Exception handler +@app.exception_handler(Exception) +async def global_exception_handler(request: Request, exc: Exception): + logger.error(f"Unhandled exception: {exc}", exc_info=True) + return JSONResponse( + status_code=500, + content={ + "ok": False, + "error": "Internal server error", + "detail": str(exc) if os.getenv("DEBUG") else "An error occurred" + } + ) + +# Health check endpoint +@app.get("/health") +def health_check(): + """健康检查端点""" + uptime = (datetime.now() - STATS["start_time"]).total_seconds() + return { + "status": "healthy", + "version": "1.0.0", + "uptime_seconds": uptime, + "loaded_cases": len(SCENARIOS), + "stats": { + "total_requests": STATS["total_requests"], + "successful_requests": STATS["successful_requests"], + "failed_requests": STATS["failed_requests"], + "success_rate": STATS["successful_requests"] / max(STATS["total_requests"], 1) + } + } + +# Statistics endpoint +@app.get("/stats") +def get_stats(): + """获取详细统计信息""" + return { + "stats": STATS, + "loaded_cases": list(SCENARIOS.keys()), + "uptime": str(datetime.now() - STATS["start_time"]) + } + +def _apply_progressive_reveal_at_init(scenario: GraphScenario): + """ + 在初始化时应用渐进式暴露机制(基于ITEM/HIDDEN_ITEM边) + + 新逻辑: + - 如果一个节点没有 ITEM/HIDDEN_ITEM 类型的入边,它就是初始可见的 + - 如果一个节点有 ITEM/HIDDEN_ITEM 类型的入边,它初始不可见,需要等待上游触发 + + Args: + scenario: 场景对象 + """ + # 收集所有有 ITEM/HIDDEN_ITEM 入边的节点 + nodes_with_item_edges = set() + for edge in scenario.edges: + if edge.connection_type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + nodes_with_item_edges.add(edge.target_id) + + logger.info(f"Nodes with ITEM/HIDDEN_ITEM incoming edges: {nodes_with_item_edges}") + + # 设置初始可见性:没有 ITEM/HIDDEN_ITEM 入边的节点初始可见 + initially_visible_count = 0 + for node_id, node in scenario.nodes.items(): + if node_id not in nodes_with_item_edges: + node.is_revealed = True + initially_visible_count += 1 + logger.info(f"Initial visible (no ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + else: + node.is_revealed = False + logger.debug(f"Initial hidden (has ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + + logger.info(f"Progressive reveal initialized: {initially_visible_count}/{len(scenario.nodes)} nodes initially visible") + + +def _check_inputs_match_golden(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> bool: + """ + 检查实际输入参数是否与 golden inputs 完全匹配 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + True 表示所有 golden inputs 都存在且值匹配 + """ + if not golden_inputs: + return True # 如果没有 golden inputs,认为匹配 + + for key, expected_value in golden_inputs.items(): + actual_value = arguments.get(key) + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) != str(expected_value): + logger.debug(f"Input mismatch for '{key}': expected '{expected_value}', got '{actual_value}'") + return False + + return True + + +def _get_parameter_validation_feedback(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> Dict[str, Any]: + """ + 对源头节点的参数进行详细验证,返回验证反馈 + + 注意:不返回期望值(expected),避免泄漏答案 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + 包含验证结果的字典: + - all_correct: bool - 所有参数是否正确 + - correct_params: List[str] - 正确的参数名列表 + - incorrect_params: List[str] - 错误的参数名列表(不包含期望值) + """ + if not golden_inputs: + return { + "all_correct": True, + "correct_params": [], + "incorrect_params": [] + } + + correct_params = [] + incorrect_params = [] + + for key, actual_value in arguments.items(): + # 只对用户实际提交的参数给反馈,未提交的参数不评价 + if key not in golden_inputs: + continue # 该参数不在 golden 中,跳过(如 _golden_inputs 等内部参数) + expected_value = golden_inputs[key] + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) == str(expected_value): + correct_params.append(key) + else: + # 只记录参数名,不包含期望值,避免泄漏答案 + incorrect_params.append(key) + + # all_correct:用户提交的所有参数都正确,且覆盖了全部 golden 参数 + all_provided_correct = len(incorrect_params) == 0 + all_golden_covered = all(k in arguments for k in golden_inputs) + return { + "all_correct": all_provided_correct and all_golden_covered, + "correct_params": correct_params, + "incorrect_params": incorrect_params + } + + +def _is_source_node(node_id: str, scenario: GraphScenario) -> bool: + """ + 判断节点是否是源头节点(完全没有任何入边的节点) + + 源头节点定义: + - 没有任何类型的入边(包括 DATA、ITEM、HIDDEN_ITEM) + - 即没有任何上游节点 + + Args: + node_id: 节点ID + scenario: 场景对象 + + Returns: + True 表示是源头节点 + """ + for edge in scenario.edges: + if edge.target_id == node_id: + # 只要有任何入边,就不是源头节点 + return False + + return True + + +def _check_and_reveal_ready_nodes(scenario: GraphScenario, recent_outputs: Dict[str, Any], source_node_id: str) -> List[Dict[str, Any]]: + """ + 检查并释放参数齐全的隐藏节点(渐进式暴露机制) + + 核心逻辑: + 1. 维护"可见值集合":包含所有被测模型当前可以看到的值 + - init_inputs 的值(初始可见) + - 工具执行后的实际输出值(运行时获得) + - 可见 Item 的输出值 + 2. 检查隐藏节点:该节点的所有 golden_input 值是否都在可见值集合中 + 3. 如果是,则释放该节点 + + Args: + scenario: 场景对象 + recent_outputs: 最近执行的工具的输出 + source_node_id: 刚执行的工具节点ID + + Returns: + 新释放的节点列表 + """ + newly_revealed = [] + + # 构建"可见值集合"(Set of visible values) + # 存储格式:set of values (转为字符串) + visible_values = set() + + # 1. 添加有意义的 init_inputs 值到可见值集合 + # Item 的 init_inputs 不应该加入,因为它们在密室中完全用不到 + for node_id, node in scenario.nodes.items(): + # 跳过源头 Item 节点(没有入边的 Item) + if node.type == "Item": + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,跳过其 init_inputs + continue + + # 添加其他节点的 init_inputs + for port_name, init_value in node.init_input_values.items(): + if init_value: + visible_values.add(str(init_value)) + + # 2. 添加已执行工具的所有历史输出值 + for node_id, node in scenario.nodes.items(): + if node.type == "Tool" and node.if_success and node.actual_outputs_history: + # 遍历所有历史执行记录 + for output_dict in node.actual_outputs_history: + for output_port_name, output_value in output_dict.items(): + if output_value: + visible_values.add(str(output_value)) + + # 3. 添加已被 investigate 的 Item 的 golden 输出值 + # 注意:Item 可见不等于其输出值可见,需要 investigate 后才能获得 + # 这里我们使用 actual_outputs_history 来标记 Item 是否已被 investigate + for node_id, node in scenario.nodes.items(): + if node.type == "Item" and node.is_revealed and node.actual_outputs_history: + # Item 通常只会被 investigate 一次,但为了一致性也使用历史列表 + for output_dict in node.actual_outputs_history: + for port_name, port_value in output_dict.items(): + if port_value: + visible_values.add(str(port_value)) + + # 遍历所有隐藏的节点,检查其 golden_input 是否都在可见值集合中 + for node_id, node in scenario.nodes.items(): + # 跳过已可见的节点 + if node.is_revealed: + continue + + # 只检查工具节点(物品节点由 ITEM 输出触发) + if node.type != "Tool": + continue + + # 检查该节点的所有 golden_input 值是否都在可见值集合中 + all_inputs_ready = True + missing_values = [] + + for input_port_name, golden_input_value in node.golden_input_values.items(): + # 检查这个 golden 值是否在可见值集合中 + if str(golden_input_value) not in visible_values: + all_inputs_ready = False + missing_values.append(f"{input_port_name}={golden_input_value}") + + # 如果所有 golden_input 值都在可见值集合中,释放该节点 + if all_inputs_ready and len(node.golden_input_values) > 0: + logger.info(f"All golden inputs ready for {node_id}: {list(node.golden_input_values.values())}") + + # 如果所有输入都齐全,释放该节点 + if all_inputs_ready: + node.is_revealed = True + + # 构建节点信息返回给模型 + node_info = { + "id": node.id, + "type": node.type, + "can_investigate": True, + "hint": "This tool's input parameters are now complete, you can use investigate to view detailed information" + } + + # if node.name: + # node_info["name"] = node.name + if node.description: + node_info["description"] = node.description + + newly_revealed.append(node_info) + logger.info(f"Progressive reveal: {node_id} is now ready (all inputs satisfied)") + + return newly_revealed + + +def _initialize_node_values(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]): + """ + Initialize node state and load values from port value fields. + 应用渐进式暴露机制:初始时只显示参数齐全的节点(源头节点) + + 重要区分: + 1. input_values: 只加载 metadata.initial_values 中的 init_inputs(真正的初始值) + 2. output_values: 加载 nodes[].outputs[].value(golden 输出,用于验证) + """ + # 第一步:加载所有节点的值,并将所有节点初始设为隐藏 + initial_values = metadata.get('initial_values', {}) + + for node_id, node in scenario.nodes.items(): + # 忽略 initial_visible 字段,初始全部隐藏 + # 由渐进式暴露机制根据参数齐全情况决定是否显示 + node.is_revealed = False + + if node.type == "Tool": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + elif node.type == "Item": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + + # 从 JSON 加载值 + if node_id in raw_nodes_data: + node_data = raw_nodes_data[node_id] # node_data是json文件中nodes中的字典 + + # 【重要】只加载 metadata.initial_values 中的初始输入值 + if node_id in initial_values: + init_data = initial_values[node_id] + # 加载初始输入值(用于渐进式暴露判断) + for port_name, port_value in init_data.get('init_inputs', {}).items(): + node.init_input_values[port_name] = port_value + + # 【评测用】加载 golden 输入值(用于验证模型传入的参数是否正确) + for input_port_data in node_data.get('inputs', []): + if 'value' in input_port_data: + node.golden_input_values[input_port_data['name']] = input_port_data['value'] + + # 【评测用】加载 golden 输出值(用于验证工具调用是否正确,以及 Item 节点的 content) + for output_port_data in node_data.get('outputs', []): + if 'value' in output_port_data: + node.golden_output_values[output_port_data['name']] = output_port_data['value'] + + # For Items, set content from golden_output_values + if node.type == "Item" and node.golden_output_values: + # Item 的 content 是其第一个 golden 输出值 + node.content = list(node.golden_output_values.values())[0] + + # 第二步:应用渐进式暴露机制 + # 检查所有节点,根据参数齐全情况释放源头节点(工具 + Item) + _apply_progressive_reveal_at_init(scenario) + +def _build_node_info(node: Node, raw_nodes_data: Dict[str, Any]) -> Dict[str, Any]: + """ + 构建节点信息(工具或物品) + + Args: + node: 节点对象 + raw_nodes_data: 原始节点数据(用于获取 template_id 等) + + Returns: + 节点信息字典 + """ + if node.type == "Tool": + # 过滤掉输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口) + # 这些端口仅用于控制掉落机制,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + tool_info = { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Tool", + "inputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.inputs if p.type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]], + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id(工具的标准名称) + if node.id in raw_nodes_data: + node_data = raw_nodes_data[node.id] + template_id = node_data.get('template_id') + if template_id: + tool_info['template_id'] = template_id + + return tool_info + + elif node.type == "Item": + return { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Item" + } + + else: + return { + "id": node.id, + # "name": node.name, + "type": node.type + } + +def _get_initial_observation(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]) -> Dict[str, Any]: + """ + Generate initial observation for the agent (what they see when entering the room). + + 策略: + - Tools: 只显示名称和描述,不显示接口定义。需要 investigate 才能获得详细接口信息。 + - Items: 只显示存在,不显示内容。需要 investigate 才能获得内容值。 + - init_inputs: 作为"可用信息"告诉模型,这些是可以用作工具参数的初始值。 + - init_outputs: 不告诉模型(这些是答案,需要模型通过调用工具获得)。 + """ + available_entities = [] # 统一的实体列表(Tools 和 Items) + available_information = [] # 可用的初始信息(来自 init_inputs) + + # 从 metadata.initial_values 提取 init_inputs 作为可用信息 + # 只提供值本身,不透露这些值对应哪个节点的哪个参数,让模型自己推理 + # 注意:跳过源头 Item(没有入边的 Item)的 init_inputs,因为它们在密室中完全用不到 + initial_values = metadata.get('initial_values', {}) + # initial_values字段的格式 + # "initial_values": { + # "terminal_1": { + # "init_inputs": {}, + # "init_outputs": { + # "text_output": "System initialization complete.", + # "hex_output": "48656c6c6f20576f726c64", + # "item_dispenser": "掉落了一张纸条,上面写着“请勿随意触摸终端”" + # } + # } + # } + for node_id, init_data in initial_values.items(): + # 获取节点信息,判断是否为源头 Item + node = scenario.nodes.get(node_id) + if node and node.type == "Item": + # 检查是否为源头 Item(没有入边) + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,检查是否有 init_inputs + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 有 init_inputs,需要暴露这些参数 + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + # 处理完后跳过后续的通用逻辑 + continue + + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 为每个 init_input 值创建一个信息条目(不包含 source_node 和 parameter 信息) + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + + for node in scenario.nodes.values(): + if node.is_revealed: + # Tools: 只显示基本信息,提示可以 investigate 查看详细接口 + if node.type == "Tool": + tool_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Tool", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the tool's detailed interface information for calling" + } + # 只在 name 非空时添加 + # if node.name: + # tool_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_info["description"] = node.description + + available_entities.append(tool_info) + + # Items: 只显示基本信息,提示可以 investigate 查看内容 + elif node.type == "Item": + item_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Item", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the item's content" + } + # 只在 name 非空时添加 + # if node.name: + # item_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + item_info["description"] = node.description + + available_entities.append(item_info) + + return { + "narrative": scenario.intro_narrative, + "available_entities": available_entities, # 使用统一的实体列表 + "available_information": available_information, # 可用的初始信息(只包含 init_inputs) + "win_node_id": scenario.win_node_id # 胜利节点ID,让模型知道需要关注哪个节点 + } + +@app.post("/env/reset") +def reset_case(case_id: str = None, case_file_path: str = None, session_id: str = None): + """Loads a specific case from file and resets it. + + Args: + case_id: Optional case ID for resetting an existing case + case_file_path: Path to case file for loading a new case + session_id: Optional session ID to ensure isolation between concurrent evaluations + """ + logger.info(f"Reset request - case_id: {case_id}, case_file_path: {case_file_path}, session_id: {session_id}") + STATS["case_loads"] += 1 + + if case_file_path: + if not os.path.exists(case_file_path): + logger.error(f"Case file not found: {case_file_path}") + raise HTTPException(status_code=404, detail=f"File not found: {case_file_path}") + try: + with open(case_file_path, "r", encoding="utf-8") as f: + file_data = json.load(f) + + # 转换格式:从 DAG executor 生成的格式转换为 GraphScenario 格式 + # 1. 提取 metadata + metadata = file_data.get('metadata', {}) + + # 2. 生成 case_id, title, intro_narrative + # 【修复】为每个评测会话生成唯一的 case_id,防止并发评测时状态污染 + base_name = os.path.basename(case_file_path).replace('.json', '').replace('_full', '').replace('_full2', '') + + if session_id: + # 如果提供了 session_id,使用它来确保唯一性 + case_id = f"{base_name}_{session_id}" + else: + # 否则使用时间戳和随机数确保唯一性 + unique_suffix = f"{int(time.time() * 1000)}_{random.randint(1000, 9999)}" + case_id = f"{base_name}_{unique_suffix}" + + file_data['case_id'] = case_id + logger.info(f"Generated unique case_id: {case_id} (base: {base_name}, session: {session_id})") + + if 'title' not in file_data: + file_data['title'] = f"Escape Room: {file_data['case_id']}" + + if 'intro_narrative' not in file_data: # 目前的json文件中已经有了intro_narrative字段,不会使用下面一行的内容,而是使用每个评测问题的json文件中的对应字段 + 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]".' + + # 3. 转换 nodes 列表为字典(DAG executor 生成的文件中 nodes 是列表格式) + nodes_dict = {} + for node_data in file_data['nodes']: + nodes_dict[node_data['id']] = node_data # 这里的id是template_id之后可能添加一个后缀 + file_data['nodes'] = nodes_dict # 把列表转成一个字典 + + # 4. 添加缺失的字段 + if 'difficulty' not in file_data: + file_data['difficulty'] = metadata.get('total_nodes', 5) + + if 'win_node_id' not in file_data: + file_data['win_node_id'] = metadata.get('win_node_id', '') + + scenario = GraphScenario(**file_data) + + # Extract raw nodes data for template_id access + # nodes 已经在上面转换为字典格式 + raw_nodes_data = file_data.get('nodes', {}) + RAW_NODES_DATA[scenario.case_id] = raw_nodes_data + + # Store metadata for initial values access + FILE_METADATA[scenario.case_id] = metadata + + logger.info(f"Successfully parsed case file: {scenario.case_id}, nodes: {len(scenario.nodes)}, edges: {len(scenario.edges)}") + except Exception as e: + logger.error(f"Failed to load case file: {str(e)}", exc_info=True) + raise HTTPException(status_code=500, detail=f"Failed to load case file: {str(e)}") + + # Initialize node state and load values + _initialize_node_values(scenario, raw_nodes_data, metadata) + + SCENARIOS[scenario.case_id] = scenario + simulator = ToolSimulator() + SIMULATORS[scenario.case_id] = simulator + + 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'])}") + + # 生成初始观察信息(进入密室后看到的环境) + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + ''' + initial_observation的格式: + { + "narrative": scenario.intro_narrative, + "available_entities": available_entities # 使用统一的实体列表 + "available_information": available_information # 可用的初始信息(只包含 init_inputs) + } + ''' + + return { + "ok": True, + "message": f"Case loaded from {case_file_path}", + "case_id": scenario.case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果没有提供 case_file_path,但提供了 case_id,则尝试从内存重置 + if case_id and case_id in SCENARIOS: + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + metadata = FILE_METADATA.get(case_id, {}) + + # Reset dynamic fields and re-apply progressive reveal + # 重新初始化节点状态(包括渐进式暴露) + _initialize_node_values(scenario, raw_nodes_data, metadata) + + 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'])}") + + # 生成初始观察信息 + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + + return { + "ok": True, + "message": f"Case {case_id} reset.", + "case_id": case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果既没有 case_file_path,也没有在内存中找到,返回错误 + raise HTTPException( + status_code=400, + detail="Must provide case_file_path to load a new case, or use case_id to reset an existing case." + ) + +class InvestigateRequest(BaseModel): + node_id: str + +@app.post("/env/{case_id}/investigate") +def investigate(case_id: str, req: InvestigateRequest): + """ + Investigates a Tool or Item to reveal detailed information. + + - For Tools: Returns detailed interface information (inputs/outputs) needed to call the tool + - For Items: Returns content value and triggers hidden item drops + """ + logger.info(f"Investigate request - case_id: {case_id}, node_id: {req.node_id}") + STATS["investigates"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + node = scenario.nodes[req.node_id] + + if not node.is_revealed: + logger.warning(f"Attempt to investigate hidden node: {req.node_id}") + return {"ok": False, "error": "Node is not visible yet."} + + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + newly_revealed = [] + + # 处理 Tool 的 investigate + if node.type == "Tool": + logger.info(f"Investigating tool: {req.node_id}") + + # 返回工具的详细接口信息 + # id 字段使用 node.id(节点唯一标识),agent 用这个字段识别和调用具体的节点 + # template_id 是工具类型标识符,Agent 内部用于判断工具特性(如 terminal 类工具参数可选) + # 注意:只过滤输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口),这些端口仅用于控制掉落,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + # 【端口上游依赖提示 & 初始值直接给出】 + # 针对参数语义模糊(全为数字类型)的工具,在 investigate 返回信息中标注 + # 哪个输入端口来自哪个上游节点(upstream_from)。 + # 对于所有工具:若该节点不是纯源头节点(有任意数据流入边), + # 且某个端口没有上游入边(值来自初始可见参数),则直接给出该端口的 golden input 值。 + AMBIGUOUS_TOOLS = { + "num_base_convert", "calc_modexp", "calc_modexp_int", + "calc_inv_mod", "calc_inv_mod_int", "crypto_rsa_decrypt_hex", "geo_haversine" + } + # Terminal 类工具自带参数对错反馈机制,玩家/模型可自行试错, + # 无需在 investigate 时直接暴露 init_value + SELF_FEEDBACK_TOOLS = { + "terminal_1", "terminal_2", + "Logic Terminal", "Math Terminal", "Encryption Terminal", "Sequence Terminal" + } + _template_id_for_hint = raw_nodes_data.get(node.id, {}).get("template_id", "") + # 构建数据流入边映射(对所有工具):{target_port -> (source_node_id, source_port)} + _upstream_map = {} + for _edge in scenario.edges: + if (_edge.target_id == node.id + and _edge.connection_type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM] + and _edge.target_port is not None): + _upstream_map[_edge.target_port] = (_edge.source_id, _edge.source_port) + # 判断该节点是否有任意数据流入边(即不是纯源头节点) + _has_any_upstream = len(_upstream_map) > 0 + # 判断该节点是否有任意入边(包括 ITEM/HIDDEN_ITEM 掉落边) + # 有任意入边(含掉落边)但无数据流入边的节点,其输入来自初始可见参数,应直接给出 + _has_any_edge = any(_edge.target_id == node.id for _edge in scenario.edges) + # 构建 inputs 列表 + _inputs_list = [] + for p in node.inputs: + if p.type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + continue + port_dict = {"name": p.name, "type": p.type, "description": p.description} + if p.name in _upstream_map: + # 该端口有上游数据流依赖,且属于语义模糊工具 → 标注来源 + if _template_id_for_hint in AMBIGUOUS_TOOLS: + src_node_id, src_port = _upstream_map[p.name] + port_dict["upstream_from"] = f"{src_node_id}.{src_port}" if src_port else src_node_id + elif _has_any_edge and _template_id_for_hint not in SELF_FEEDBACK_TOOLS: + # 该节点有任意入边,但此端口没有数据流入边 → 值来自初始可见参数,直接给出 + # 排除自带反馈机制的 terminal 类工具(它们通过执行结果反馈对错,无需提前暴露参数值) + golden_val = node.golden_input_values.get(p.name) + if golden_val is not None: + port_dict["init_value"] = golden_val + _inputs_list.append(port_dict) + + tool_details = { + "id": node.id, # 节点 ID,用于唯一标识和调用这个具体节点 + "type": "Tool", + "inputs": _inputs_list, + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id 用于 Agent 内部判断工具类型(不会展示给被测模型) + if node.id in raw_nodes_data: + template_id = raw_nodes_data[node.id].get('template_id') + if template_id: + tool_details["_template_id"] = template_id # 使用下划线前缀标记为内部字段 + + # 只在 name 非空时添加 + # if node.name: + # tool_details["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_details["description"] = node.description + + # 添加 narrative 字段(如果存在) + if node.id in raw_nodes_data: + narrative = raw_nodes_data[node.id].get('narrative') + if narrative: + tool_details['narrative'] = narrative + + # 不再返回 init_values,避免泄漏答案 + # investigate 只应该返回工具的接口定义,不应该暴露初始值 + + # 【新增】检查该 Tool 是否有待触发的 HIDDEN_ITEM 掉落 + # 如果该工具已按照 golden_input 正确执行,且有 HIDDEN_ITEM 输出边,则触发掉落 + if node.has_hidden_item_ready: + logger.info(f"Tool has HIDDEN_ITEM ready - triggering passive drop for: {req.node_id}") + + # 遍历该工具的所有 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + # 重置标志,已经触发过了,避免重复 + node.has_hidden_item_ready = False + + logger.info(f"Tool investigation successful - node: {req.node_id}, revealed: {len(newly_revealed)}") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Tool", + "details": tool_details + } + + # 如果有新掉落的节点,添加到响应中 + if newly_revealed: + result["newly_revealed"] = newly_revealed + + return result + + # 处理 Item 的 investigate + elif node.type == "Item": + logger.info(f"Investigating item: {req.node_id}") + + # 【第一步】检查该 Item 是否有需要参数的输入端口 + # 如果有,且尚未通过 use_item 验证,则不返回内容,只返回参数要求 + required_inputs = [] + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + inputs_info = raw_node.get('inputs', []) + required_inputs = [ + { + "name": inp.get("name"), + "type": inp.get("type"), + "description": inp.get("description", "") + } + for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + # 如果有 required_inputs 且尚未通过 use_item 验证(if_success == False) + # 则不返回内容,只返回参数要求提示 + if required_inputs and not node.if_success: + logger.info(f"Item has required inputs and not yet unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "required_inputs": required_inputs + } + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + param_names = ', '.join([inp['name'] for inp in required_inputs]) + 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}" + + return result + + # 【新增】如果有 required_inputs 且已经通过 use_item 验证(if_success == True) + # 则返回提示:该节点已经被成功解决 + if required_inputs and node.if_success: + logger.info(f"Item has required inputs and already unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "message": "This item has already been successfully unlocked by you." + } + return result + + # 【第二步】该 Item 没有 required_inputs 或已通过验证,返回内容 + # 1. 返回 Item 的 golden_output_values(即 Item 的内容) + # 注意:某些 Item 仅用于触发 HIDDEN_ITEM 掉落,没有实际内容 + has_actual_content = bool(node.golden_output_values) or node.content is not None + content = node.golden_output_values if node.golden_output_values else node.content + + # 【关键】将 golden_output_values 追加到 actual_outputs_history,标记该 Item 已被 investigate + # 这样在渐进式暴露时,这些值才会被加入可见值集合 + # 即使是空字典(仅触发 HIDDEN_ITEM 的 Item),也要记录,以便渐进式暴露逻辑知道该 Item 已被调查 + if node.golden_output_values is not None: + node.actual_outputs_history.append(dict(node.golden_output_values)) + + # 2. Trigger Hidden Item Drops (Passive Drop) + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + logger.info(f"Item investigation successful - node: {req.node_id}, has_content: {has_actual_content}, revealed: {len(newly_revealed)}") + + # 【渐进式暴露】旧机制(基于 golden_input)已禁用 + # 现在完全由 ITEM/HIDDEN_ITEM 边触发控制节点可见性 + # 上面的 HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, node.golden_output_values or {}, node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # logger.info(f"Progressive reveal after Item investigate: {len(progressive_revealed)} nodes now ready") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Item" + } + + # 只在有实际内容时才添加 content 字段 + # 对于仅触发 HIDDEN_ITEM 掉落的 Item,不返回 content 字段,避免返回 None 或空字典让模型困惑 + if has_actual_content: + result["content"] = content + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型通过 investigate 获得内容后,需要自己识别这是否是胜利字符串 + + return result + + else: + logger.warning(f"Attempt to investigate unknown node type: {req.node_id} (type: {node.type})") + return {"ok": False, "error": f"Cannot investigate node type: {node.type}"} + +class ToolCallRequest(BaseModel): + node_id: str # 使用 node_id 精确指定要调用的节点 + arguments: Dict[str, Any] + +@app.post("/env/{case_id}/tool_call") +def tool_call(case_id: str, req: ToolCallRequest): + """Executes a tool and triggers item drops.""" + logger.info(f"Tool call request - case_id: {case_id}, node_id: {req.node_id}, args: {list(req.arguments.keys())}") + STATS["tool_calls"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + + # 通过 node_id 精确查找节点 + node_id = req.node_id + if node_id not in scenario.nodes: + logger.error(f"Node not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + tool_node = scenario.nodes[node_id] + + if not tool_node: + logger.error(f"Tool not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Tool not found") + + if not tool_node.is_revealed: + logger.warning(f"Attempt to call hidden tool: {node_id}") + return {"ok": False, "error": "Tool is not visible yet."} + + if tool_node.type != "Tool": + logger.warning(f"Attempt to call non-tool node: {node_id} (type: {tool_node.type})") + return {"ok": False, "error": "Only tools can be called."} + + # 1. Execute Tool (Real Execution via Simulator) + simulator = SIMULATORS[case_id] + + # Get tool name from template_id if available, otherwise use node name + tool_name = tool_node.name + if case_id in RAW_NODES_DATA and node_id in RAW_NODES_DATA[case_id]: + template_id = RAW_NODES_DATA[case_id][node_id].get('template_id') + if template_id: + tool_name = template_id + + # 文件处理工具和 Terminal 需要验证输入并返回预先计算的输出 + # 传递节点的实际输入输出值(从 DAG 执行后填充的数据) + tool_arguments = dict(req.arguments) # Make a copy + + # 传递节点的 golden values(从 JSON 的 inputs[].value 和 outputs[].value 加载) + # 用于在评测阶段验证被测模型传入的参数是否正确 + if tool_node.golden_input_values: + tool_arguments['_golden_inputs'] = tool_node.golden_input_values + if tool_node.golden_output_values: + tool_arguments['_golden_outputs'] = tool_node.golden_output_values + + logger.debug(f"Executing tool {tool_name} (node: {tool_node.name}) with args {tool_arguments}") + + try: + output_values = simulator.execute(tool_name, tool_arguments) + logger.info(f"Tool invoked - {tool_name}: {list(output_values.keys())}") + except Exception as e: + logger.error(f"Tool execution failed - {tool_name}: {str(e)}", exc_info=True) + return {"ok": False, "error": f"Tool execution failed: {str(e)}"} + + # 检查验证结果(精细化错误反馈) + validation = output_values.pop("_validation", {"valid": True}) + + if not validation["valid"]: + # 根据错误类型构造友好的错误消息 + error_type = validation.get("error_type") + + if error_type == "missing_required": + missing = validation.get("missing_params", []) + error_msg = f"Error: Missing required parameters {', '.join(missing)}" + + elif error_type == "type_error": + param = validation.get("param_name") + message = validation.get("message", "Parameter type error") + error_msg = f"Error: {message}" + + elif error_type == "incomplete_optional": + provided = validation.get("provided_params", []) + missing = validation.get("missing_params", []) + error_msg = ( + f"Hint: You provided some parameters ({', '.join(provided)}), " + f"but may also need: {', '.join(missing)}.\n" + f"Trying to provide these parameters together might yield better results." + ) + + elif error_type == "value_mismatch": + param = validation.get("param_name") + hint = validation.get("hint", "Parameter value may be incorrect") + error_msg = f"Hint: {hint}.\nPlease check if this parameter value meets the requirements." + + else: + error_msg = validation.get("hint") or validation.get("message", "Parameter validation failed") + + logger.info(f"Tool validation failed - {tool_name}: {error_type}") + return { + "ok": False, + "error": error_msg, + "error_type": error_type + } + + # Simulate success + tool_node.if_success = True + + # 【关键】将本次执行的输出值追加到历史列表(用于渐进式暴露判断) + # 每次调用都会记录,不会覆盖之前的执行结果 + tool_node.actual_outputs_history.append(dict(output_values)) + + # 2. 检查是否应该触发掉落(只有输入参数正确时才掉落) + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, tool_node.golden_input_values) + + newly_revealed = [] + investigate_hints = [] # 提示模型哪些节点可以 investigate 来发现隐藏内容 + + if inputs_match_golden: + logger.info(f"✓ Tool inputs match golden - node: {node_id}, triggering drops") + + # 检查该工具是否有 ITEM 或 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == tool_node.id: + target_node = scenario.nodes[edge.target_id] + + # ITEM 边:立即掉落(主动掉落) + if edge.connection_type == InterfaceType.ITEM: + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from {node_id})") + + # HIDDEN_ITEM 边:不立即掉落,标记并提示(被动掉落) + elif edge.connection_type == InterfaceType.HIDDEN_ITEM: + # 标记该工具有待触发的 HIDDEN_ITEM 掉落 + tool_node.has_hidden_item_ready = True + + # 提示模型可以 investigate 这个工具来发现隐藏内容 + hint_info = { + "tool_id": tool_node.id, + "hint": f"Tool '{tool_node.id}' seems to hide something, try investigating it to discover more information" + } + # if tool_node.name: + # hint_info["tool_name"] = tool_node.name + + investigate_hints.append(hint_info) + logger.info(f"HIDDEN_ITEM ready: {tool_node.id} -> {target_node.id} (will drop on investigate)") + else: + logger.info(f"✗ Tool inputs do NOT match golden - node: {node_id}, no drops triggered") + + response = { + "ok": True, + "message": "Tool invoked", + "output_values": output_values # Return raw outputs to Agent + } + + # 【新增】对源头节点进行参数验证反馈 + # 源头节点:没有数据流入边的节点,这些节点的参数需要模型自己推理 + # 验证模型使用的参数是否正确,并提供明确的反馈 + if _is_source_node(node_id, scenario) and tool_node.golden_input_values: + validation_feedback = _get_parameter_validation_feedback(req.arguments, tool_node.golden_input_values) + + if validation_feedback["all_correct"]: + # 用户提交了全部 golden 参数且全部正确 + response["parameter_feedback"] = { + "status": "correct", + "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." + } + logger.info(f"✓ Source node parameters all correct - node: {node_id}") + elif validation_feedback["incorrect_params"]: + # 有提交了但值错误的参数,只对这些参数给出反馈 + incorrect_list = [] + for param_name in validation_feedback["incorrect_params"]: + incorrect_list.append(f" - Parameter '{param_name}' is incorrect") + + correct_info = "" + if validation_feedback["correct_params"]: + correct_info = f"\n✓ Correct parameters: {', '.join(validation_feedback['correct_params'])}" + + response["parameter_feedback"] = { + "status": "incorrect", + "message": ( + f"⚠️ Some parameters are incorrect:\n" + + "\n".join(incorrect_list) + + correct_info + + 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." + ), + "incorrect_params": validation_feedback["incorrect_params"], + "correct_params": validation_feedback["correct_params"] + } + logger.info(f"✗ Source node parameters incorrect - node: {node_id}, incorrect: {validation_feedback['incorrect_params']}") + # else: 部分提交且全部正确 → 不给任何 parameter_feedback,避免对未提交的参数发表意见 + + # 检查工具调用是否完全正确(输出与 golden outputs 匹配) + # 用于给模型正向反馈,让它知道这个工具已经正确调用过,避免重复调用 + # 注意:只有当输出完全匹配时才标记为 correct,不会在错误时提供具体错误信息 + # if tool_node.golden_output_values and output_values: + # is_correct = True + # for port_name, expected_value in tool_node.golden_output_values.items(): + # actual_value = output_values.get(port_name) + # if str(actual_value) != str(expected_value): + # is_correct = False + # break + + # if is_correct: + # response["tool_call_correct"] = True + # logger.info(f"✓ Tool called with correct result - node: {node_id}") + + # 只在有新内容掉落时才返回 newly_revealed + if newly_revealed: + response["newly_revealed"] = newly_revealed + + # 添加 investigate 提示(对于有待触发 HIDDEN_ITEM 掉落的工具) + if investigate_hints: + response["investigate_hints"] = investigate_hints + + # 3. 渐进式暴露机制 - 现在完全由 ITEM/HIDDEN_ITEM 边控制 + # 旧机制(基于 golden_input 检查)已被禁用 + # 新机制中,节点的可见性只由 ITEM/HIDDEN_ITEM 边触发决定 + # 上面的 ITEM/HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, output_values, tool_node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # response["newly_revealed"] = newly_revealed + # logger.info(f"Progressive reveal: {len(progressive_revealed)} nodes now ready") + + # Check if this is the win node + if node_id == scenario.win_node_id: + # 验证输出值是否等于预期的胜利值 + # 从节点的 golden_output_values 中获取预期值(在 _initialize_node_values 时从 JSON 加载) + expected_outputs = tool_node.golden_output_values + + # 检查实际输出是否与预期输出匹配 + is_correct = False + victory_string = None + mismatch_info = [] + + if expected_outputs and output_values: + # 检查每个预期输出端口的值是否匹配 + is_correct = True + for port_name, expected_value in expected_outputs.items(): + actual_value = output_values.get(port_name) + if actual_value != expected_value: + is_correct = False + mismatch_info.append(f"Port '{port_name}': expected '{expected_value}', actual '{actual_value}'") + logger.warning(f"Win node output mismatch - port: {port_name}, expected: {expected_value}, actual: {actual_value}") + + # 如果所有输出都匹配,使用第一个输出作为胜利字符串 + if is_correct and output_values: + victory_string = list(output_values.values())[0] + else: + logger.warning(f"Win node called but missing output values - expected: {expected_outputs}, actual: {output_values}") + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型调用工具获得输出后,需要自己识别这是否是胜利字符串并提交 + if is_correct: + logger.info(f"🎯 Win node called with correct output - case: {case_id}, node: {node_id}, victory: {victory_string}") + else: + logger.info(f"❌ Win node called with incorrect output - case: {case_id}, node: {node_id}") + + return response + +class UseItemRequest(BaseModel): + node_id: str = Field(..., description="The ID of the Item node to use (must be Item type)") + arguments: Dict[str, Any] = Field(default_factory=dict, description="Input arguments to provide to the item") + +@app.post("/env/{case_id}/use_item") +def use_item(case_id: str, req: UseItemRequest): + """ + Use an Item node by providing input arguments. + + This is specifically for Item nodes that require parameters to be "unlocked" or "activated", + such as containers that need a password/fingerprint. + + - Validates that the node is of type Item + - Checks if provided arguments match the item's golden_input_values + - If match: triggers ITEM-type edge drops and returns the item's content + - If not match: returns error message + """ + logger.info(f"Use item request - case_id: {case_id}, node_id: {req.node_id}, args: {req.arguments}") + STATS["use_items"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + item_node = scenario.nodes[req.node_id] + + if not item_node.is_revealed: + logger.warning(f"Attempt to use hidden item: {req.node_id}") + return {"ok": False, "error": "Item is not visible yet."} + + if item_node.type != "Item": + logger.warning(f"Attempt to use non-item node: {req.node_id} (type: {item_node.type})") + return {"ok": False, "error": "Only Item nodes can be used with use_item. Tools should be called with tool_call."} + + # 【新增】检查该 Item 是否已经被成功解锁 + # 如果已经被正确使用过,直接返回成功提示 + if item_node.if_success: + logger.info(f"Item already unlocked, returning success message: {req.node_id}") + return { + "ok": True, + "message": "This item has already been successfully unlocked by you." + } + + # 检查该 Item 是否真的需要通过 use_item 提供参数 + # 只有当 Item 有非 Item/Hidden_Item 类型的输入时,才应该使用 use_item + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + non_hidden_inputs = [ + inp for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + if not non_hidden_inputs: + # 该 Item 不需要参数,应该只使用 investigate + logger.warning(f"Attempt to use_item on a node that doesn't require parameters: {req.node_id}") + return { + "ok": False, + "error": "This item does not require parameters. Please use investigate to examine the item directly." + } + + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, item_node.golden_input_values) + + if not inputs_match_golden: + logger.info(f"✗ Item inputs do NOT match golden - node: {req.node_id}") + # 提供更详细的错误信息,帮助 Agent 理解问题 + # 只显示非 Item/Hidden_Item 类型的参数(Hidden_Item 由系统自动处理) + expected_params = [] + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + expected_params = [ + inp.get("name") for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + provided_params = list(req.arguments.keys()) if req.arguments else [] + + # 检查参数名是否匹配 + if set(expected_params) == set(provided_params): + # 参数名正确但值不匹配 - 不泄漏正确的值 + error_msg = f"Parameter names are correct, but the parameter values are incorrect. Please try using different parameter values." + else: + error_msg = f"Parameter names do not match. Expected parameter names: {expected_params}, you provided: {provided_params}." + + return { + "ok": False, + "error": error_msg + } + + logger.info(f"✓ Item inputs match golden - node: {req.node_id}, activating item") + + # 标记该 Item 已被正确使用 + item_node.if_success = True + + # 将 golden_output_values 追加到 actual_outputs_history + if item_node.golden_output_values: + item_node.actual_outputs_history.append(dict(item_node.golden_output_values)) + + # 触发 ITEM 类型边的掉落 + newly_revealed = [] + for edge in scenario.edges: + if edge.source_id == item_node.id and edge.connection_type == InterfaceType.ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from use_item on {req.node_id})") + + # 检查是否为 Win Node + win_node_id = scenario.win_node_id + is_win_node = (req.node_id == win_node_id) + + # 构建返回结果 + result = { + "ok": True, + "message": "Item used successfully.", + "content": item_node.golden_output_values if item_node.golden_output_values else None + } + + # 获取 narrative(如果存在) + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + narrative = raw_nodes_data[req.node_id].get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 如果是 Win Node,只记录日志 + if is_win_node: + logger.info(f"Win node (Item) unlocked via use_item - case: {case_id}, node: {req.node_id}") + + return result + + +class SubmitAnswerRequest(BaseModel): + answer: str = Field(..., description="The victory string to submit") + +@app.post("/env/{case_id}/submit_answer") +def submit_answer(case_id: str, req: SubmitAnswerRequest): + """ + 提交答案接口 + 被测模型在获得胜利字符串提示后,需要调用此接口提交答案 + """ + logger.info(f"Submit answer request - case_id: {case_id}, answer: {req.answer}") + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + + # 获取 win_node 的 golden_output_values + if not scenario.win_node_id: + logger.error(f"No win node defined for case: {case_id}") + return { + "ok": False, + "error": "This case has no victory node defined" + } + + win_node = scenario.nodes.get(scenario.win_node_id) + if not win_node: + logger.error(f"Win node not found: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node does not exist" + } + + # 获取正确的胜利字符串(取第一个 golden_output_value) + if win_node.golden_output_values: + correct_answer = list(win_node.golden_output_values.values())[0] + else: + logger.error(f"Win node has no golden_output_values: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node has no correct answer" + } + + # 验证提交的答案 + if req.answer == correct_answer: + logger.info(f"🎉 CORRECT ANSWER SUBMITTED - case: {case_id}, answer: {req.answer}") + return { + "ok": True, + "is_win": True, + "victory_message": f"🎉 Congratulations on successfully escaping the room! Your answer is correct: {req.answer}" + } + else: + logger.info(f"❌ INCORRECT ANSWER SUBMITTED - case: {case_id}, submitted: {req.answer}, correct: {correct_answer}") + return { + "ok": True, + "is_win": False, + "error": f"The submitted answer is incorrect. You submitted: {req.answer}" + } + +if __name__ == "__main__": + + uvicorn.run(app, host="0.0.0.0", port=8000) \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-3597bfa8/environment/puzzle/upstream/simulator.py b/tasks/agentescape-25-skeleton-3597bfa8/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3597bfa8/environment/puzzle/upstream/simulator.py @@ -0,0 +1,2911 @@ +import hashlib +import hmac +import base64 +import binascii +import zlib +import json +import uuid +import math +import re +from typing import Dict, Any, List + +class ToolSimulator: + def __init__(self): + """工具模拟器 + + 文件处理工具(zip_unzip, zip_unzip_file, zip_unzip_item, json_get, csv_query, + regex_search, graph_shortest_path)不需要真实文件系统。 + 这些工具只验证输入参数,然后返回预先初始化好的 golden_outputs。 + """ + self.tool_map = { + # 数论 + "calc_bigmul": self.calc_bigmul, + "calc_modexp": self.calc_modexp, + "calc_modexp_int": self.calc_modexp_int, + "calc_gcd": self.calc_gcd, + "calc_gcd_int": self.calc_gcd_int, + "calc_inv_mod": self.calc_inv_mod, + "calc_inv_mod_int": self.calc_inv_mod_int, + + # 哈希 + "hash_sha256": self.hash_sha256, + "hash_md5": self.hash_md5, + "hmac_sha256": self.hmac_sha256, + + # 编码 + "base64_decode": self.base64_decode, + "base64_encode": self.base64_encode, + "hex_decode": self.hex_decode, + "hex_encode": self.hex_encode, + "zlib_inflate": self.zlib_inflate, + "zlib_deflate": self.zlib_deflate, + + # 文件 + "zip_unzip": self.zip_unzip, + "zip_unzip_file": self.zip_unzip_file, + "zip_unzip_item": self.zip_unzip_item, + "regex_search": self.regex_search, + "json_get": self.json_get, + "csv_query": self.csv_query, + "code_py_exec": self.code_py_exec, + + # 图 + "graph_shortest_path": self.graph_shortest_path, + + # 加解密 (简化模拟) + "crypto_aes_cbc_decrypt": self.crypto_aes_cbc_decrypt, + "crypto_rsa_decrypt_hex": self.crypto_rsa_decrypt_hex, + + # 其他 + "num_base_convert": self.num_base_convert, + "time_convert": self.time_convert, + "checksum_crc32": self.checksum_crc32, + "geo_haversine": self.geo_haversine, + "otp_totp_generate": self.otp_totp_generate, + "unicode_norm": self.unicode_norm, + "text_bidi_sanitize": self.text_bidi_sanitize, + "text_xor_hex": self.text_xor_hex, + "text_rotN": self.text_rotN, + "luhn_check": self.luhn_check, + "iban_validate": self.iban_validate, + + # 物理 + "matter_synthesizer": self.matter_synthesizer, + + # 终端机 + "terminal_1": self.terminal_1, + "terminal_2": self.terminal_2, + "Logic Terminal": self.logic_terminal, + "Math Terminal": self.math_terminal, + "Encryption Terminal": self.crypt_terminal, + "Sequence Terminal": self.sequence_terminal + } + + def execute(self, tool_name: str, inputs: Dict[str, Any]) -> Dict[str, Any]: + if tool_name not in self.tool_map: + # Fallback for unknown tools: return dummy outputs based on expected output types + # This should ideally not happen if all tools are implemented + return {} + + try: + return self.tool_map[tool_name](inputs) + except Exception as e: + print(f"Error executing {tool_name}: {e}") + # Return empty or error indication? For generation, we might want to fail hard or return dummy. + # For now, return dummy to keep flow going, but log error. + return {} + + # --- Implementations --- + + def calc_bigmul(self, inputs): + # Check if required parameters are present + if "a" not in inputs or "b" not in inputs: + raise ValueError("Missing required parameters 'a' and/or 'b'") + + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + return {"product": str(a * b)} + except (ValueError, TypeError) as e: + raise ValueError(f"Failed to convert parameters to integers: {str(e)}") + + def calc_modexp(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + try: + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if isinstance(base, str): + base = int(base) + elif not isinstance(base, int): + raise ValueError("Parameter 'base' must be a string or integer") + + if isinstance(exp, str): + exp = int(exp) + elif not isinstance(exp, int): + raise ValueError("Parameter 'exp' must be a string or integer") + + if isinstance(mod, str): + mod = int(mod) + elif not isinstance(mod, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": str(pow(base, exp, mod))} + + def calc_modexp_int(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["base"], int): + raise ValueError("Parameter 'base' must be an integer") + if not isinstance(inputs["exp"], int): + raise ValueError("Parameter 'exp' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": pow(base, exp, mod)} + + def calc_gcd(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + # 计算 GCD 并返回字符串格式(符合 Big_Int 输出类型) + result = math.gcd(a, b) + return {"gcd": str(result)} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def calc_gcd_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["b"], int): + raise ValueError("Parameter 'b' must be an integer") + + # 获取参数 + a = inputs["a"] + b = inputs["b"] + + return {"gcd": math.gcd(a, b)} + + def calc_inv_mod(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + m = inputs["mod"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(m, str): + m = int(m) + elif not isinstance(m, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": str(pow(a, -1, m))} + except ValueError as e: + # 模逆不存在时,返回一个特殊值(用于数据传递) + # 在 DAG 生成阶段,这允许数据流继续 + return {"inv": str(a)} + + def calc_inv_mod_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + a = inputs["a"] + m = inputs["mod"] + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": pow(a, -1, m)} + except ValueError as e: + raise ValueError(f"Modular inverse does not exist: {str(e)}") + + def hash_sha256(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.sha256(text.encode()).hexdigest()} + + def hash_md5(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.md5(text.encode()).hexdigest()} + + def hmac_sha256(self, inputs): + # 参数检查 + if "hex_key" not in inputs: + raise ValueError("Missing required parameter: hex_key") + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["hex_key"], str): + raise ValueError("Parameter 'hex_key' must be a string") + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + try: + key = bytes.fromhex(inputs["hex_key"]) + text = inputs["text"].encode() + return {"hex": hmac.new(key, text, hashlib.sha256).hexdigest()} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def base64_decode(self, inputs): + # 参数检查 + if "data" not in inputs: + raise ValueError("Missing required parameter: data") + + # 类型检查 + if not isinstance(inputs["data"], str): + raise ValueError("Parameter 'data' must be a string") + + data = inputs["data"] + try: + return {"bytes_hex": binascii.hexlify(base64.b64decode(data)).decode()} + except Exception as e: + raise ValueError(f"Base64 decode error: {str(e)}") + + def base64_encode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"b64": base64.b64encode(bytes.fromhex(hex_data)).decode()} + except Exception as e: + raise ValueError(f"Base64 encode error: {str(e)}") + + def hex_decode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"text": bytes.fromhex(hex_data).decode('utf-8', errors='ignore')} + except Exception as e: + raise ValueError(f"Hex decode error: {str(e)}") + + def hex_encode(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + try: + return {"hex": text.encode().hex()} + except Exception as e: + raise ValueError(f"Hex encode error: {str(e)}") + + + # 到此处实现已经更新 + + def zlib_inflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("Parameter 'hex' must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("Missing required parameter: hex") + + try: + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空字符串 + if not hex_data: + raise ValueError("Empty hex string provided") + + # 检查十六进制字符串的有效性 + if len(hex_data) % 2 != 0: + raise ValueError("Hex string must have even length") + + # 检查是否只包含有效的十六进制字符 + if not all(c in '0123456789abcdefABCDEF' for c in hex_data): + raise ValueError("Invalid hex string provided") + + # 尝试解压缩 + return {"text": zlib.decompress(bytes.fromhex(hex_data)).decode('utf-8')} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hex string provided") from e + raise ValueError(f"Invalid zlib data: {e}") from e + except Exception as e: + raise RuntimeError(f"Failed to inflate data: {e}") from e + + def zlib_deflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("Parameter 'text' must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("Missing required parameter: text") + + try: + # 压缩文本 + return {"hex": zlib.compress(text.encode('utf-8')).hex()} + except Exception as e: + raise RuntimeError(f"Failed to deflate data: {e}") from e + + # --- File Operations --- + + def zip_unzip(self, inputs): + """ZIP 解压工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"files": golden_outputs.get("files", "")} + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return {"files": golden_outputs.get("files", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "files" in golden_outputs: + # 验证必需参数 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 检查类型 + if has_zip_id and not isinstance(zip_id, str): + return {"error": "Parameter 'zip_id' must be a string type"} + if has_password and not isinstance(password, str): + return {"error": "Parameter 'password' must be a string type"} + + # 验证输入是否与预期匹配 + if golden_inputs: + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return {"files": golden_outputs["files"]} + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + # 没有golden_inputs但有golden_outputs,直接返回输出 + return {"files": golden_outputs["files"]} + + # 如果没有预期输出,返回空结果 + return {"files": ""} + + def regex_search(self, inputs): + """正则搜索工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"matches": golden_outputs.get("matches", "[]")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "matches" in golden_outputs: + # 提取实际参数 + pattern = inputs.get("pattern") + file_id = inputs.get("file_id") + text = inputs.get("text") + + # 1. 检查必需参数 + if pattern is None: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["pattern"], + "message": "Missing required parameter 'pattern'" + } + } + + # 类型检查 + if not isinstance(pattern, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "pattern", + "message": "Parameter 'pattern' must be a string type" + } + } + if file_id is not None and not isinstance(file_id, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if text is not None and not isinstance(text, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "text", + "message": "Parameter 'text' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合 + provided_params = {} + if pattern is not None: + provided_params["pattern"] = pattern + if file_id is not None: + provided_params["file_id"] = file_id + if text is not None: + provided_params["text"] = text + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数(关键改进) + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_pattern = golden_inputs.get("pattern") + expected_file_id = golden_inputs.get("file_id") + expected_text = golden_inputs.get("text") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_pattern is not None: + if str(pattern) != str(expected_pattern): + incorrect_params.append("pattern") + else: + correct_params.append("pattern") + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_text is not None: + if str(text) != str(expected_text): + incorrect_params.append("text") + else: + correct_params.append("text") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "matches": "[]", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "matches": golden_outputs["matches"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空列表 + return {"matches": "[]"} + + def json_get(self, inputs): + """JSON 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"values": golden_outputs.get("values", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "values" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + jsonpath = inputs.get("jsonpath", "") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if jsonpath is not None and not isinstance(jsonpath, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "jsonpath", + "message": "Parameter 'jsonpath' must be a string type" + } + } + + # 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:jsonpath有默认值"") + provided_params = {} + if file_id is not None: + provided_params["file_id"] = file_id + if jsonpath != "": + provided_params["jsonpath"] = jsonpath + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_jsonpath = golden_inputs.get("jsonpath") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_jsonpath is not None: + if str(jsonpath) != str(expected_jsonpath): + incorrect_params.append("jsonpath") + else: + correct_params.append("jsonpath") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "values": "", + "_validation": validation_info + } + + # 所有验证通过,返回正确输出 + return { + "values": golden_outputs["values"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"values": ""} + + def csv_query(self, inputs): + """CSV 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"rows": golden_outputs.get("rows", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "rows" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + select_columns = inputs.get("select", "") + where_clause = inputs.get("where", "") + + # 1. 检查必需参数 + if file_id is None: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["file_id"], + "message": "Missing required parameter 'file_id'" + } + } + + # 类型检查 + if not isinstance(file_id, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if not isinstance(select_columns, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "select", + "message": "Parameter 'select' must be a string type" + } + } + if not isinstance(where_clause, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "where", + "message": "Parameter 'where' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:select和where有默认值"") + provided_params = {"file_id": file_id} + if select_columns != "": + provided_params["select"] = select_columns + if where_clause != "": + provided_params["where"] = where_clause + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_select = golden_inputs.get("select") + expected_where = golden_inputs.get("where") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_select is not None: + if str(select_columns) != str(expected_select): + incorrect_params.append("select") + else: + correct_params.append("select") + + if expected_where is not None: + if str(where_clause) != str(expected_where): + incorrect_params.append("where") + else: + correct_params.append("where") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "rows": "", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "rows": golden_outputs["rows"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"rows": ""} + + def graph_shortest_path(self, inputs): + """图最短路径工具 + + 如果有 _golden_outputs 或 _init_outputs,验证输入并返回预设输出。 + 否则执行真实的 Dijkstra 算法。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 检查是否在预设模式中(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + if golden_outputs and "path" in golden_outputs: + # 评测阶段但没有 golden_inputs,直接返回 outputs + if not golden_inputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 评测模式:验证输入参数是否匹配 golden 值 + src = inputs.get("src") + dst = inputs.get("dst") + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + + has_src = src is not None and src != "" + has_dst = dst is not None and dst != "" + + # 验证必需参数 + if not has_src or not has_dst: + missing = [] + if not has_src: + missing.append("src") + if not has_dst: + missing.append("dst") + return {"error": "Missing required parameters: " + ", ".join(missing)} + + # 类型检查 + if not isinstance(src, str): + return {"error": "Parameter 'src' must be a string"} + if not isinstance(dst, str): + return {"error": "Parameter 'dst' must be a string"} + + # 验证输入是否匹配期望值 + if golden_inputs: + expected_src = golden_inputs.get("src") + expected_dst = golden_inputs.get("dst") + expected_file_id = golden_inputs.get("file_id") + expected_graph_data = golden_inputs.get("graph_data") + + # 收集验证结果 + incorrect_params = [] + correct_params = [] + + # 检查必需参数是否匹配 + if expected_src is not None: + if str(src) != str(expected_src): + incorrect_params.append("src") + else: + correct_params.append("src") + + if expected_dst is not None: + if str(dst) != str(expected_dst): + incorrect_params.append("dst") + else: + correct_params.append("dst") + + # 检查可选参数(如果在 expected_inputs 中定义了) + if expected_file_id is not None: + if file_id != expected_file_id: + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_graph_data is not None: + if graph_data != expected_graph_data: + incorrect_params.append("graph_data") + else: + correct_params.append("graph_data") + + # 如果有参数不正确,返回详细的反馈 + if incorrect_params: + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 验证通过,返回预设的输出 + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 获取参数(真实执行路径) + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + # Support both src/dst (interface definition) and start/end (original implementation) + start = inputs.get("src") + end = inputs.get("dst") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + raise TypeError("file_id must be a string") + + if graph_data is not None and not isinstance(graph_data, str): + raise TypeError("graph_data must be a string") + + if start is not None and not isinstance(start, str): + raise TypeError("src/start must be a string") + + if end is not None and not isinstance(end, str): + raise TypeError("dst/end must be a string") + + # 检查必需参数 + if file_id is None and graph_data is None: + raise ValueError("Either file_id or graph_data must be provided") + + if start is None: + raise ValueError("src/start parameter is required") + + if end is None: + raise ValueError("dst/end parameter is required") + + # Get graph content + content = None + if file_id is not None: + # 尝试从 VFS 获取(如果存在) + if hasattr(self, 'vfs') and file_id in self.vfs: + content = self.vfs[file_id] + else: + # VFS 不存在或文件不在 VFS 中 + # 返回一个默认的空图结果,或者抛出错误提示需要 init_outputs + raise ValueError( + f"File '{file_id}' not found. For tools that require files, " + f"please provide init_outputs in the initial_values." + ) + elif graph_data is not None: + content = graph_data + + if content is None: + content = "{}" + + try: + # Parse graph data + graph = json.loads(content) + + # 类型检查 + if not isinstance(graph, dict): + raise TypeError("Graph data must be a dictionary") + + # If graph is not in the expected format, try to extract adjacency list + if "nodes" in graph and "edges" in graph: + # 验证nodes和edges的类型 + if not isinstance(graph["nodes"], list): + raise TypeError("Nodes must be a list") + + if not isinstance(graph["edges"], list): + raise TypeError("Edges must be a list") + + # Convert from nodes/edges format to adjacency list + adjacency_list = {} + for node in graph["nodes"]: + # 验证node类型 + if not isinstance(node, dict): + raise TypeError("Each node must be a dictionary") + + # Use node ID as key, not the entire node dictionary + node_id = node.get("id", "") + if node_id: + adjacency_list[node_id] = {} + + for edge in graph["edges"]: + # 验证edge类型 + if not isinstance(edge, dict): + raise TypeError("Each edge must be a dictionary") + + u = edge["from"] + v = edge["to"] + weight = edge.get("weight", 1) # Default to unweighted + + # 类型检查 + if not isinstance(u, str): + raise TypeError("Edge 'from' must be a string") + + if not isinstance(v, str): + raise TypeError("Edge 'to' must be a string") + + if not isinstance(weight, (int, float)): + raise TypeError("Edge weight must be a number") + + if u not in adjacency_list: + adjacency_list[u] = {} + if v not in adjacency_list: + adjacency_list[v] = {} + + adjacency_list[u][v] = weight + # If undirected, add reverse edge + if not edge.get("directed", False): + adjacency_list[v][u] = weight + elif isinstance(graph, dict): + # Already in adjacency list format + adjacency_list = graph + + # 验证邻接表结构 + for node, neighbors in adjacency_list.items(): + if not isinstance(neighbors, dict): + raise TypeError("Adjacency list must be a dictionary of dictionaries") + + for neighbor, weight in neighbors.items(): + if not isinstance(weight, (int, float)): + raise TypeError("Edge weights must be numbers") + else: + raise TypeError("Graph data must be a dictionary") + + # 检查起点和终点是否为空 + if not start: + raise ValueError("Start node cannot be empty") + + if not end: + raise ValueError("End node cannot be empty") + + # 检查起点和终点是否在图中 + if start not in adjacency_list: + raise ValueError(f"Start node '{start}' not found in graph") + + if end not in adjacency_list: + raise ValueError(f"End node '{end}' not found in graph") + + # Dijkstra's algorithm implementation + import heapq + + # Initialize distances and previous nodes + distances = {node: float('infinity') for node in adjacency_list} + previous = {node: None for node in adjacency_list} + distances[start] = 0 + + # Priority queue + pq = [(0, start)] + heapq.heapify(pq) + + while pq: + current_dist, current_node = heapq.heappop(pq) + + # If we've reached the end node, we can break early + if current_node == end: + break + + # Nodes can be added multiple times to the priority queue, but we only process them once + if current_dist > distances[current_node]: + continue + + # Explore neighbors + for neighbor, weight in adjacency_list[current_node].items(): + distance = current_dist + weight + + # If a shorter path is found + if distance < distances[neighbor]: + distances[neighbor] = distance + previous[neighbor] = current_node + heapq.heappush(pq, (distance, neighbor)) + + # Reconstruct the shortest path + path = [] + current = end + while current is not None: + path.append(current) + current = previous[current] + path.reverse() # Reverse to get from start to end + + # Check if path exists + if not path or path[0] != start: + return {"path": "[]", "cost": 0} + + return { + "path": json.dumps(path), + "cost": distances[end] + } + except json.JSONDecodeError as e: + raise ValueError(f"Invalid JSON in graph data: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in graph_shortest_path: {str(e)}") + + # --- Crypto (Simplified) --- + def crypto_aes_cbc_decrypt(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 (使用模板中定义的参数名) + hex_cipher = inputs.get("hex_cipher") + hex_key = inputs.get("hex_key") + hex_iv = inputs.get("hex_iv") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + + if hex_key is not None and not isinstance(hex_key, str): + raise TypeError("hex_key must be a string") + + if hex_iv is not None and not isinstance(hex_iv, str): + raise TypeError("hex_iv must be a string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + + if hex_key is None: + raise ValueError("hex_key parameter is required") + + if hex_iv is None: + raise ValueError("hex_iv parameter is required") + + from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes + from cryptography.hazmat.backends import default_backend + from cryptography.hazmat.primitives import padding + + try: + # Convert hex strings to bytes + ciphertext = bytes.fromhex(hex_cipher) + key = bytes.fromhex(hex_key) + iv = bytes.fromhex(hex_iv) + + # Validate key length (AES-128, AES-192, AES-256) + if len(key) not in [16, 24, 32]: + raise ValueError("Invalid key length. Must be 16, 24, or 32 bytes.") + + if len(iv) != 16: + raise ValueError("Invalid IV length. Must be 16 bytes.") + + # Create cipher object + cipher = Cipher( + algorithms.AES(key), + modes.CBC(iv), + backend=default_backend() + ) + + decryptor = cipher.decryptor() + + # Decrypt the ciphertext + padded_plaintext = decryptor.update(ciphertext) + decryptor.finalize() + + # Remove PKCS7 padding + unpadder = padding.PKCS7(128).unpadder() + plaintext = unpadder.update(padded_plaintext) + unpadder.finalize() + + # Return decrypted text + return {"text": plaintext.decode('utf-8', errors='ignore')} + except ValueError as e: + if "non-hexadecimal number found in fromhex()" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher, hex_key, or hex_iv") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in crypto_aes_cbc_decrypt: {str(e)}") + + def crypto_rsa_decrypt_hex(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_cipher = inputs.get("hex_cipher") + n = inputs.get("n") + d = inputs.get("d") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + if n is not None and not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + if d is not None and not isinstance(d, (int, str)): + raise TypeError("d must be an integer or string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + if n is None: + raise ValueError("n parameter is required") + if d is None: + raise ValueError("d parameter is required") + + try: + # Convert parameters to appropriate types + cipher_int = int(hex_cipher, 16) + n_int = int(n) if isinstance(n, str) else n + d_int = int(d) if isinstance(d, str) else d + + # RSA decryption: plaintext = ciphertext^d mod n + plaintext_int = pow(cipher_int, d_int, n_int) + + # Convert result to hex and then to text + plaintext_hex = hex(plaintext_int)[2:] + + # Pad with leading zero if odd length + if len(plaintext_hex) % 2 != 0: + plaintext_hex = '0' + plaintext_hex + + # Convert hex to bytes and then to text + try: + plaintext_bytes = bytes.fromhex(plaintext_hex) + plaintext_text = plaintext_bytes.decode('utf-8', errors='ignore') + except: + # If decoding fails, return hex representation + plaintext_text = plaintext_hex + + return {"text": plaintext_text} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in crypto_rsa_decrypt_hex: {str(e)}") + + # --- Others --- + def num_base_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + s = inputs.get("s") + from_base = inputs.get("from_base") + to_base = inputs.get("to_base") + + # 类型检查 - 接受 str 或 int + if s is not None and not isinstance(s, (str, int)): + raise TypeError("s must be a string or integer") + + if from_base is not None and not isinstance(from_base, (int, str)): + raise TypeError("from_base must be an integer") + + if to_base is not None and not isinstance(to_base, (int, str)): + raise TypeError("to_base must be an integer") + + # 检查必需参数 + if s is None: + raise ValueError("s parameter is required") + + if from_base is None: + raise ValueError("from_base parameter is required") + + if to_base is None: + raise ValueError("to_base parameter is required") + + try: + # Convert to int if needed + from_base = int(from_base) if isinstance(from_base, str) else from_base + to_base = int(to_base) if isinstance(to_base, str) else to_base + s_str = str(s) + + # 验证基数范围 + if from_base < 2 or from_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + if to_base < 2 or to_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + # Convert from source base to decimal + val = int(s_str, from_base) + + # Convert from decimal to target base + if to_base == 10: + result = str(val) + elif to_base == 16: + result = hex(val)[2:] + elif to_base == 8: + result = oct(val)[2:] + elif to_base == 2: + result = bin(val)[2:] + else: + # Generic base conversion for other bases + if val == 0: + result = "0" + else: + digits = "0123456789abcdefghijklmnopqrstuvwxyz" + result = "" + n = abs(val) + while n: + result = digits[n % to_base] + result + n //= to_base + if val < 0: + result = "-" + result + + return {"str": result} + except ValueError as e: + raise ValueError(f"Invalid number format: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in num_base_convert: {str(e)}") + + def time_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iso = inputs.get("iso") + timestamp = inputs.get("timestamp") + datetime_str = inputs.get("datetime") + from_tz = inputs.get("from_tz") + to_tz = inputs.get("to_tz") + format_str = inputs.get("format") + + # 类型检查 + if iso is not None and not isinstance(iso, str): + raise TypeError("iso must be a string") + + if timestamp is not None and not isinstance(timestamp, (str, int, float)): + raise TypeError("timestamp must be a string, integer, or float") + + if datetime_str is not None and not isinstance(datetime_str, str): + raise TypeError("datetime must be a string") + + if from_tz is not None and not isinstance(from_tz, str): + raise TypeError("from_tz must be a string") + + if to_tz is not None and not isinstance(to_tz, str): + raise TypeError("to_tz must be a string") + + if format_str is not None and not isinstance(format_str, str): + raise TypeError("format must be a string") + + # 设置默认值 + if from_tz is None: + from_tz = "UTC" + + if to_tz is None: + to_tz = "UTC" + + import datetime + import pytz + + # 验证时区参数 + try: + if from_tz: + pytz.timezone(from_tz) + if to_tz: + pytz.timezone(to_tz) + except Exception: + raise ValueError("Invalid timezone provided") + + try: + # Parse input time + dt = None + + if iso is not None: + # Parse ISO 8601 format + dt = datetime.datetime.fromisoformat(iso.replace('Z', '+00:00')) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=pytz.UTC) + elif timestamp is not None: + # Parse Unix timestamp + timestamp = float(timestamp) + dt = datetime.datetime.fromtimestamp(timestamp, pytz.UTC) + elif datetime_str is not None: + # Parse datetime string + # Try common formats + formats_to_try = [ + "%Y-%m-%d %H:%M:%S", + "%Y-%m-%d %H:%M:%S.%f", + "%Y-%m-%d", + "%m/%d/%Y %H:%M:%S", + "%m/%d/%Y" + ] + + parse_success = False + for fmt in formats_to_try: + try: + dt = datetime.datetime.strptime(datetime_str, fmt) + dt = pytz.timezone(from_tz).localize(dt) + parse_success = True + break + except ValueError: + continue + + if not parse_success: + raise ValueError("Unable to parse datetime string with common formats") + else: + # 如果没有提供任何时间参数,则使用当前时间 + dt = datetime.datetime.now(pytz.UTC) + except ValueError as e: + raise ValueError(f"Error parsing time input: {str(e)}") + except Exception as e: + raise RuntimeError(f"Unexpected error parsing time input: {str(e)}") + + try: + # Convert timezone + if from_tz != to_tz: + dt = dt.astimezone(pytz.timezone(to_tz)) + + # Format outputs + result = { + "iso": dt.isoformat(), + "timestamp": str(dt.timestamp()), + "datetime": dt.strftime("%Y-%m-%d %H:%M:%S"), + "date": dt.strftime("%Y-%m-%d"), + "time": dt.strftime("%H:%M:%S"), + "timezone": to_tz + } + + # Add custom format if requested + if format_str: + try: + result["formatted"] = dt.strftime(format_str) + except ValueError as e: + raise ValueError(f"Invalid format string: {str(e)}") + + return result + except Exception as e: + raise RuntimeError(f"Error in time_convert: {str(e)}") + + def checksum_crc32(self, inputs): + import zlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("hex must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("hex parameter is required") + + try: + # 验证十六进制字符串 + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空 + if not hex_data: + raise ValueError("hex data cannot be empty") + + # 检查是否为有效的十六进制字符串 + if not all(c in "0123456789abcdefABCDEF" for c in hex_data): + raise ValueError("hex must be a valid hexadecimal string") + + # 检查长度是否为偶数 + if len(hex_data) % 2 != 0: + raise ValueError("hex must have even number of characters") + + val = zlib.crc32(bytes.fromhex(hex_data)) + # 确保 hex 输出是 8 位,前导补 0 + return {"hex": f"{val:08x}", "int": val} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in checksum_crc32: {str(e)}") + + def geo_haversine(self, inputs): + import math + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + lat1 = inputs.get("lat1") + lon1 = inputs.get("lon1") + lat2 = inputs.get("lat2") + lon2 = inputs.get("lon2") + + # 类型检查 + if lat1 is not None and not isinstance(lat1, (int, float, str)): + raise TypeError("lat1 must be a number or string") + if lon1 is not None and not isinstance(lon1, (int, float, str)): + raise TypeError("lon1 must be a number or string") + if lat2 is not None and not isinstance(lat2, (int, float, str)): + raise TypeError("lat2 must be a number or string") + if lon2 is not None and not isinstance(lon2, (int, float, str)): + raise TypeError("lon2 must be a number or string") + + # 检查必需参数 + if lat1 is None: + raise ValueError("lat1 parameter is required") + if lon1 is None: + raise ValueError("lon1 parameter is required") + if lat2 is None: + raise ValueError("lat2 parameter is required") + if lon2 is None: + raise ValueError("lon2 parameter is required") + + try: + # 转换为浮点数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(lat1, str): + lat1 = float(lat1) + elif not isinstance(lat1, (int, float)): + raise TypeError("lat1 must be a number or string") + else: + lat1 = float(lat1) + + if isinstance(lon1, str): + lon1 = float(lon1) + elif not isinstance(lon1, (int, float)): + raise TypeError("lon1 must be a number or string") + else: + lon1 = float(lon1) + + if isinstance(lat2, str): + lat2 = float(lat2) + elif not isinstance(lat2, (int, float)): + raise TypeError("lat2 must be a number or string") + else: + lat2 = float(lat2) + + if isinstance(lon2, str): + lon2 = float(lon2) + elif not isinstance(lon2, (int, float)): + raise TypeError("lon2 must be a number or string") + else: + lon2 = float(lon2) + + # Validate coordinates (approximate range check) + if not (-90 <= lat1 <= 90): + raise ValueError("lat1 must be between -90 and 90") + if not (-90 <= lat2 <= 90): + raise ValueError("lat2 must be between -90 and 90") + if not (-180 <= lon1 <= 180): + raise ValueError("lon1 must be between -180 and 180") + if not (-180 <= lon2 <= 180): + raise ValueError("lon2 must be between -180 and 180") + + # Earth radius in meters + R = 6371000 # Approximate radius of Earth + + # Convert degrees to radians + lat1_rad = math.radians(lat1) + lon1_rad = math.radians(lon1) + lat2_rad = math.radians(lat2) + lon2_rad = math.radians(lon2) + + # Calculate differences + delta_lat = lat2_rad - lat1_rad + delta_lon = lon2_rad - lon1_rad + + # Haversine formula + a = math.sin(delta_lat / 2) ** 2 + \ + math.cos(lat1_rad) * math.cos(lat2_rad) * \ + math.sin(delta_lon / 2) ** 2 + c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) + distance_m = R * c + + # Return distance in meters + return {"meters": round(distance_m, 2)} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in geo_haversine: {str(e)}") + + def otp_totp_generate(self, inputs): + import hmac + import hashlib + import base64 + import time + import struct + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + base32_secret = inputs.get("base32_secret") + step = inputs.get("step", 30) # Default to 30 seconds + digits = inputs.get("digits", 6) # Default to 6 digits + timestamp_iso = inputs.get("timestamp_iso", "") + algo = inputs.get("algo", "sha1") # Default to sha1 as current implementation only supports this + + # 类型检查 + if base32_secret is not None and not isinstance(base32_secret, str): + raise TypeError("base32_secret must be a string") + if not isinstance(step, (int, str)): + raise TypeError("step must be an integer or string") + if not isinstance(digits, (int, str)): + raise TypeError("digits must be an integer or string") + if not isinstance(timestamp_iso, str): + raise TypeError("timestamp_iso must be a string") + if not isinstance(algo, str): + raise TypeError("algo must be a string") + + # 检查必需参数 + if base32_secret is None: + raise ValueError("base32_secret parameter is required") + + try: + # Convert step and digits to appropriate types + step = int(step) + digits = int(digits) + if digits < 6 or digits > 8: + raise ValueError("Digits must be between 6 and 8") + + # Convert timestamp_iso to integer timestamp + if timestamp_iso: + import datetime + dt = datetime.datetime.fromisoformat(timestamp_iso.replace('Z', '+00:00')) + timestamp = int(dt.timestamp()) + else: + timestamp = int(time.time()) + + # Calculate counter value (T = floor(timestamp / step)) + counter = timestamp // step + + # Decode the base32 secret + # Add padding if necessary (base64 requires padding to be multiple of 8) + base32_secret = base32_secret.upper().replace(' ', '') + if len(base32_secret) % 8 != 0: + base32_secret += '=' * (8 - (len(base32_secret) % 8)) + key = base64.b32decode(base32_secret, casefold=True) + + # Calculate HMAC-SHA1 + counter_bytes = struct.pack('>Q', counter) # Big-endian 8-byte integer + hmac_hash = hmac.new(key, counter_bytes, hashlib.sha1).digest() + + # Dynamic truncation + offset = hmac_hash[-1] & 0xF + code = struct.unpack('>I', hmac_hash[offset:offset+4])[0] & 0x7FFFFFFF + + # Generate the OTP + otp = str(code % (10 ** digits)).zfill(digits) + + # Calculate remaining time until next OTP change + remaining_time = step - (timestamp % step) + + return {"totp": otp, "remaining_time": remaining_time, "time_step": step} + except ValueError as e: + if "invalid literal for int()" in str(e): + raise ValueError("step and digits must be valid integers") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in otp_totp_generate: {str(e)}") + + def unicode_norm(self, inputs): + import unicodedata + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + form = inputs.get("form", "NFC") # Default to NFC + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if form is not None and not isinstance(form, str): + raise TypeError("form must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Normalize form (NFC, NFD, NFKC, NFKD) + form = form.upper().strip() + + if form not in ['NFC', 'NFD', 'NFKC', 'NFKD']: + raise ValueError(f"Invalid normalization form: {form}. Must be one of: NFC, NFD, NFKC, NFKD") + + # Apply Unicode normalization + normalized_text = unicodedata.normalize(form, text) + + return {"text": normalized_text} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in unicode_norm: {str(e)}") + + def text_bidi_sanitize(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Bidi control characters to remove + bidi_controls = [ + '\u200E', # LEFT-TO-RIGHT MARK + '\u200F', # RIGHT-TO-LEFT MARK + '\u202A', # LEFT-TO-RIGHT EMBEDDING + '\u202B', # RIGHT-TO-LEFT EMBEDDING + '\u202C', # POP DIRECTIONAL FORMATTING + '\u202D', # LEFT-TO-RIGHT OVERRIDE + '\u202E', # RIGHT-TO-LEFT OVERRIDE + '\u2066', # LEFT-TO-RIGHT ISOLATE + '\u2067', # RIGHT-TO-LEFT ISOLATE + '\u2068', # FIRST STRONG ISOLATE + '\u2069', # POP DIRECTIONAL ISOLATE + ] + + # Remove all Bidi control characters + sanitized_text = text + for control_char in bidi_controls: + sanitized_text = sanitized_text.replace(control_char, '') + + return {"text": sanitized_text} + except Exception as e: + raise RuntimeError(f"Error in text_bidi_sanitize: {str(e)}") + + def text_xor_hex(self, inputs): + import binascii + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_a = inputs.get("hex_a") + hex_b = inputs.get("hex_b") + + # 类型检查 + if hex_a is not None and not isinstance(hex_a, str): + raise TypeError("hex_a must be a string") + if hex_b is not None and not isinstance(hex_b, str): + raise TypeError("hex_b must be a string") + + # 检查必需参数 + if hex_a is None: + raise ValueError("hex_a parameter is required") + if hex_b is None: + raise ValueError("hex_b parameter is required") + + try: + # Remove any whitespace + hex_a = hex_a.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + hex_b = hex_b.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + + # Validate hex strings + if not (all(c in "0123456789abcdefABCDEF" for c in hex_a) and len(hex_a) % 2 == 0): + raise ValueError("hex_a must be a valid hexadecimal string with even length") + if not (all(c in "0123456789abcdefABCDEF" for c in hex_b) and len(hex_b) % 2 == 0): + raise ValueError("hex_b must be a valid hexadecimal string with even length") + + # Convert hex strings to bytes + bytes_a = binascii.unhexlify(hex_a) + bytes_b = binascii.unhexlify(hex_b) + + # Make the byte arrays the same length by padding the shorter one with zeros + max_len = max(len(bytes_a), len(bytes_b)) + bytes_a = bytes_a.ljust(max_len, b'\x00') + bytes_b = bytes_b.ljust(max_len, b'\x00') + + # Perform XOR operation + result_bytes = bytes(a ^ b for a, b in zip(bytes_a, bytes_b)) + + # Convert result back to hex + result_hex = binascii.hexlify(result_bytes).decode('utf-8') + + return {"hex": result_hex} + except ValueError as e: + if "Non-hexadecimal digit found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in text_xor_hex: {str(e)}") + + def text_rotN(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + n = inputs.get("n", 0) + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + n = int(n) + except ValueError: + raise ValueError("n must be a valid integer") + + result = [] + for char in text: + if char.isupper(): + # Rotate uppercase letters + result_char = chr((ord(char) - ord('A') + n) % 26 + ord('A')) + result.append(result_char) + elif char.islower(): + # Rotate lowercase letters + result_char = chr((ord(char) - ord('a') + n) % 26 + ord('a')) + result.append(result_char) + else: + # Keep non-alphabetic characters unchanged + result.append(char) + + return {"text": ''.join(result)} + + def luhn_check(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数(支持 card_number 和 number 两个参数名) + card_number = inputs.get("number") or inputs.get("card_number") + + # 类型检查 + if card_number is not None and not isinstance(card_number, str): + raise TypeError("number must be a string") + + # 检查必需参数 + if card_number is None: + raise ValueError("number parameter is required") + + try: + # 如果输入是JSON数组或其他非数字字符串,返回该字符串本身(用于数据传递) + # 这种情况发生在DAG设计中类型不匹配时 + if card_number.startswith('[') or card_number.startswith('{'): + # 输入是JSON,直接返回原值(用于传递) + return {"valid": card_number} + + # Remove whitespace from card number + card_number = card_number.replace(" ", "").replace("-", "") + + # Check if card number is all digits + if not card_number.isdigit() or len(card_number) < 13: + return {"valid": "false"} + + # Implement Luhn algorithm + total = 0 + reverse_digits = card_number[::-1] # Reverse the number for easier processing + + for i, digit in enumerate(reverse_digits): + num = int(digit) + if i % 2 == 1: # Every second digit starting from the right (which is first in reversed string) + num *= 2 + if num > 9: + num -= 9 # Equivalent to sum of digits for 2-digit numbers + total += num + + # Check if total is divisible by 10 + is_valid = total % 10 == 0 + return {"valid": "true" if is_valid else "false"} + except Exception as e: + raise RuntimeError(f"Error in luhn_check: {str(e)}") + + def iban_validate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iban = inputs.get("iban") + + # 类型检查 + if iban is not None and not isinstance(iban, str): + raise TypeError("iban must be a string") + + # 检查必需参数 + if iban is None: + raise ValueError("iban parameter is required") + + try: + # Remove whitespace from IBAN + iban = iban.replace(" ", "") + + # Basic length and format check + if not (len(iban) >= 15 and len(iban) <= 34): + return {"valid": "False"} + + if not (iban[:2].isalpha() and iban[2:].isdigit()): + return {"valid": "False"} + + # Move first four characters to the end + rearranged = iban[4:] + iban[:4] + + # Replace letters with numbers (A=10, B=11, ..., Z=35) + numeric_iban = '' + for char in rearranged: + if char.isdigit(): + numeric_iban += char + else: + numeric_iban += str(ord(char.upper()) - ord('A') + 10) + + # Perform modulo 97 check + # Use step-by-step approach for very large numbers + remainder = 0 + for char in numeric_iban: + remainder = (remainder * 10 + int(char)) % 97 + + is_valid = remainder == 1 + return {"valid": "True" if is_valid else "False"} + except Exception as e: + raise RuntimeError(f"Error in iban_validate: {str(e)}") + + def matter_synthesizer(self, inputs): + import hashlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + blueprint = inputs.get("blueprint") + + # 类型检查 + if blueprint is not None and not isinstance(blueprint, str): + raise TypeError("blueprint must be a string") + + try: + # Get blueprint parameter as defined in interface + if blueprint is None: + blueprint = "" + + # Generate a unique item ID based on the blueprint + # This ensures the same blueprint always produces the same item + blueprint_hash = hashlib.sha256(blueprint.encode()).hexdigest()[:16] + + # Create a synthesized item with a deterministic ID based on blueprint + synthesized_item = f"synthesized_item_{blueprint_hash}" + + return {"output_slot": synthesized_item} + except Exception as e: + raise RuntimeError(f"Error in matter_synthesizer: {str(e)}") + + # --- Terminal Implementations --- + def terminal_1(self, inputs): + """ + terminal_1: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 只返回 text_output + - 只输入正确的 slot_b → 只返回 hex_output + - 同时输入正确的 slot_a 和 slot_b → 返回 item_dispenser(物品掉落) + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + # 检查哪些输入被提供了 + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值是否正确(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + expected_a = golden_inputs["slot_a"] + a_valid = str(slot_a) == str(expected_a) + + if has_b and "slot_b" in golden_inputs: + expected_b = golden_inputs["slot_b"] + b_valid = str(slot_b) == str(expected_b) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 item_dispenser + if has_a and has_b: + if a_valid and b_valid: + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 text_output + if has_a and not has_b: + if a_valid: + if "text_output" in golden_outputs: + result["text_output"] = golden_outputs["text_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 hex_output + if has_b and not has_a: + if b_valid: + if "hex_output" in golden_outputs: + result["hex_output"] = golden_outputs["hex_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def terminal_2(self, inputs): + """ + terminal_2: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 text_result + - 同时输入正确的 num1 和 num2 → 返回 hex_result 和 math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + # 检查哪些输入被提供了 + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值是否正确(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + expected_num1 = golden_inputs["num1"] + num1_valid = str(num1) == str(expected_num1) + + if has_num2 and "num2" in golden_inputs: + expected_num2 = golden_inputs["num2"] + num2_valid = str(num2) == str(expected_num2) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 hex_result 和 math_token + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 text_result + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "text_result" in golden_outputs: + result["text_result"] = golden_outputs["text_result"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def logic_terminal(self, inputs): + """ + Logic Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 返回 screen(部分输出) + - 只输入正确的 slot_b → 返回 screen 和 secondary_output + - 同时输入正确的 slot_a 和 slot_b → 返回 screen, secondary_output, item_dispenser + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + a_valid = str(slot_a) == str(golden_inputs["slot_a"]) + + if has_b and "slot_b" in golden_inputs: + b_valid = str(slot_b) == str(golden_inputs["slot_b"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出(包括 item_dispenser) + if has_a and has_b: + if a_valid and b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 screen(部分输出) + if has_a and not has_b: + if a_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 screen 和 secondary_output + if has_b and not has_a: + if b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def math_terminal(self, inputs): + """ + Math Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 result_display + - 同时输入正确的 num1 和 num2 → 返回 result_display, hex_result, math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + num1_valid = str(num1) == str(golden_inputs["num1"]) + + if has_num2 and "num2" in golden_inputs: + num2_valid = str(num2) == str(golden_inputs["num2"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 result_display + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def crypt_terminal(self, inputs): + """ + Encryption Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 plaintext → 返回 status(部分输出) + - 同时输入正确的 plaintext 和 key → 返回 status, encrypted_hex, encryption_chip + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + plaintext = inputs.get("plaintext") + key = inputs.get("key") + + has_plaintext = plaintext is not None and plaintext != "" + has_key = key is not None and key != "" + + # 验证输入值(与 golden values 比较) + plaintext_valid = False + key_valid = False + + if has_plaintext and "plaintext" in golden_inputs: + plaintext_valid = str(plaintext) == str(golden_inputs["plaintext"]) + + if has_key and "key" in golden_inputs: + key_valid = str(key) == str(golden_inputs["key"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_plaintext and has_key: + if plaintext_valid and key_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + if "encrypted_hex" in golden_outputs: + result["encrypted_hex"] = golden_outputs["encrypted_hex"] + if "encryption_chip" in golden_outputs: + result["encryption_chip"] = golden_outputs["encryption_chip"] + return result + else: + incorrect_params = [] + correct_params = [] + if not plaintext_valid: + incorrect_params.append("plaintext") + else: + correct_params.append("plaintext") + if not key_valid: + incorrect_params.append("key") + else: + correct_params.append("key") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 plaintext 且正确 → 返回 status(部分输出) + if has_plaintext and not has_key: + if plaintext_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: plaintext"} + + # 只提供 key 但没有 plaintext + if has_key and not has_plaintext: + return {"error": "plaintext required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + def sequence_terminal(self, inputs): + """ + Sequence Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 sequence → 返回 verification(部分输出) + - 同时输入正确的 sequence 和 checksum → 返回 verification, auth_code, access_card + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + sequence = inputs.get("sequence") + checksum = inputs.get("checksum") + + has_sequence = sequence is not None and sequence != "" + has_checksum = checksum is not None and checksum != "" + + # 验证输入值(与 golden values 比较) + sequence_valid = False + checksum_valid = False + + if has_sequence and "sequence" in golden_inputs: + sequence_valid = str(sequence) == str(golden_inputs["sequence"]) + + if has_checksum and "checksum" in golden_inputs: + checksum_valid = str(checksum) == str(golden_inputs["checksum"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_sequence and has_checksum: + if sequence_valid and checksum_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + if "auth_code" in golden_outputs: + result["auth_code"] = golden_outputs["auth_code"] + if "access_card" in golden_outputs: + result["access_card"] = golden_outputs["access_card"] + return result + else: + incorrect_params = [] + correct_params = [] + if not sequence_valid: + incorrect_params.append("sequence") + else: + correct_params.append("sequence") + if not checksum_valid: + incorrect_params.append("checksum") + else: + correct_params.append("checksum") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 sequence 且正确 → 返回 verification(部分输出) + if has_sequence and not has_checksum: + if sequence_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: sequence"} + + # 只提供 checksum 但没有 sequence + if has_checksum and not has_sequence: + return {"error": "sequence required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + # --- Additional File Tools --- + + def zip_unzip_file(self, inputs): + """ZIP 解压文件工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def zip_unzip_item(self, inputs): + """ZIP 解压道具工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def code_py_exec(self, inputs): + """Python 代码执行工具 + + 这是一个真实执行的工具,在 DAG 生成阶段和运行时评测阶段都会执行代码。 + 输入: code (Python 代码字符串) + 输出: stdout (标准输出,包含执行结果和错误信息) + + 特殊行为: + - 如果代码定义了 main() 函数,会自动调用它 + - 如果执行出错,错误信息会包含在 stdout 中 + """ + code = inputs.get("code", "") + + if not code: + return {"stdout": "Error: No code provided"} + + try: + # 创建一个受限的执行环境 + import io + import sys + + # 捕获标准输出和标准错误 + old_stdout = sys.stdout + old_stderr = sys.stderr + sys.stdout = io.StringIO() + sys.stderr = io.StringIO() + + # 执行代码 + exec_globals = {"__builtins__": __builtins__} + exec_locals = {} + exec(code, exec_globals, exec_locals) + + # 如果定义了 main() 函数,自动调用它 + if 'main' in exec_locals and callable(exec_locals['main']): + exec_locals['main']() + + # 获取输出 + stdout_value = sys.stdout.getvalue() + stderr_value = sys.stderr.getvalue() + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 合并 stdout 和 stderr + output = stdout_value + if stderr_value: + output += ("\n" if output else "") + f"[stderr] {stderr_value}" + + # 如果没有任何输出,尝试返回 result 变量的值 + if not output: + result = exec_locals.get("_result") or exec_locals.get("result") + if result is not None: + output = str(result) + + return {"stdout": output if output else "(no output)"} + + except Exception as e: + # 恢复标准输出和错误输出 + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 返回错误信息 + return {"stdout": f"Error: {type(e).__name__}: {str(e)}"} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-3597bfa8/environment/puzzle/worker.Dockerfile b/tasks/agentescape-25-skeleton-3597bfa8/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-25-skeleton-3597bfa8/environment/puzzle/worker.Dockerfile @@ -0,0 +1,8 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends libseccomp2 && rm -rf /var/lib/apt/lists/* +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY worker.py child.py /app/ +COPY upstream/simulator.py /app/simulator.py +CMD ["uvicorn", "worker:app", "--host", "0.0.0.0", "--port", "8001", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-25-skeleton-3597bfa8/environment/puzzle/worker.py b/tasks/agentescape-25-skeleton-3597bfa8/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3597bfa8/environment/puzzle/worker.py @@ -0,0 +1,73 @@ +"""Stateless Python tool worker. Never receives a scenario or reference values.""" + +import json +import os +import signal +import subprocess +import sys +import tempfile +import threading + +from fastapi import FastAPI +from pydantic import BaseModel, ConfigDict + +app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) +lock = threading.Lock() + + +class Execution(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + code: str + + +@app.get("/health") +def health(): + return {"ok": True} + + +@app.post("/execute") +def execute(request: Execution): + if len(request.code.encode()) > 65536: + return {"stdout": "Error: code exceeds 64 KiB limit"} + with lock, tempfile.TemporaryDirectory(prefix="escape-code-") as directory: + os.chown(directory, 65534, 65534) + with tempfile.TemporaryFile() as output: + process = subprocess.Popen( + [sys.executable, "-I", "/app/child.py"], + stdin=subprocess.PIPE, + stdout=output, + stderr=subprocess.DEVNULL, + cwd=directory, + user=65534, + group=65534, + extra_groups=[], + start_new_session=True, + env={"PATH": "/usr/local/bin:/usr/bin:/bin"}, + ) + try: + process.communicate( + json.dumps({"code": request.code}).encode(), timeout=5 + ) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + return {"stdout": "Error: Python execution timed out"} + finally: + # Also remove children still in the process group after normal exit. + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + output.seek(0) + value = output.read(65537) + if len(value) > 65536 or process.returncode != 0: + return { + "stdout": "Error: Python execution exceeded a resource limit or failed" + } + try: + result = json.loads(value) + if not isinstance(result.get("stdout"), str): + raise ValueError("Invalid worker response") + return result + except (ValueError, AttributeError): + return {"stdout": "Error: Python execution returned invalid output"} diff --git a/tasks/agentescape-25-skeleton-3597bfa8/instruction.md b/tasks/agentescape-25-skeleton-3597bfa8/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3597bfa8/instruction.md @@ -0,0 +1,18 @@ +# Escape the room + +Discover the victory string and submit it with `escape submit-answer`. +Start with `escape observe`. This returns the room, available information, visible entities, and victory node ID. + +Use these commands (JSON responses): + +```sh +escape investigate NODE_ID +escape tool-call NODE_ID --arguments-json '{"parameter": "value"}' +escape use-item NODE_ID --arguments-json '{"parameter": "value"}' +escape submit-answer 'exact victory string' +escape state +``` + +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. + +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. diff --git a/tasks/agentescape-25-skeleton-3597bfa8/solution/oracle.py b/tasks/agentescape-25-skeleton-3597bfa8/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3597bfa8/solution/oracle.py @@ -0,0 +1,133 @@ +"""Reference solver: use trusted inputs, but obtain the answer through public actions.""" + +import json +import urllib.request +from pathlib import Path + + +def http_action(base_url, payload): + request = urllib.request.Request( + base_url + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(request, timeout=30) as response: + return json.load(response) + + +def solve(scenario, act, observe): + nodes = {node["id"]: node for node in scenario["nodes"]} + visible = {entity["id"] for entity in observe["available_entities"]} + solved = set() + seen_outputs = {} + action_count = 0 + + def call(payload): + nonlocal action_count + action_count += 1 + response = act(payload) + visible.update(entity["id"] for entity in response.get("newly_revealed", [])) + if ( + response.get("episode", {}).get("termination_reason") + == "infrastructure_error" + ): + raise RuntimeError("Infrastructure failure") + return response + + for _round in range(len(nodes) + 2): + progress = False + for node_id, node in nodes.items(): + if node_id not in visible or node_id in solved: + continue + # Preserve graph order for data inputs; trigger/drop edges express visibility. + predecessors = [ + edge["source_id"] + for edge in scenario["edges"] + if edge["target_id"] == node_id + and edge["connection_type"] not in ("Item", "Hidden_Item") + ] + if any(pred not in solved for pred in predecessors): + continue + info = call({"action": "investigate", "node_id": node_id}) + if not info.get("ok"): + raise RuntimeError(f"Investigation failed: {node_id}: {info}") + inputs = { + port["name"]: port["value"] + for port in node.get("inputs", []) + if "value" in port + } + if node["type"] == "Tool": + result = call( + {"action": "tool_call", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok") or result.get("output_values", {}).get("error"): + raise RuntimeError(f"Tool failed: {node_id}: {result}") + output = result.get("output_values", {}) + if node.get("template_id") in ("terminal_1", "terminal_2"): + slots = { + port["name"]: inputs[port["name"]] + for port in node["inputs"] + if port["type"] not in ("Item", "Hidden_Item") + and port["name"] in inputs + } + triggers = { + key: value for key, value in inputs.items() if key not in slots + } + for key, value in slots.items(): + partial = call( + { + "action": "tool_call", + "node_id": node_id, + "arguments": {**triggers, key: value}, + } + ) + if partial.get("ok"): + output.update(partial.get("output_values", {})) + # HIDDEN_ITEM tool drops only occur on subsequent investigation. + call({"action": "investigate", "node_id": node_id}) + elif info.get("required_inputs"): + result = call( + {"action": "use_item", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok"): + raise RuntimeError(f"Item failed: {node_id}: {result}") + output = result.get("content") + else: + output = info.get("content") + seen_outputs[node_id] = output + solved.add(node_id) + progress = True + win_id = scenario["metadata"]["win_node_id"] + if win_id in solved and (len(solved) == len(nodes) or not progress): + outputs = seen_outputs[win_id] + if not outputs: + raise RuntimeError(f"Victory node returned no output: {win_id}") + # Upstream grades its first stored output port, independent of response order. + victory_port = next( + port["name"] for port in nodes[win_id]["outputs"] if "value" in port + ) + answer = outputs[victory_port] if isinstance(outputs, dict) else outputs + result = call({"action": "submit_answer", "answer": answer}) + if not result.get("is_win"): + raise RuntimeError(f"Victory submission failed: {result}") + return {"won": True, "actions": action_count, "visited_nodes": len(solved)} + if not progress: + raise RuntimeError(f"No progress: visible={visible}, solved={solved}") + raise RuntimeError("Reference solver exceeded graph traversal limit") + + +if __name__ == "__main__": + import os + + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000") + with urllib.request.urlopen(base + "/observation", timeout=20) as response: + observation = json.load(response) + print( + json.dumps( + solve( + json.loads(Path("/solution/scenario.json").read_text()), + lambda payload: http_action(base, payload), + observation, + ) + ) + ) diff --git a/tasks/agentescape-25-skeleton-3597bfa8/solution/scenario.json b/tasks/agentescape-25-skeleton-3597bfa8/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..746ab409adfb12c2dd44192f19026b35d8a42aae --- /dev/null +++ b/tasks/agentescape-25-skeleton-3597bfa8/solution/scenario.json @@ -0,0 +1,1864 @@ +{ + "metadata": { + "total_nodes": 25, + "total_edges": 30, + "win_node_id": "zip_unzip_item", + "win_condition": { + "type": "tool_output", + "node_id": "zip_unzip_item", + "output_port": "item", + "output_type": "Item", + "description": "Execute Zip Unzipper and get the output from port 'item'" + }, + "source_init": { + "source_nodes": [ + "zip_unzip_item", + "regex_search", + "text_rotN", + "hex_decode", + "zip_unzip_file", + "zip_unzip_file_a989", + "text_bidi_sanitize", + "zip_unzip_file_9915", + "zip_unzip_file_6e53", + "zip_unzip_file_46a0", + "crypto_rsa_decrypt_hex", + "graph_shortest_path", + "terminal_1", + "text_xor_hex", + "terminal_2", + "regex_search_2a22", + "calc_modexp", + "graph_shortest_path_fd8d", + "zip_unzip_file_54e1", + "num_base_convert", + "zip_unzip_file_1e39", + "hex_decode_ab54", + "container_1", + "calc_bigmul" + ], + "by_node": { + "zip_unzip_item": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_item", + "init_inputs": {}, + "init_outputs": { + "item": { + "type": "Item", + "description": "item in the zip" + } + } + }, + "regex_search": { + "node_name": "Regex Search", + "node_type": "Tool", + "template_id": "regex_search", + "init_inputs": {}, + "init_outputs": { + "matches": { + "type": "Text_Generic", + "description": "Found matches (List)" + } + } + }, + "text_rotN": { + "node_name": "ROT-N Cipher", + "node_type": "Tool", + "template_id": "text_rotN", + "init_inputs": { + "n": { + "type": "Big_Int", + "description": "Shift N" + } + }, + "init_outputs": {} + }, + "hex_decode": { + "node_name": "Hex to Text Decoder", + "node_type": "Tool", + "template_id": "hex_decode", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex string" + } + }, + "init_outputs": {} + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "zip_unzip_file_a989": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "text_bidi_sanitize": { + "node_name": "Bidi Sanitizer", + "node_type": "Tool", + "template_id": "text_bidi_sanitize", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text" + } + }, + "init_outputs": {} + }, + "zip_unzip_file_9915": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "zip_unzip_file_6e53": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "zip_unzip_file_46a0": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "crypto_rsa_decrypt_hex": { + "node_name": "RSA Decrypt", + "node_type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "init_inputs": { + "d": { + "type": "Big_Int", + "description": "Private exponent d" + } + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "Graph JSON file ID" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": {}, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + } + } + }, + "text_xor_hex": { + "node_name": "Hex XOR", + "node_type": "Tool", + "template_id": "text_xor_hex", + "init_inputs": { + "hex_a": { + "type": "Hex_String", + "description": "Hex A" + } + }, + "init_outputs": {} + }, + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": { + "num1": { + "type": "Big_Int", + "description": "First Number" + } + }, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + } + } + }, + "regex_search_2a22": { + "node_name": "Regex Search", + "node_type": "Tool", + "template_id": "regex_search", + "init_inputs": { + "pattern": { + "type": "Text_Generic", + "description": "Regex pattern" + } + }, + "init_outputs": { + "matches": { + "type": "Text_Generic", + "description": "Found matches (List)" + } + } + }, + "calc_modexp": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "base": { + "type": "Big_Int", + "description": "Base" + }, + "exp": { + "type": "Big_Int", + "description": "Exponent" + }, + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "graph_shortest_path_fd8d": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "Graph JSON file ID" + }, + "src": { + "type": "Text_Generic", + "description": "Source node" + }, + "dst": { + "type": "Text_Generic", + "description": "Destination node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "zip_unzip_file_54e1": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + }, + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "num_base_convert": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "to_base": { + "type": "Big_Int", + "description": "To base" + } + }, + "init_outputs": {} + }, + "zip_unzip_file_1e39": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + }, + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "hex_decode_ab54": { + "node_name": "Hex to Text Decoder", + "node_type": "Tool", + "template_id": "hex_decode", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex string" + } + }, + "init_outputs": {} + }, + "container_1": { + "node_name": "", + "node_type": "Item", + "template_id": "container_1", + "init_inputs": { + "fingerprint_input": { + "type": "Hex_String", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + }, + "calc_bigmul": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First large integer" + }, + "b": { + "type": "Big_Int", + "description": "Second large integer" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "zip_unzip_item": { + "init_inputs": {}, + "init_outputs": { + "item": "Blue, Yellow, Black, Green, Red — any five interlocking rings" + } + }, + "regex_search": { + "init_inputs": {}, + "init_outputs": { + "matches": "[\"pattern_01\", \"pattern_02\", \"pattern_03\", \"pattern_04\", \"pattern_05\"]" + } + }, + "text_rotN": { + "init_inputs": { + "n": "84729485729384758291" + }, + "init_outputs": {} + }, + "hex_decode": { + "init_inputs": { + "hex": "48656c6c6f20576f726c642066726f6d20686578206465636f6465" + }, + "init_outputs": {} + }, + "zip_unzip_file": { + "init_inputs": {}, + "init_outputs": { + "files": "extracted_data_1.zip" + } + }, + "zip_unzip_file_a989": { + "init_inputs": {}, + "init_outputs": { + "files": "extracted_data_2.zip" + } + }, + "text_bidi_sanitize": { + "init_inputs": { + "text": "Text containing ‮ right-to-left ‬ override characters." + }, + "init_outputs": {} + }, + "zip_unzip_file_9915": { + "init_inputs": { + "password": "secure_password_9915" + }, + "init_outputs": { + "files": "extracted_data_3.zip" + } + }, + "zip_unzip_file_6e53": { + "init_inputs": {}, + "init_outputs": { + "files": "extracted_data_4.zip" + } + }, + "zip_unzip_file_46a0": { + "init_inputs": { + "password": "secure_password_46a0" + }, + "init_outputs": { + "files": "extracted_data_5.zip" + } + }, + "crypto_rsa_decrypt_hex": { + "init_inputs": { + "d": "4982734982739485729384759283749283749283" + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": { + "file_id": "graph_network.json" + }, + "init_outputs": { + "path": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\"]", + "cost": "458391" + } + }, + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "Terminal one execution completed successfully with data.", + "hex_output": "deadbeefcafebabe1234567890abcdef" + } + }, + "text_xor_hex": { + "init_inputs": { + "hex_a": "112233445566778899aabbccddeeff00" + }, + "init_outputs": {} + }, + "terminal_2": { + "init_inputs": { + "num1": "192837465019283746501928" + }, + "init_outputs": { + "text_result": "Terminal two partial computation result generated successfully.", + "hex_result": "abcdef1234567890abcdef1234567890" + } + }, + "regex_search_2a22": { + "init_inputs": { + "pattern": "[A-Z0-9]{16}" + }, + "init_outputs": { + "matches": "[\"result_A1\", \"result_B2\", \"result_C3\", \"result_D4\", \"result_E5\"]" + } + }, + "calc_modexp": { + "init_inputs": { + "base": "17", + "exp": "938475829384758293847", + "mod": "999983" + }, + "init_outputs": {} + }, + "graph_shortest_path_fd8d": { + "init_inputs": { + "file_id": "city_routes.json", + "src": "City_Origin", + "dst": "City_Destination" + }, + "init_outputs": { + "path": "[\"City_Origin\", \"City_A\", \"City_B\", \"City_C\", \"City_Destination\"]", + "cost": "105938" + } + }, + "zip_unzip_file_54e1": { + "init_inputs": { + "zip_id": "archive_54e1.zip", + "password": "pass_54e1_secure" + }, + "init_outputs": { + "files": "extracted_data_6.zip" + } + }, + "num_base_convert": { + "init_inputs": { + "to_base": "10" + }, + "init_outputs": {} + }, + "zip_unzip_file_1e39": { + "init_inputs": { + "zip_id": "archive_1e39.zip", + "password": "pass_1e39_secure" + }, + "init_outputs": { + "files": "extracted_data_7.zip" + } + }, + "hex_decode_ab54": { + "init_inputs": { + "hex": "536563726574204d6573736167652031" + }, + "init_outputs": {} + }, + "container_1": { + "init_inputs": { + "fingerprint_input": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + }, + "init_outputs": {} + }, + "calc_bigmul": { + "init_inputs": { + "a": "485729384758293847582938", + "b": "938475829384758293847582" + }, + "init_outputs": {} + } + }, + "intro_narrative": "The neon lights of the city flicker through the blinds of your dimly lit detective agency. A notorious cyber-syndicate has been operating in the shadows, leaving behind a trail of encrypted files, locked terminals, and fragmented evidence. You've managed to intercept a massive cache of their digital tools and data, but everything is heavily interconnected and protected. The police are relying on you to piece together the evidence before the syndicate's leader skips town. Your primary objective is to unlock the final evidence locker, which holds the definitive proof needed to put them away for good. To do this, you must carefully examine each piece of software and hardware in your office. Trace the data trails, decrypt the hidden messages, and figure out how these devices feed into one another. Time is ticking, and the syndicate's servers are programmed to wipe themselves by dawn. You need to focus, use your deductive skills, and uncover the truth hidden within the code.", + "narrative_style": "detective" + }, + "nodes": [ + { + "id": "zip_unzip_item", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_item", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "extracted_data_4.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "[\"pattern_01\", \"pattern_02\", \"pattern_03\", \"pattern_04\", \"pattern_05\"]" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip", + "value": "Blue, Yellow, Black, Green, Red — any five interlocking rings" + } + ], + "init": { + "inputs": {}, + "outputs": { + "item": "Blue, Yellow, Black, Green, Red — any five interlocking rings" + } + }, + "narrative": "This is the final evidence locker. It requires inputs from the suspect database and the surveillance archive." + }, + { + "id": "regex_search", + "name": "Regex Search", + "description": "Search regex in either raw text or a file.", + "type": "Tool", + "template_id": "regex_search", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "pattern", + "type": "Text_Generic", + "description": "Regex pattern", + "value": "\u0001" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "File ID (optional)", + "value": "extracted_data_1.zip" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text (optional)", + "value": "Khoor Zruog iurp kha ghfrgh" + } + ], + "outputs": [ + { + "name": "matches", + "type": "Text_Generic", + "description": "Found matches (List)", + "value": "[\"pattern_01\", \"pattern_02\", \"pattern_03\", \"pattern_04\", \"pattern_05\"]" + } + ], + "init": { + "inputs": {}, + "outputs": { + "matches": "[\"pattern_01\", \"pattern_02\", \"pattern_03\", \"pattern_04\", \"pattern_05\"]" + } + }, + "narrative": "This is the suspect database. It requires inputs from the anagram cipher tool, the corrupted archive, and the advanced decryption module." + }, + { + "id": "text_rotN", + "name": "ROT-N Cipher", + "description": "Caesar shift by N.", + "type": "Tool", + "template_id": "text_rotN", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "Hello World from hex decode" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Shift N", + "value": "84729485729384758291" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Rotated text", + "value": "Khoor Zruog iurp kha ghfrgh" + } + ], + "init": { + "inputs": { + "n": "84729485729384758291" + }, + "outputs": {} + }, + "narrative": "This is the anagram cipher tool. It requires input from the raw memory dump." + }, + { + "id": "hex_decode", + "name": "Hex to Text Decoder", + "description": "Decode hex to UTF-8 text.", + "type": "Tool", + "template_id": "hex_decode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex string", + "value": "48656c6c6f20576f726c642066726f6d20686578206465636f6465" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decoded text", + "value": "Hello World from hex decode" + } + ], + "init": { + "inputs": { + "hex": "48656c6c6f20576f726c642066726f6d20686578206465636f6465" + }, + "outputs": {} + }, + "narrative": "A raw memory dump file extracted directly from a suspect's laptop." + }, + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "extracted_data_2.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Text containing right-to-left override characters." + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_data_1.zip" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "extracted_data_1.zip" + } + }, + "narrative": "This is the corrupted archive. It requires inputs from the blackmail folder and the text cleaner program." + }, + { + "id": "zip_unzip_file_a989", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "extracted_data_3.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "[\"City_Origin\", \"City_A\", \"City_B\", \"City_C\", \"City_Destination\"]" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_data_2.zip" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "extracted_data_2.zip" + } + }, + "narrative": "This is the blackmail folder. It requires inputs from the financial records and the map navigation system." + }, + { + "id": "text_bidi_sanitize", + "name": "Bidi Sanitizer", + "description": "Strip bidi control chars.", + "type": "Tool", + "template_id": "text_bidi_sanitize", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "Text containing ‮ right-to-left ‬ override characters." + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Sanitized text", + "value": "Text containing right-to-left override characters." + } + ], + "init": { + "inputs": { + "text": "Text containing ‮ right-to-left ‬ override characters." + }, + "outputs": {} + }, + "narrative": "A text cleaner program used by the forensics lab to strip out invisible control characters." + }, + { + "id": "zip_unzip_file_9915", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "extracted_data_5.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "secure_password_9915" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_data_3.zip" + } + ], + "init": { + "inputs": { + "password": "secure_password_9915" + }, + "outputs": { + "files": "extracted_data_3.zip" + } + }, + "narrative": "This is the financial records. It requires input from the burner phone backup." + }, + { + "id": "zip_unzip_file_6e53", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "extracted_data_6.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Text containing right-to-left override characters." + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_data_4.zip" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "extracted_data_4.zip" + } + }, + "narrative": "This is the surveillance archive. It requires inputs from the text cleaner program and the interrogation records." + }, + { + "id": "zip_unzip_file_46a0", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "extracted_data_7.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "secure_password_46a0" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_data_5.zip" + } + ], + "init": { + "inputs": { + "password": "secure_password_46a0" + }, + "outputs": { + "files": "extracted_data_5.zip" + } + }, + "narrative": "This is the burner phone backup. It requires input from the initial crime scene file." + }, + { + "id": "crypto_rsa_decrypt_hex", + "name": "RSA Decrypt", + "description": "RSA decrypt (hex cipher) with n,d (decimal).", + "type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "hex_cipher", + "type": "Hex_String", + "description": "Ciphertext (Hex)", + "value": "cf8f8dab9f98cd368b9eedb44d4532ef" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Modulus n", + "value": "458391" + }, + { + "name": "d", + "type": "Big_Int", + "description": "Private exponent d", + "value": "4982734982739485729384759283749283749283" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decrypted text", + "value": "\u0001" + } + ], + "init": { + "inputs": { + "d": "4982734982739485729384759283749283749283" + }, + "outputs": {} + }, + "narrative": "This is the advanced decryption module. It requires inputs from the route analyzer and the digital comparator." + }, + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "graph_network.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "[\"result_A1\", \"result_B2\", \"result_C3\", \"result_D4\", \"result_E5\"]" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Secret Message 1" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "458391" + } + ], + "init": { + "inputs": { + "file_id": "graph_network.json" + }, + "outputs": { + "path": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\"]", + "cost": "458391" + } + }, + "narrative": "This is the route analyzer. It requires inputs from the license plate scanner and the GPS log decoder." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "Terminal two partial computation result generated successfully." + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "105938" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Terminal one execution completed successfully with data." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "deadbeefcafebabe1234567890abcdef" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "Terminal one execution completed successfully with data.", + "hex_output": "deadbeefcafebabe1234567890abcdef" + } + }, + "narrative": "This is the mainframe terminal. It requires inputs from the number conversion tool and the accounting terminal." + }, + { + "id": "text_xor_hex", + "name": "Hex XOR", + "description": "XOR two hex strings.", + "type": "Tool", + "template_id": "text_xor_hex", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex_a", + "type": "Hex_String", + "description": "Hex A", + "value": "112233445566778899aabbccddeeff00" + }, + { + "name": "hex_b", + "type": "Hex_String", + "description": "Hex B", + "value": "deadbeefcafebabe1234567890abcdef" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "XOR Result Hex", + "value": "cf8f8dab9f98cd368b9eedb44d4532ef" + } + ], + "init": { + "inputs": { + "hex_a": "112233445566778899aabbccddeeff00" + }, + "outputs": {} + }, + "narrative": "This is the digital comparator. It requires input from the mainframe terminal." + }, + { + "id": "terminal_2", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this terminal" + }, + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "192837465019283746501928" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "252178" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Terminal two partial computation result generated successfully." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "abcdef1234567890abcdef1234567890" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": { + "num1": "192837465019283746501928" + }, + "outputs": { + "text_result": "Terminal two partial computation result generated successfully.", + "hex_result": "abcdef1234567890abcdef1234567890" + } + }, + "narrative": "This is the accounting terminal. It requires input from the cryptographic calculator." + }, + { + "id": "regex_search_2a22", + "name": "Regex Search", + "description": "Search regex in either raw text or a file.", + "type": "Tool", + "template_id": "regex_search", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "pattern", + "type": "Text_Generic", + "description": "Regex pattern", + "value": "[A-Z0-9]{16}" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "File ID (optional)", + "value": "extracted_data_5.zip" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text (optional)", + "value": "[\"City_Origin\", \"City_A\", \"City_B\", \"City_C\", \"City_Destination\"]" + } + ], + "outputs": [ + { + "name": "matches", + "type": "Text_Generic", + "description": "Found matches (List)", + "value": "[\"result_A1\", \"result_B2\", \"result_C3\", \"result_D4\", \"result_E5\"]" + } + ], + "init": { + "inputs": { + "pattern": "[A-Z0-9]{16}" + }, + "outputs": { + "matches": "[\"result_A1\", \"result_B2\", \"result_C3\", \"result_D4\", \"result_E5\"]" + } + }, + "narrative": "This is the license plate scanner. It requires inputs from the map navigation system and the burner phone backup." + }, + { + "id": "calc_modexp", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "17" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "938475829384758293847" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "999983" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "252178" + } + ], + "init": { + "inputs": { + "base": "17", + "exp": "938475829384758293847", + "mod": "999983" + }, + "outputs": {} + }, + "narrative": "A cryptographic calculator found on the suspect's desk, designed for complex math." + }, + { + "id": "graph_shortest_path_fd8d", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "city_routes.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "City_Origin" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "City_Destination" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"City_Origin\", \"City_A\", \"City_B\", \"City_C\", \"City_Destination\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "105938" + } + ], + "init": { + "inputs": { + "file_id": "city_routes.json", + "src": "City_Origin", + "dst": "City_Destination" + }, + "outputs": { + "path": "[\"City_Origin\", \"City_A\", \"City_B\", \"City_C\", \"City_Destination\"]", + "cost": "105938" + } + }, + "narrative": "A map navigation system used by the local cab company to track all vehicle routes." + }, + { + "id": "zip_unzip_file_54e1", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "archive_54e1.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "pass_54e1_secure" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_data_6.zip" + } + ], + "init": { + "inputs": { + "zip_id": "archive_54e1.zip", + "password": "pass_54e1_secure" + }, + "outputs": { + "files": "extracted_data_6.zip" + } + }, + "narrative": "The interrogation records from the precinct's secure server, locked in a digital vault." + }, + { + "id": "num_base_convert", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "105938" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "455845287217588192587234227586219616726875755916" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "10" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "105938" + } + ], + "init": { + "inputs": { + "to_base": "10" + }, + "outputs": {} + }, + "narrative": "This is the number conversion tool. It requires inputs from the map navigation system and the forensic multiplier." + }, + { + "id": "zip_unzip_file_1e39", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "archive_1e39.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "pass_1e39_secure" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_data_7.zip" + } + ], + "init": { + "inputs": { + "zip_id": "archive_1e39.zip", + "password": "pass_1e39_secure" + }, + "outputs": { + "files": "extracted_data_7.zip" + } + }, + "narrative": "The initial crime scene file, containing the first responder's digital report." + }, + { + "id": "hex_decode_ab54", + "name": "Hex to Text Decoder", + "description": "Decode hex to UTF-8 text.", + "type": "Tool", + "template_id": "hex_decode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex string", + "value": "536563726574204d6573736167652031" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decoded text", + "value": "Secret Message 1" + } + ], + "init": { + "inputs": { + "hex": "536563726574204d6573736167652031" + }, + "outputs": {} + }, + "narrative": "A GPS log decoder utility designed to translate cryptic location data." + }, + { + "id": "container_1", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + }, + { + "name": "fingerprint_input", + "type": "Hex_String", + "description": "Fingerprint Hash", + "value": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + }, + "outputs": {} + }, + "narrative": "The detective's briefcase, secured with a heavy-duty biometric lock mechanism." + }, + { + "id": "calc_bigmul", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "485729384758293847582938" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "938475829384758293847582" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "455845287217588192587234227586219616726875755916" + } + ], + "init": { + "inputs": { + "a": "485729384758293847582938", + "b": "938475829384758293847582" + }, + "outputs": {} + }, + "narrative": "A forensic multiplier used specifically for processing extremely large numeric variables." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A forgotten evidence bag covered in dust, sitting quietly in the corner of the room." + } + ], + "edges": [ + { + "source_id": "regex_search", + "target_id": "zip_unzip_item", + "connection_type": "Text_Generic", + "source_port": "matches", + "target_port": "password" + }, + { + "source_id": "text_rotN", + "target_id": "regex_search", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "text" + }, + { + "source_id": "hex_decode", + "target_id": "text_rotN", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "text" + }, + { + "source_id": "zip_unzip_file", + "target_id": "regex_search", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "zip_unzip_file_a989", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "text_bidi_sanitize", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "password" + }, + { + "source_id": "zip_unzip_file_9915", + "target_id": "zip_unzip_file_a989", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "zip_unzip_file_6e53", + "target_id": "zip_unzip_item", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "zip_unzip_file_46a0", + "target_id": "zip_unzip_file_9915", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "crypto_rsa_decrypt_hex", + "target_id": "regex_search", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "pattern" + }, + { + "source_id": "graph_shortest_path", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "n" + }, + { + "source_id": "text_bidi_sanitize", + "target_id": "zip_unzip_file_6e53", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "password" + }, + { + "source_id": "terminal_1", + "target_id": "regex_search", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "trigger_item" + }, + { + "source_id": "text_xor_hex", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_cipher" + }, + { + "source_id": "terminal_2", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "trigger_item" + }, + { + "source_id": "terminal_1", + "target_id": "text_xor_hex", + "connection_type": "Hex_String", + "source_port": "hex_output", + "target_port": "hex_b" + }, + { + "source_id": "regex_search_2a22", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "matches", + "target_port": "src" + }, + { + "source_id": "calc_modexp", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "num2" + }, + { + "source_id": "graph_shortest_path_fd8d", + "target_id": "regex_search_2a22", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "text" + }, + { + "source_id": "zip_unzip_file_54e1", + "target_id": "zip_unzip_file_6e53", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "graph_shortest_path_fd8d", + "target_id": "zip_unzip_file_a989", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "password" + }, + { + "source_id": "num_base_convert", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "slot_b" + }, + { + "source_id": "zip_unzip_file_1e39", + "target_id": "zip_unzip_file_46a0", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "graph_shortest_path_fd8d", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "s" + }, + { + "source_id": "terminal_2", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "slot_a" + }, + { + "source_id": "hex_decode_ab54", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "dst" + }, + { + "source_id": "zip_unzip_file_46a0", + "target_id": "regex_search_2a22", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "container_1", + "target_id": "zip_unzip_file_46a0", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "calc_bigmul", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "from_base" + }, + { + "source_id": "item_16", + "target_id": "zip_unzip_file_54e1", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-3597bfa8/solution/solve.sh b/tasks/agentescape-25-skeleton-3597bfa8/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3597bfa8/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-25-skeleton-3597bfa8/task.toml b/tasks/agentescape-25-skeleton-3597bfa8/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..baf76593e2184309af4eb584136f8208211bdf11 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3597bfa8/task.toml @@ -0,0 +1,38 @@ +schema_version = "1.4" +source = "https://github.com/AGI-Eval-Official/Repo-of-AgentEscapeBench" + +[[artifacts]] +source = "/evidence/final.json" +service = "puzzle" + +[[artifacts]] +source = "/evidence/trace.jsonl" +service = "puzzle" + +[task] +name = "edbeeching/agentescape-25-skeleton-3597bfa8" +version = "0.1.0" + +[metadata] +difficulty = 25 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "8cbf0a212ebce6dd298f05fe53a0ea48bbef623a77ab8dc85125ec48dce67253" +protocol = "harbor-cli-action-budget-v1" +max_actions = 500 + +[agent] +timeout_sec = 1200 + +[environment] +build_timeout_sec = 900 +cpus = 1 +memory_mb = 1024 + +[verifier] +environment_mode = "separate" +timeout_sec = 60 + +[[verifier.collect]] +service = "puzzle" +command = "python -I /app/export.py" +timeout_sec = 15 diff --git a/tasks/agentescape-25-skeleton-3597bfa8/tests/Dockerfile b/tasks/agentescape-25-skeleton-3597bfa8/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-25-skeleton-3597bfa8/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-25-skeleton-3597bfa8/tests/expected.json b/tasks/agentescape-25-skeleton-3597bfa8/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..6e8919a509733fc3536ca8e8e41dad41ec382448 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3597bfa8/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "8cbf0a212ebce6dd298f05fe53a0ea48bbef623a77ab8dc85125ec48dce67253", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-3597bfa8/tests/grade.py b/tasks/agentescape-25-skeleton-3597bfa8/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3597bfa8/tests/grade.py @@ -0,0 +1,21 @@ +"""Grade only Harbor-collected sidecar evidence in a fresh verifier container.""" + +import json +from pathlib import Path + +expected = json.loads(Path("/tests/expected.json").read_text()) +state = json.loads(Path("/evidence/final.json").read_text()) +assert state["collected_from_live_service"] is True, "Missing trusted service export" +assert state["scenario_sha256"] == expected["scenario_sha256"], ( + "Wrong scenario evidence" +) +assert state["max_actions"] == expected["max_actions"], "Wrong budget" +assert type(state["won"]) is bool +assert 0 <= state["action_count"] <= state["max_actions"] +assert state["termination_reason"] != "infrastructure_error", ( + "Infrastructure failure is not a puzzle failure" +) +assert not state["won"] or state["termination_reason"] == "success" +Path("/logs/verifier").mkdir(parents=True, exist_ok=True) +Path("/logs/verifier/state.json").write_text(json.dumps(state, indent=2)) +Path("/logs/verifier/reward.txt").write_text("1.0\n" if state["won"] else "0.0\n") diff --git a/tasks/agentescape-25-skeleton-3597bfa8/tests/test.sh b/tasks/agentescape-25-skeleton-3597bfa8/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3597bfa8/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-25-skeleton-3ae882d5/environment/Dockerfile b/tasks/agentescape-25-skeleton-3ae882d5/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3ae882d5/environment/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-25-skeleton-3ae882d5/environment/agent/Dockerfile b/tasks/agentescape-25-skeleton-3ae882d5/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3ae882d5/environment/agent/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-25-skeleton-3ae882d5/environment/agent/cli.py b/tasks/agentescape-25-skeleton-3ae882d5/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-25-skeleton-3ae882d5/environment/agent/cli.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Public agent client; depends only on the Python standard library.""" + +import argparse +import json +import os +import sys +import urllib.error +import urllib.request + + +def main(): + parser = argparse.ArgumentParser(description="Interact with the escape room") + parser.add_argument( + "action", + choices=[ + "observe", + "state", + "investigate", + "tool-call", + "use-item", + "submit-answer", + ], + ) + parser.add_argument("value", nargs="?") + parser.add_argument("--arguments-json", default="{}") + args = parser.parse_args() + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000").rstrip("/") + if args.action in ("observe", "state"): + request = urllib.request.Request( + base + ("/observation" if args.action == "observe" else "/state") + ) + else: + if args.value is None: + parser.error("node ID or answer is required") + payload = {"action": args.action.replace("-", "_")} + if args.action == "submit-answer": + payload["answer"] = args.value + else: + payload["node_id"] = args.value + if args.action in ("tool-call", "use-item"): + payload["arguments"] = json.loads(args.arguments_json) + request = urllib.request.Request( + base + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=30) as response: + print(json.dumps(json.load(response), ensure_ascii=False)) + except (urllib.error.URLError, ValueError) as exc: + print(json.dumps({"ok": False, "error": str(exc)})) + sys.exit(2) + + +if __name__ == "__main__": + main() diff --git a/tasks/agentescape-25-skeleton-3ae882d5/environment/docker-compose.yaml b/tasks/agentescape-25-skeleton-3ae882d5/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8d2651038a2a0bb3c8ef91626cf15f2ec9b0e3d9 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3ae882d5/environment/docker-compose.yaml @@ -0,0 +1,50 @@ +services: + main: + image: agentescapebench-agent:aab05a0a9ddb + build: + context: ./agent + networks: [default, puzzle] + security_opt: [no-new-privileges:true] + depends_on: + puzzle: + condition: service_healthy + puzzle: + image: agentescapebench-puzzle:agentescape-25-skeleton-3ae882d5-aab05a0a9ddb + build: + context: ./puzzle + networks: [puzzle, execution] + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 512m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"] + interval: 1s + timeout: 3s + retries: 30 + depends_on: + worker: + condition: service_healthy + worker: + image: agentescapebench-worker:aab05a0a9ddb + build: + context: ./puzzle + dockerfile: worker.Dockerfile + networks: [execution] + read_only: true + tmpfs: ["/tmp:size=64m,mode=1777"] + cap_drop: [ALL] + cap_add: [SETUID, SETGID, KILL, CHOWN, DAC_OVERRIDE] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 384m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8001/health')"] + interval: 1s + timeout: 3s + retries: 30 +networks: + puzzle: + internal: true + execution: + internal: true diff --git a/tasks/agentescape-25-skeleton-3ae882d5/environment/puzzle/Dockerfile b/tasks/agentescape-25-skeleton-3ae882d5/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3ae882d5/environment/puzzle/Dockerfile @@ -0,0 +1,9 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY upstream /app/upstream +COPY service.py export.py /app/ +COPY scenario.json /private/scenario.json +ENV SCENARIO_PATH=/private/scenario.json EVIDENCE_DIR=/evidence WORKER_URL=http://worker:8001 MAX_ACTIONS=500 +CMD ["uvicorn", "service:create_app", "--factory", "--host", "0.0.0.0", "--port", "8000", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-25-skeleton-3ae882d5/environment/puzzle/child.py b/tasks/agentescape-25-skeleton-3ae882d5/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3ae882d5/environment/puzzle/child.py @@ -0,0 +1,59 @@ +"""Run the original Python tool after reducing privileges and blocking networking.""" + +import ctypes +import errno +import json +import resource +import sys + +resource.setrlimit(resource.RLIMIT_CPU, (3, 3)) +resource.setrlimit(resource.RLIMIT_AS, (256 * 1024 * 1024, 256 * 1024 * 1024)) +resource.setrlimit(resource.RLIMIT_FSIZE, (65536, 65536)) +resource.setrlimit(resource.RLIMIT_NOFILE, (32, 32)) +resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + +# Filters survive fork/exec. Fail closed if seccomp cannot be loaded. +lib = ctypes.CDLL("libseccomp.so.2", use_errno=True) +lib.seccomp_init.argtypes = [ctypes.c_uint32] +lib.seccomp_init.restype = ctypes.c_void_p +lib.seccomp_rule_add.argtypes = [ + ctypes.c_void_p, + ctypes.c_uint32, + ctypes.c_int, + ctypes.c_uint, +] +lib.seccomp_syscall_resolve_name.argtypes = [ctypes.c_char_p] +lib.seccomp_load.argtypes = [ctypes.c_void_p] +lib.seccomp_release.argtypes = [ctypes.c_void_p] +ctx = lib.seccomp_init(0x7FFF0000) # SCMP_ACT_ALLOW +if not ctx: + raise RuntimeError("Cannot initialize execution isolation") +try: + for name in ( + "socket", + "socketpair", + "connect", + "ptrace", + "process_vm_readv", + "process_vm_writev", + "mount", + "unshare", + "setns", + "bpf", + ): + number = lib.seccomp_syscall_resolve_name(name.encode()) + if ( + number >= 0 + and lib.seccomp_rule_add(ctx, 0x00050000 | errno.EPERM, number, 0) != 0 + ): + raise RuntimeError("Cannot install execution isolation rule") + if lib.seccomp_load(ctx) != 0: + raise RuntimeError("Cannot activate execution isolation") +finally: + lib.seccomp_release(ctx) + +sys.path.insert(0, "/app") +from simulator import ToolSimulator # noqa: E402 + +request = json.load(sys.stdin) +json.dump(ToolSimulator().code_py_exec(request), sys.stdout) diff --git a/tasks/agentescape-25-skeleton-3ae882d5/environment/puzzle/export.py b/tasks/agentescape-25-skeleton-3ae882d5/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3ae882d5/environment/puzzle/export.py @@ -0,0 +1,13 @@ +"""Harbor invokes this inside the puzzle service after stopping the agent.""" + +import json +import pathlib +import urllib.request + +with urllib.request.urlopen("http://127.0.0.1:8000/state", timeout=10) as response: + state = json.load(response) +state["collected_from_live_service"] = True +target = pathlib.Path("/evidence/final.json") +temp = target.with_suffix(".tmp") +temp.write_text(json.dumps(state)) +temp.replace(target) diff --git a/tasks/agentescape-25-skeleton-3ae882d5/environment/puzzle/requirements.txt b/tasks/agentescape-25-skeleton-3ae882d5/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3ae882d5/environment/puzzle/requirements.txt @@ -0,0 +1,57 @@ +annotated-doc==0.0.5 + # via fastapi +annotated-types==0.8.0 + # via pydantic +anyio==4.16.0 + # via starlette +certifi==2026.10.23 + # via requests +cffi==2.1.1 ; platform_python_implementation != 'PyPy' + # via cryptography +charset-normalizer==3.5.2 + # via requests +click==8.5.0 + # via uvicorn +cryptography==50.0.2 + # via agentescapebench-harbor +fastapi==0.162.0 + # via agentescapebench-harbor +h11==0.16.0 + # via uvicorn +idna==3.20 + # via + # anyio + # requests +opentelemetry-api==1.45.2 + # via fastapi +pycparser==3.12 ; implementation_name != 'PyPy' and platform_python_implementation != 'PyPy' + # via cffi +pydantic==2.14.2 + # via + # agentescapebench-harbor + # fastapi +pydantic-core==2.50.2 + # via pydantic +pytz==2025.2 + # via agentescapebench-harbor +requests==2.34.2 + # via agentescapebench-harbor +starlette==1.10.0 + # via fastapi +typing-extensions==4.16.0 + # via + # anyio + # fastapi + # opentelemetry-api + # pydantic + # pydantic-core + # starlette + # typing-inspection +typing-inspection==0.4.4 + # via + # fastapi + # pydantic +urllib3==2.8.0 + # via requests +uvicorn==0.54.0 + # via agentescapebench-harbor diff --git a/tasks/agentescape-25-skeleton-3ae882d5/environment/puzzle/scenario.json b/tasks/agentescape-25-skeleton-3ae882d5/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..c0d1c3f53b2a6c86fa15c07fdfd37a30b3bb81be --- /dev/null +++ b/tasks/agentescape-25-skeleton-3ae882d5/environment/puzzle/scenario.json @@ -0,0 +1,1466 @@ +{ + "metadata": { + "total_nodes": 25, + "total_edges": 43, + "win_node_id": "crypto_rsa_decrypt_hex", + "win_condition": { + "type": "tool_output", + "node_id": "crypto_rsa_decrypt_hex", + "output_port": "text", + "output_type": "Text_Generic", + "description": "Execute RSA Decrypt and get the output from port 'text'" + }, + "source_init": { + "source_nodes": [ + "terminal_1", + "calc_modexp_90b3", + "terminal_1_ccb2", + "zip_unzip_file", + "base64_decode", + "calc_modexp_483a", + "item_1", + "hex_decode", + "csv_query" + ], + "by_node": { + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": {}, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + }, + "item_dispenser": { + "type": "Item", + "description": "Item output when both slots are provided" + } + } + }, + "calc_modexp_90b3": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "base": { + "type": "Big_Int", + "description": "Base" + } + }, + "init_outputs": {} + }, + "terminal_1_ccb2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": {}, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + }, + "item_dispenser": { + "type": "Item", + "description": "Item output when both slots are provided" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "base64_decode": { + "node_name": "Base64 Decoder", + "node_type": "Tool", + "template_id": "base64_decode", + "init_inputs": { + "data": { + "type": "Text_Generic", + "description": "Base64 string" + } + }, + "init_outputs": {} + }, + "calc_modexp_483a": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "exp": { + "type": "Big_Int", + "description": "Exponent" + } + }, + "init_outputs": {} + }, + "item_1": { + "node_name": "", + "node_type": "Item", + "template_id": "item_1", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Big_Int", + "description": "The number" + } + } + }, + "hex_decode": { + "node_name": "Hex to Text Decoder", + "node_type": "Tool", + "template_id": "hex_decode", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex string" + } + }, + "init_outputs": {} + }, + "csv_query": { + "node_name": "CSV Query", + "node_type": "Tool", + "template_id": "csv_query", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "CSV file ID" + }, + "select": { + "type": "Text_Generic", + "description": "Columns to select" + }, + "where": { + "type": "Text_Generic", + "description": "Where clause" + } + }, + "init_outputs": { + "rows": { + "type": "Text_Generic", + "description": "Result rows" + } + } + } + } + }, + "initial_values": { + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "Terminal 1 operation executed completely.", + "hex_output": "1a2b3c4d5e6f7a8b9c0d", + "item_dispenser": "A completely useless empty box output" + } + }, + "calc_modexp_90b3": { + "init_inputs": { + "base": "31" + }, + "init_outputs": {} + }, + "terminal_1_ccb2": { + "init_inputs": {}, + "init_outputs": { + "text_output": "Secondary terminal process finished successfully.", + "hex_output": "ffeeddccbbaa99887766554433221100", + "item_dispenser": "A rusted cogwheel with no mechanism" + } + }, + "zip_unzip_file": { + "init_inputs": { + "zip_id": "secure_archive_54.zip" + }, + "init_outputs": { + "files": "extracted_data_54.dat" + } + }, + "base64_decode": { + "init_inputs": { + "data": "U2VjcmV0IG1lc3NhZ2UgZGVjb2RlZA==" + }, + "init_outputs": {} + }, + "calc_modexp_483a": { + "init_inputs": { + "exp": "84759382019384756201" + }, + "init_outputs": {} + }, + "item_1": { + "init_inputs": {}, + "init_outputs": { + "content": "91827364554637281920" + } + }, + "hex_decode": { + "init_inputs": { + "hex": "546869732069732061207465737420737472696e67" + }, + "init_outputs": {} + }, + "csv_query": { + "init_inputs": { + "file_id": "financial_records_2023.csv", + "select": "transaction_id, amount, date", + "where": "amount > 5000" + }, + "init_outputs": { + "rows": "[{\"transaction_id\":\"TX1001\",\"amount\":6000,\"date\":\"2023-01-05\"},{\"transaction_id\":\"TX1002\",\"amount\":7500,\"date\":\"2023-01-10\"},{\"transaction_id\":\"TX1003\",\"amount\":8200,\"date\":\"2023-01-15\"}]" + } + } + }, + "intro_narrative": "You step into the dusty ruins of Precinct 42, a station abandoned years ago after the infamous 'Phantom' hacker corrupted all the critical evidence files in the city. You are Detective Miller's former partner, returning to this forgotten place to finish what he started before he mysteriously disappeared. The precinct is a labyrinth of disconnected mainframe terminals, scattered case files, and sealed evidence vaults. The air is thick with the smell of stale coffee and old paper. Your objective is clear: navigate this maze of archaic technology and piece together the fractured digital trail left behind by both Miller and the Phantom. To uncover the ultimate truth, you must process the raw evidence and reconstruct the sequence of events. The final, damning piece of the puzzle lies hidden deep within The Master Decryption Terminal. Only by correctly routing the clues through the various analytical devices scattered around the room can you break the final cipher and solve the cold case.", + "narrative_style": "detective" + }, + "nodes": [ + { + "id": "crypto_rsa_decrypt_hex", + "name": "RSA Decrypt", + "description": "RSA decrypt (hex cipher) with n,d (decimal).", + "type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex_cipher", + "type": "Hex_String", + "description": "Ciphertext (Hex)", + "value": "39a6f4a5" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Modulus n", + "value": "1" + }, + { + "name": "d", + "type": "Big_Int", + "description": "Private exponent d", + "value": "3143408493" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decrypted text", + "value": "\u0000" + } + ], + "narrative": "This is The Master Decryption Terminal. It requires inputs from The Fingerprint Scanner, The Primary Code Breaker, and The Alibi Verifier to reveal the final truth." + }, + { + "id": "checksum_crc32", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "a177a7205e6f7a8b9c0d" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "39a6f4a5" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 967242917 + } + ], + "narrative": "This is The Fingerprint Scanner. It requires input from The Cipher Overlay to analyze the digital prints." + }, + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": 3143408493 + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "0" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "3143408493" + } + ], + "narrative": "This is The Primary Code Breaker. It requires inputs from both The Motive Processor and The Integrity Checker." + }, + { + "id": "calc_modexp", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "1" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "0" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": 3143408493 + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "1" + } + ], + "narrative": "This is The Alibi Verifier. It requires inputs from The Integrity Checker, The Pattern Matcher, and The Suspect Profiler to validate alibis." + }, + { + "id": "checksum_crc32_47c3", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "536563726574206d657373616765206465636f646564" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "bb5c9b6d" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3143408493 + } + ], + "narrative": "This is The Integrity Checker. It requires input from The Evidence Decoder to verify the data integrity." + }, + { + "id": "calc_modexp_989e", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": 967242917 + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "1" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "1" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "0" + } + ], + "narrative": "This is The Motive Processor. It requires inputs from The Format Converter, The Fingerprint Scanner, and The Alibi Verifier to deduce intentions." + }, + { + "id": "num_base_convert", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "1" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": 3143408493 + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "0" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "1" + } + ], + "narrative": "This is The Format Converter. It requires inputs from The Timeline Reconstructor, The Integrity Checker, and The Suspect Profiler." + }, + { + "id": "calc_gcd_564d", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "1" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "1" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "narrative": "This is The Timeline Reconstructor. It requires inputs from both The Pattern Matcher and The Alibi Verifier to build a chronology." + }, + { + "id": "text_xor_hex", + "name": "Hex XOR", + "description": "XOR two hex strings.", + "type": "Tool", + "template_id": "text_xor_hex", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex_a", + "type": "Hex_String", + "description": "Hex A", + "value": "bb5c9b6d" + }, + { + "name": "hex_b", + "type": "Hex_String", + "description": "Hex B", + "value": "1a2b3c4d5e6f7a8b9c0d" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "XOR Result Hex", + "value": "a177a7205e6f7a8b9c0d" + } + ], + "narrative": "This is The Cipher Overlay. It requires inputs from both The Integrity Checker and The Main Frame." + }, + { + "id": "calc_gcd_86c2", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": 3143408493 + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": 967242917 + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "narrative": "This is The Pattern Matcher. It requires inputs from both The Fingerprint Scanner and The Integrity Checker." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "Secondary terminal process finished successfully." + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "1" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Terminal 1 operation executed completely." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "1a2b3c4d5e6f7a8b9c0d" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided", + "value": "A completely useless empty box output" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "Terminal 1 operation executed completely.", + "hex_output": "1a2b3c4d5e6f7a8b9c0d", + "item_dispenser": "A completely useless empty box output" + } + }, + "narrative": "This is The Main Frame. It requires inputs from both The Backup Terminal and The Reversal Engine to gain full system access." + }, + { + "id": "calc_modexp_90b3", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "31" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": 3143408493 + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "1" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "0" + } + ], + "init": { + "inputs": { + "base": "31" + }, + "outputs": {} + }, + "narrative": "This is The Suspect Profiler. It requires inputs from both The Integrity Checker and The Pattern Matcher to narrow down the culprits." + }, + { + "id": "terminal_1_ccb2", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this terminal" + }, + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "u1ybbQ==" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": 3143408493 + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Secondary terminal process finished successfully." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "ffeeddccbbaa99887766554433221100" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided", + "value": "A rusted cogwheel with no mechanism" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "Secondary terminal process finished successfully.", + "hex_output": "ffeeddccbbaa99887766554433221100", + "item_dispenser": "A rusted cogwheel with no mechanism" + } + }, + "narrative": "This is The Backup Terminal. It requires inputs from both The Signal Encoder and The Integrity Checker to initialize." + }, + { + "id": "container_1", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_1", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by", + "value": "synthesized_item_717ac506950da0cc" + }, + { + "name": "fingerprint_input", + "type": "Hex_String", + "description": "Fingerprint Hash", + "value": "bb5c9b6d" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is The Evidence Vault. It requires input from The Integrity Checker to unlock its mechanical seal." + }, + { + "id": "zip_unzip_item", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_item", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "extracted_data_54.dat" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "u1ybbQ==" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip" + } + ], + "narrative": "This is The Case File Unpacker. It requires inputs from both The Signal Encoder and The Archive Extractor to open sealed files." + }, + { + "id": "base64_encode", + "name": "Base64 Encoder", + "description": "Encode hex bytes to base64.", + "type": "Tool", + "template_id": "base64_encode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex bytes", + "value": "bb5c9b6d" + } + ], + "outputs": [ + { + "name": "b64", + "type": "Text_Generic", + "description": "Base64 string", + "value": "u1ybbQ==" + } + ], + "narrative": "This is The Signal Encoder. It requires input from The Integrity Checker to transmit data securely." + }, + { + "id": "calc_inv_mod", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "1" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": 3143408493 + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "1" + } + ], + "narrative": "This is The Reversal Engine. It requires inputs from both The Forensic Analyzer and The Integrity Checker to invert the logic." + }, + { + "id": "calc_gcd_028c", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": 3143408493 + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "1860539552" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "narrative": "This is The Forensic Analyzer. It requires inputs from both The Integrity Checker and The Ballistics Calculator to cross-reference data." + }, + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "secure_archive_54.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "[{\"transaction_id\":\"TX1001\",\"amount\":6000,\"date\":\"2023-01-05\"},{\"transaction_id\":\"TX1002\",\"amount\":7500,\"date\":\"2023-01-10\"},{\"transaction_id\":\"TX1003\",\"amount\":8200,\"date\":\"2023-01-15\"}]" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_data_54.dat" + } + ], + "init": { + "inputs": { + "zip_id": "secure_archive_54.zip" + }, + "outputs": { + "files": "extracted_data_54.dat" + } + }, + "narrative": "This is The Archive Extractor. It requires input from The Police Database to pull the correct case records." + }, + { + "id": "base64_decode", + "name": "Base64 Decoder", + "description": "Decode base64 to hex bytes.", + "type": "Tool", + "template_id": "base64_decode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "data", + "type": "Text_Generic", + "description": "Base64 string", + "value": "U2VjcmV0IG1lc3NhZ2UgZGVjb2RlZA==" + } + ], + "outputs": [ + { + "name": "bytes_hex", + "type": "Hex_String", + "description": "Decoded bytes as Hex", + "value": "536563726574206d657373616765206465636f646564" + } + ], + "init": { + "inputs": { + "data": "U2VjcmV0IG1lc3NhZ2UgZGVjb2RlZA==" + }, + "outputs": {} + }, + "narrative": "A rugged field computer known as The Evidence Decoder." + }, + { + "id": "matter_synthesizer", + "name": "Matter Synthesizer", + "description": "Synthesizes physical objects from data blueprints.", + "type": "Tool", + "template_id": "matter_synthesizer", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "blueprint", + "type": "Text_Generic", + "description": "Object Blueprint", + "value": "This is a test string" + } + ], + "outputs": [ + { + "name": "output_slot", + "type": "Item", + "description": "Synthesized Object", + "value": "synthesized_item_717ac506950da0cc" + } + ], + "narrative": "This is The Evidence Printer. It requires input from The Note Translator to synthesize physical clues." + }, + { + "id": "calc_modexp_483a", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "91827364554637281920" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "84759382019384756201" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": 3143408493 + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "1860539552" + } + ], + "init": { + "inputs": { + "exp": "84759382019384756201" + }, + "outputs": {} + }, + "narrative": "This is The Ballistics Calculator. It requires inputs from both The Integrity Checker and The Victim's Pocket Watch to trace trajectories." + }, + { + "id": "item_1", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "Big_Int", + "description": "The number", + "value": "91827364554637281920" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "91827364554637281920" + } + }, + "narrative": "The Victim's Pocket Watch. It stopped at the exact time of the crime." + }, + { + "id": "hex_decode", + "name": "Hex to Text Decoder", + "description": "Decode hex to UTF-8 text.", + "type": "Tool", + "template_id": "hex_decode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "hex", + "type": "Hex_String", + "description": "Hex string", + "value": "546869732069732061207465737420737472696e67" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decoded text", + "value": "This is a test string" + } + ], + "init": { + "inputs": { + "hex": "546869732069732061207465737420737472696e67" + }, + "outputs": {} + }, + "narrative": "A small decryption device known as The Note Translator." + }, + { + "id": "csv_query", + "name": "CSV Query", + "description": "Query CSV: select columns and simple WHERE.", + "type": "Tool", + "template_id": "csv_query", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "CSV file ID", + "value": "financial_records_2023.csv" + }, + { + "name": "select", + "type": "Text_Generic", + "description": "Columns to select", + "value": "transaction_id, amount, date" + }, + { + "name": "where", + "type": "Text_Generic", + "description": "Where clause", + "value": "amount > 5000" + } + ], + "outputs": [ + { + "name": "rows", + "type": "Text_Generic", + "description": "Result rows", + "value": "[{\"transaction_id\":\"TX1001\",\"amount\":6000,\"date\":\"2023-01-05\"},{\"transaction_id\":\"TX1002\",\"amount\":7500,\"date\":\"2023-01-10\"},{\"transaction_id\":\"TX1003\",\"amount\":8200,\"date\":\"2023-01-15\"}]" + } + ], + "init": { + "inputs": { + "file_id": "financial_records_2023.csv", + "select": "transaction_id, amount, date", + "where": "amount > 5000" + }, + "outputs": { + "rows": "[{\"transaction_id\":\"TX1001\",\"amount\":6000,\"date\":\"2023-01-05\"},{\"transaction_id\":\"TX1002\",\"amount\":7500,\"date\":\"2023-01-10\"},{\"transaction_id\":\"TX1003\",\"amount\":8200,\"date\":\"2023-01-15\"}]" + } + }, + "narrative": "An old terminal hooked up to The Police Database." + } + ], + "edges": [ + { + "source_id": "checksum_crc32", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_cipher" + }, + { + "source_id": "calc_gcd", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "d" + }, + { + "source_id": "calc_modexp", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "n" + }, + { + "source_id": "checksum_crc32_47c3", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "mod" + }, + { + "source_id": "calc_modexp_989e", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "b" + }, + { + "source_id": "num_base_convert", + "target_id": "calc_modexp_989e", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "mod" + }, + { + "source_id": "calc_gcd_564d", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "s" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp_989e", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "base" + }, + { + "source_id": "calc_modexp", + "target_id": "calc_modexp_989e", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "exp" + }, + { + "source_id": "checksum_crc32_47c3", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "a" + }, + { + "source_id": "text_xor_hex", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "checksum_crc32_47c3", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "from_base" + }, + { + "source_id": "calc_gcd_86c2", + "target_id": "calc_gcd_564d", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "a" + }, + { + "source_id": "checksum_crc32_47c3", + "target_id": "text_xor_hex", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_a" + }, + { + "source_id": "calc_modexp", + "target_id": "calc_gcd_564d", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "b" + }, + { + "source_id": "terminal_1", + "target_id": "text_xor_hex", + "connection_type": "Hex_String", + "source_port": "hex_output", + "target_port": "hex_b" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_gcd_86c2", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "b" + }, + { + "source_id": "calc_gcd_86c2", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "base" + }, + { + "source_id": "checksum_crc32_47c3", + "target_id": "calc_gcd_86c2", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "a" + }, + { + "source_id": "calc_modexp_90b3", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "exp" + }, + { + "source_id": "terminal_1_ccb2", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "slot_a" + }, + { + "source_id": "container_1", + "target_id": "calc_modexp_90b3", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "zip_unzip_item", + "target_id": "terminal_1_ccb2", + "connection_type": "Item", + "source_port": "item", + "target_port": "trigger_item" + }, + { + "source_id": "checksum_crc32_47c3", + "target_id": "calc_modexp_90b3", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "exp" + }, + { + "source_id": "calc_gcd_86c2", + "target_id": "calc_modexp_90b3", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "mod" + }, + { + "source_id": "base64_encode", + "target_id": "terminal_1_ccb2", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "slot_a" + }, + { + "source_id": "checksum_crc32_47c3", + "target_id": "terminal_1_ccb2", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "slot_b" + }, + { + "source_id": "checksum_crc32_47c3", + "target_id": "base64_encode", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "base64_encode", + "target_id": "zip_unzip_item", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "password" + }, + { + "source_id": "calc_modexp_90b3", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "to_base" + }, + { + "source_id": "calc_inv_mod", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "slot_b" + }, + { + "source_id": "calc_gcd_028c", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "a" + }, + { + "source_id": "checksum_crc32_47c3", + "target_id": "container_1", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "fingerprint_input" + }, + { + "source_id": "checksum_crc32_47c3", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "mod" + }, + { + "source_id": "zip_unzip_file", + "target_id": "zip_unzip_item", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "base64_decode", + "target_id": "checksum_crc32_47c3", + "connection_type": "Hex_String", + "source_port": "bytes_hex", + "target_port": "hex" + }, + { + "source_id": "checksum_crc32_47c3", + "target_id": "calc_gcd_028c", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "a" + }, + { + "source_id": "matter_synthesizer", + "target_id": "container_1", + "connection_type": "Item", + "source_port": "output_slot", + "target_port": "source_tool" + }, + { + "source_id": "calc_modexp_483a", + "target_id": "calc_gcd_028c", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "b" + }, + { + "source_id": "checksum_crc32_47c3", + "target_id": "calc_modexp_483a", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "mod" + }, + { + "source_id": "item_1", + "target_id": "calc_modexp_483a", + "connection_type": "Big_Int", + "source_port": "content", + "target_port": "base" + }, + { + "source_id": "hex_decode", + "target_id": "matter_synthesizer", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "blueprint" + }, + { + "source_id": "csv_query", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "rows", + "target_port": "password" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-3ae882d5/environment/puzzle/service.py b/tasks/agentescape-25-skeleton-3ae882d5/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-25-skeleton-3ae882d5/environment/puzzle/service.py @@ -0,0 +1,212 @@ +"""Restricted facade over the unchanged, pinned upstream puzzle handlers.""" + +import hashlib +import json +import logging +import os +import sys +import threading +import urllib.request +import uuid +from pathlib import Path + +from fastapi import FastAPI, HTTPException +from fastapi.responses import JSONResponse +from pydantic import BaseModel, ConfigDict + +sys.path.insert(0, str(Path(__file__).parent / "upstream")) +import server as upstream # noqa: E402 + +log = logging.getLogger(__name__) + + +def public(value): + """Keep upstream agent-internal template hints out of the public response.""" + if isinstance(value, dict): + return {k: public(v) for k, v in value.items() if not k.startswith("_")} + if isinstance(value, list): + return [public(v) for v in value] + return value + + +class Action(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + action: str + node_id: str | None = None + arguments: dict | None = None + answer: str | None = None + + +class Episode: + def __init__( + self, scenario_path, max_actions=500, evidence_dir=None, worker_url=None + ): + if max_actions < 1: + raise ValueError("max_actions must be positive") + self.lock = threading.Lock() + self.max_actions = max_actions + self.count = 0 + self.won = False + self.reason = None + self.evidence_dir = Path(evidence_dir) if evidence_dir else None + self.scenario_hash = hashlib.sha256( + Path(scenario_path).read_bytes() + ).hexdigest() + self.initial = upstream.reset_case( + case_file_path=str(scenario_path), session_id=uuid.uuid4().hex + ) + self.case_id = self.initial["case_id"] + # Hide source file paths; no upstream reset/stats/routes are mounted. + self.initial.pop("message", None) + simulator = upstream.SIMULATORS[self.case_id] + if worker_url is None: + + def no_worker(_inputs): + self.reason = "infrastructure_error" + raise RuntimeError("isolated Python worker is not configured") + + simulator.tool_map["code_py_exec"] = no_worker + else: + + def execute_python(inputs): + request = urllib.request.Request( + worker_url + "/execute", + data=json.dumps({"code": inputs.get("code", "")}).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=12) as response: + result = json.load(response) + if not isinstance(result.get("stdout"), str): + raise RuntimeError("Invalid Python worker response") + return result + except Exception: + self.reason = "infrastructure_error" + raise + + simulator.tool_map["code_py_exec"] = execute_python + self.save() + if self.evidence_dir is not None: + (self.evidence_dir / "trace.jsonl").touch() + + def state(self): + return { + "scenario_sha256": self.scenario_hash, + "action_count": self.count, + "max_actions": self.max_actions, + "won": self.won, + "termination_reason": self.reason, + } + + def save(self, action=None, result=None): + if self.evidence_dir is None: + return + self.evidence_dir.mkdir(parents=True, exist_ok=True) + target = self.evidence_dir / "outcome.json" + temp = target.with_suffix(".tmp") + temp.write_text(json.dumps(self.state())) + temp.replace(target) + if action is not None: + with (self.evidence_dir / "trace.jsonl").open("a") as handle: + handle.write( + json.dumps( + {"index": self.count, "action": action, "result": result} + ) + + "\n" + ) + + def dispatch(self, payload): + with self.lock: + if self.reason is not None: + return { + "ok": False, + "error": "Episode has ended", + "episode": self.state(), + } + self.count += 1 + try: + action = Action.model_validate(payload) + if action.action == "submit_answer" and action.answer is not None: + result = upstream.submit_answer( + self.case_id, upstream.SubmitAnswerRequest(answer=action.answer) + ) + if result.get("is_win"): + self.won = True + self.reason = "success" + elif action.action == "investigate" and action.node_id is not None: + result = upstream.investigate( + self.case_id, + upstream.InvestigateRequest(node_id=action.node_id), + ) + elif ( + action.action in ("tool_call", "use_item") + and action.node_id is not None + ): + request_type, handler = ( + (upstream.ToolCallRequest, upstream.tool_call) + if action.action == "tool_call" + else (upstream.UseItemRequest, upstream.use_item) + ) + result = handler( + self.case_id, + request_type( + node_id=action.node_id, arguments=action.arguments or {} + ), + ) + else: + result = { + "ok": False, + "error": "Unknown action or missing action parameter", + } + except HTTPException as exc: + result = {"ok": False, "error": exc.detail} + except ValueError: + result = {"ok": False, "error": "Malformed action"} + except Exception: + log.exception("Puzzle service failure") + self.reason = "infrastructure_error" + self.save() + raise + if self.reason is None and self.count >= self.max_actions: + self.reason = "action_budget_exhausted" + result = public(result) + result["episode"] = self.state() + self.save(payload, result) + return result + + +def create_app( + scenario_path=None, max_actions=None, evidence_dir=None, worker_url=None +): + episode = Episode( + scenario_path or os.environ["SCENARIO_PATH"], + max_actions or int(os.environ.get("MAX_ACTIONS", "500")), + evidence_dir if evidence_dir is not None else os.environ.get("EVIDENCE_DIR"), + worker_url if worker_url is not None else os.environ.get("WORKER_URL"), + ) + app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) + app.state.episode = episode + + @app.get("/health") + def health(): + return {"ok": True} + + @app.get("/observation") + def observation(): + return {**public(episode.initial), "episode": episode.state()} + + @app.get("/state") + def state(): + return episode.state() + + @app.post("/action") + def action(payload: dict): + try: + return episode.dispatch(payload) + except Exception: + return JSONResponse( + status_code=503, + content={"ok": False, "error": "Puzzle infrastructure failure"}, + ) + + return app diff --git a/tasks/agentescape-25-skeleton-3ae882d5/environment/puzzle/upstream/models.py b/tasks/agentescape-25-skeleton-3ae882d5/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3ae882d5/environment/puzzle/upstream/models.py @@ -0,0 +1,108 @@ +from enum import Enum +from typing import List, Dict, Any, Optional +from pydantic import BaseModel, Field + +# 1. 细粒度接口类型定义 +class InterfaceType(str, Enum): + ''' + BIG_INT + TEXT_GENERIC + HEX_STRING + FILE_ID + HEX_STRING_KEY_AES + HEX_STRING_IV_AES + CODE_PYTHON + HIDDEN_ITEM + ITEM + ''' + # --- 基础类型 --- + TEXT_GENERIC = "Text_Generic" + BIG_INT = "Big_Int" + + # --- 编码/格式化字符串 --- + HEX_STRING = "Hex_String" # 通用 Hex + + # --- 特定用途的 Hex 字符串 (用于精确匹配) --- + HEX_STRING_KEY_AES = "Hex_String_Key_AES" + HEX_STRING_IV_AES = "Hex_String_IV_AES" + + # --- 文件类型 --- + FILE_ID = "File_Id" + + # --- 代码/脚本 --- + CODE_PYTHON = "Code_Python" + + # --- 实体交互类型 (严格命名) --- + ITEM = "Item" # 主动掉落接口 (Tool -> Item) + HIDDEN_ITEM = "Hidden_Item" # 被动掉落接口 (Item -> Item) + +# 3. 端口定义 +class Port(BaseModel): + name: str + type: InterfaceType + description: str + +# 4. 统一节点定义 (融合工具和物品) +class Node(BaseModel): + id: str + name: str + description: str + type: str # "Tool" or "Item" + + # 接口定义 + inputs: List[Port] = [] + outputs: List[Port] = [] + + # 状态字段 + content: Optional[Any] = None # 物品有内容,工具为None + if_success: Optional[bool] = None # 工具初始为False,物品为None + initial_visible: bool = False + + # 运行时状态 (Server维护) + is_revealed: bool = False + + # 标记该 Tool 节点是否有待触发的 HIDDEN_ITEM 掉落 + # 当 Tool 按照 golden_input 正确执行且有 HIDDEN_ITEM 输出边时设为 True + # 在 investigate 该 Tool 时触发掉落并重置为 False + has_hidden_item_ready: bool = False + + # 初始输入值 (metadata.initial_values.init_inputs,用于渐进式暴露判断) + init_input_values: Dict[str, Any] = {} + + # Golden 输入值 (nodes[].inputs[].value,用于评测验证) + golden_input_values: Dict[str, Any] = {} + + # Golden 输出值 (nodes[].outputs[].value,用于评测验证和 Item 节点的 content) + golden_output_values: Dict[str, Any] = {} + + # 实际获得的输出值历史 (工具每次执行后实际返回的输出列表,用于渐进式暴露判断) + # 格式: List[Dict[str, Any]],每个元素是一次执行的输出字典 + actual_outputs_history: List[Dict[str, Any]] = [] + + # 逻辑规则 (用于终端机等复杂物品) + logic_rules: Optional[Dict[str, Any]] = None + + def copy(self, **kwargs): + """Helper to create a copy with updated fields.""" + data = self.dict() + data.update(kwargs) + return Node(**data) + +# 5. 边定义 (拓扑结构) +class Edge(BaseModel): + source_id: str + target_id: str + connection_type: InterfaceType # 直接使用 InterfaceType + # 如果是 Data_Flow,指定端口对应关系 + source_port: Optional[str] = None + target_port: Optional[str] = None + +# 6. 完整图定义 +class GraphScenario(BaseModel): + case_id: str + title: str + intro_narrative: str + nodes: Dict[str, Node] + edges: List[Edge] + difficulty: int + win_node_id: str # 标记哪个节点是最终目标(通常是一个提交工具或最终物品) diff --git a/tasks/agentescape-25-skeleton-3ae882d5/environment/puzzle/upstream/server.py b/tasks/agentescape-25-skeleton-3ae882d5/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-25-skeleton-3ae882d5/environment/puzzle/upstream/server.py @@ -0,0 +1,1490 @@ +import json +import os +import time +import logging +import random +from pathlib import Path +from typing import Dict, Any, List, Optional +from datetime import datetime +from collections import defaultdict +from fastapi import FastAPI, HTTPException, Request +from fastapi.responses import JSONResponse +from fastapi.middleware.cors import CORSMiddleware +from pydantic import BaseModel, Field + +from models import GraphScenario, Node, InterfaceType +# from generator import ScenarioGenerator +from simulator import ToolSimulator +import uvicorn + +# 配置日志 +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler('server.log'), + logging.StreamHandler() + ] +) +logger = logging.getLogger(__name__) + +app = FastAPI( + title="AgentEscapeBench Universal Server", + version="1.0.0", + description="Industrial-grade evaluation server for escape room AI agents" +) + +# 添加 CORS 支持 +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# In-memory State +SCENARIOS: Dict[str, GraphScenario] = {} +SIMULATORS: Dict[str, ToolSimulator] = {} # case_id -> ToolSimulator +RAW_NODES_DATA: Dict[str, Dict[str, Any]] = {} # case_id -> node_id -> raw node data (for template_id) +FILE_METADATA: Dict[str, Dict[str, Any]] = {} # case_id -> metadata (for initial_values access) + +# Performance monitoring +STATS: Dict[str, Any] = { + "total_requests": 0, + "successful_requests": 0, + "failed_requests": 0, + "tool_calls": defaultdict(int), + "investigates": defaultdict(int), + "use_items": defaultdict(int), + "case_loads": 0, + "start_time": datetime.now() +} + +# Request timing middleware +@app.middleware("http") +async def add_process_time_header(request: Request, call_next): + start_time = time.time() + STATS["total_requests"] += 1 + + try: + response = await call_next(request) + STATS["successful_requests"] += 1 + process_time = time.time() - start_time + response.headers["X-Process-Time"] = str(process_time) + logger.info(f"{request.method} {request.url.path} - {response.status_code} - {process_time:.3f}s") + return response + except Exception as e: + STATS["failed_requests"] += 1 + logger.error(f"{request.method} {request.url.path} - Error: {str(e)}") + raise + +# Exception handler +@app.exception_handler(Exception) +async def global_exception_handler(request: Request, exc: Exception): + logger.error(f"Unhandled exception: {exc}", exc_info=True) + return JSONResponse( + status_code=500, + content={ + "ok": False, + "error": "Internal server error", + "detail": str(exc) if os.getenv("DEBUG") else "An error occurred" + } + ) + +# Health check endpoint +@app.get("/health") +def health_check(): + """健康检查端点""" + uptime = (datetime.now() - STATS["start_time"]).total_seconds() + return { + "status": "healthy", + "version": "1.0.0", + "uptime_seconds": uptime, + "loaded_cases": len(SCENARIOS), + "stats": { + "total_requests": STATS["total_requests"], + "successful_requests": STATS["successful_requests"], + "failed_requests": STATS["failed_requests"], + "success_rate": STATS["successful_requests"] / max(STATS["total_requests"], 1) + } + } + +# Statistics endpoint +@app.get("/stats") +def get_stats(): + """获取详细统计信息""" + return { + "stats": STATS, + "loaded_cases": list(SCENARIOS.keys()), + "uptime": str(datetime.now() - STATS["start_time"]) + } + +def _apply_progressive_reveal_at_init(scenario: GraphScenario): + """ + 在初始化时应用渐进式暴露机制(基于ITEM/HIDDEN_ITEM边) + + 新逻辑: + - 如果一个节点没有 ITEM/HIDDEN_ITEM 类型的入边,它就是初始可见的 + - 如果一个节点有 ITEM/HIDDEN_ITEM 类型的入边,它初始不可见,需要等待上游触发 + + Args: + scenario: 场景对象 + """ + # 收集所有有 ITEM/HIDDEN_ITEM 入边的节点 + nodes_with_item_edges = set() + for edge in scenario.edges: + if edge.connection_type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + nodes_with_item_edges.add(edge.target_id) + + logger.info(f"Nodes with ITEM/HIDDEN_ITEM incoming edges: {nodes_with_item_edges}") + + # 设置初始可见性:没有 ITEM/HIDDEN_ITEM 入边的节点初始可见 + initially_visible_count = 0 + for node_id, node in scenario.nodes.items(): + if node_id not in nodes_with_item_edges: + node.is_revealed = True + initially_visible_count += 1 + logger.info(f"Initial visible (no ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + else: + node.is_revealed = False + logger.debug(f"Initial hidden (has ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + + logger.info(f"Progressive reveal initialized: {initially_visible_count}/{len(scenario.nodes)} nodes initially visible") + + +def _check_inputs_match_golden(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> bool: + """ + 检查实际输入参数是否与 golden inputs 完全匹配 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + True 表示所有 golden inputs 都存在且值匹配 + """ + if not golden_inputs: + return True # 如果没有 golden inputs,认为匹配 + + for key, expected_value in golden_inputs.items(): + actual_value = arguments.get(key) + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) != str(expected_value): + logger.debug(f"Input mismatch for '{key}': expected '{expected_value}', got '{actual_value}'") + return False + + return True + + +def _get_parameter_validation_feedback(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> Dict[str, Any]: + """ + 对源头节点的参数进行详细验证,返回验证反馈 + + 注意:不返回期望值(expected),避免泄漏答案 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + 包含验证结果的字典: + - all_correct: bool - 所有参数是否正确 + - correct_params: List[str] - 正确的参数名列表 + - incorrect_params: List[str] - 错误的参数名列表(不包含期望值) + """ + if not golden_inputs: + return { + "all_correct": True, + "correct_params": [], + "incorrect_params": [] + } + + correct_params = [] + incorrect_params = [] + + for key, actual_value in arguments.items(): + # 只对用户实际提交的参数给反馈,未提交的参数不评价 + if key not in golden_inputs: + continue # 该参数不在 golden 中,跳过(如 _golden_inputs 等内部参数) + expected_value = golden_inputs[key] + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) == str(expected_value): + correct_params.append(key) + else: + # 只记录参数名,不包含期望值,避免泄漏答案 + incorrect_params.append(key) + + # all_correct:用户提交的所有参数都正确,且覆盖了全部 golden 参数 + all_provided_correct = len(incorrect_params) == 0 + all_golden_covered = all(k in arguments for k in golden_inputs) + return { + "all_correct": all_provided_correct and all_golden_covered, + "correct_params": correct_params, + "incorrect_params": incorrect_params + } + + +def _is_source_node(node_id: str, scenario: GraphScenario) -> bool: + """ + 判断节点是否是源头节点(完全没有任何入边的节点) + + 源头节点定义: + - 没有任何类型的入边(包括 DATA、ITEM、HIDDEN_ITEM) + - 即没有任何上游节点 + + Args: + node_id: 节点ID + scenario: 场景对象 + + Returns: + True 表示是源头节点 + """ + for edge in scenario.edges: + if edge.target_id == node_id: + # 只要有任何入边,就不是源头节点 + return False + + return True + + +def _check_and_reveal_ready_nodes(scenario: GraphScenario, recent_outputs: Dict[str, Any], source_node_id: str) -> List[Dict[str, Any]]: + """ + 检查并释放参数齐全的隐藏节点(渐进式暴露机制) + + 核心逻辑: + 1. 维护"可见值集合":包含所有被测模型当前可以看到的值 + - init_inputs 的值(初始可见) + - 工具执行后的实际输出值(运行时获得) + - 可见 Item 的输出值 + 2. 检查隐藏节点:该节点的所有 golden_input 值是否都在可见值集合中 + 3. 如果是,则释放该节点 + + Args: + scenario: 场景对象 + recent_outputs: 最近执行的工具的输出 + source_node_id: 刚执行的工具节点ID + + Returns: + 新释放的节点列表 + """ + newly_revealed = [] + + # 构建"可见值集合"(Set of visible values) + # 存储格式:set of values (转为字符串) + visible_values = set() + + # 1. 添加有意义的 init_inputs 值到可见值集合 + # Item 的 init_inputs 不应该加入,因为它们在密室中完全用不到 + for node_id, node in scenario.nodes.items(): + # 跳过源头 Item 节点(没有入边的 Item) + if node.type == "Item": + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,跳过其 init_inputs + continue + + # 添加其他节点的 init_inputs + for port_name, init_value in node.init_input_values.items(): + if init_value: + visible_values.add(str(init_value)) + + # 2. 添加已执行工具的所有历史输出值 + for node_id, node in scenario.nodes.items(): + if node.type == "Tool" and node.if_success and node.actual_outputs_history: + # 遍历所有历史执行记录 + for output_dict in node.actual_outputs_history: + for output_port_name, output_value in output_dict.items(): + if output_value: + visible_values.add(str(output_value)) + + # 3. 添加已被 investigate 的 Item 的 golden 输出值 + # 注意:Item 可见不等于其输出值可见,需要 investigate 后才能获得 + # 这里我们使用 actual_outputs_history 来标记 Item 是否已被 investigate + for node_id, node in scenario.nodes.items(): + if node.type == "Item" and node.is_revealed and node.actual_outputs_history: + # Item 通常只会被 investigate 一次,但为了一致性也使用历史列表 + for output_dict in node.actual_outputs_history: + for port_name, port_value in output_dict.items(): + if port_value: + visible_values.add(str(port_value)) + + # 遍历所有隐藏的节点,检查其 golden_input 是否都在可见值集合中 + for node_id, node in scenario.nodes.items(): + # 跳过已可见的节点 + if node.is_revealed: + continue + + # 只检查工具节点(物品节点由 ITEM 输出触发) + if node.type != "Tool": + continue + + # 检查该节点的所有 golden_input 值是否都在可见值集合中 + all_inputs_ready = True + missing_values = [] + + for input_port_name, golden_input_value in node.golden_input_values.items(): + # 检查这个 golden 值是否在可见值集合中 + if str(golden_input_value) not in visible_values: + all_inputs_ready = False + missing_values.append(f"{input_port_name}={golden_input_value}") + + # 如果所有 golden_input 值都在可见值集合中,释放该节点 + if all_inputs_ready and len(node.golden_input_values) > 0: + logger.info(f"All golden inputs ready for {node_id}: {list(node.golden_input_values.values())}") + + # 如果所有输入都齐全,释放该节点 + if all_inputs_ready: + node.is_revealed = True + + # 构建节点信息返回给模型 + node_info = { + "id": node.id, + "type": node.type, + "can_investigate": True, + "hint": "This tool's input parameters are now complete, you can use investigate to view detailed information" + } + + # if node.name: + # node_info["name"] = node.name + if node.description: + node_info["description"] = node.description + + newly_revealed.append(node_info) + logger.info(f"Progressive reveal: {node_id} is now ready (all inputs satisfied)") + + return newly_revealed + + +def _initialize_node_values(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]): + """ + Initialize node state and load values from port value fields. + 应用渐进式暴露机制:初始时只显示参数齐全的节点(源头节点) + + 重要区分: + 1. input_values: 只加载 metadata.initial_values 中的 init_inputs(真正的初始值) + 2. output_values: 加载 nodes[].outputs[].value(golden 输出,用于验证) + """ + # 第一步:加载所有节点的值,并将所有节点初始设为隐藏 + initial_values = metadata.get('initial_values', {}) + + for node_id, node in scenario.nodes.items(): + # 忽略 initial_visible 字段,初始全部隐藏 + # 由渐进式暴露机制根据参数齐全情况决定是否显示 + node.is_revealed = False + + if node.type == "Tool": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + elif node.type == "Item": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + + # 从 JSON 加载值 + if node_id in raw_nodes_data: + node_data = raw_nodes_data[node_id] # node_data是json文件中nodes中的字典 + + # 【重要】只加载 metadata.initial_values 中的初始输入值 + if node_id in initial_values: + init_data = initial_values[node_id] + # 加载初始输入值(用于渐进式暴露判断) + for port_name, port_value in init_data.get('init_inputs', {}).items(): + node.init_input_values[port_name] = port_value + + # 【评测用】加载 golden 输入值(用于验证模型传入的参数是否正确) + for input_port_data in node_data.get('inputs', []): + if 'value' in input_port_data: + node.golden_input_values[input_port_data['name']] = input_port_data['value'] + + # 【评测用】加载 golden 输出值(用于验证工具调用是否正确,以及 Item 节点的 content) + for output_port_data in node_data.get('outputs', []): + if 'value' in output_port_data: + node.golden_output_values[output_port_data['name']] = output_port_data['value'] + + # For Items, set content from golden_output_values + if node.type == "Item" and node.golden_output_values: + # Item 的 content 是其第一个 golden 输出值 + node.content = list(node.golden_output_values.values())[0] + + # 第二步:应用渐进式暴露机制 + # 检查所有节点,根据参数齐全情况释放源头节点(工具 + Item) + _apply_progressive_reveal_at_init(scenario) + +def _build_node_info(node: Node, raw_nodes_data: Dict[str, Any]) -> Dict[str, Any]: + """ + 构建节点信息(工具或物品) + + Args: + node: 节点对象 + raw_nodes_data: 原始节点数据(用于获取 template_id 等) + + Returns: + 节点信息字典 + """ + if node.type == "Tool": + # 过滤掉输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口) + # 这些端口仅用于控制掉落机制,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + tool_info = { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Tool", + "inputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.inputs if p.type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]], + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id(工具的标准名称) + if node.id in raw_nodes_data: + node_data = raw_nodes_data[node.id] + template_id = node_data.get('template_id') + if template_id: + tool_info['template_id'] = template_id + + return tool_info + + elif node.type == "Item": + return { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Item" + } + + else: + return { + "id": node.id, + # "name": node.name, + "type": node.type + } + +def _get_initial_observation(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]) -> Dict[str, Any]: + """ + Generate initial observation for the agent (what they see when entering the room). + + 策略: + - Tools: 只显示名称和描述,不显示接口定义。需要 investigate 才能获得详细接口信息。 + - Items: 只显示存在,不显示内容。需要 investigate 才能获得内容值。 + - init_inputs: 作为"可用信息"告诉模型,这些是可以用作工具参数的初始值。 + - init_outputs: 不告诉模型(这些是答案,需要模型通过调用工具获得)。 + """ + available_entities = [] # 统一的实体列表(Tools 和 Items) + available_information = [] # 可用的初始信息(来自 init_inputs) + + # 从 metadata.initial_values 提取 init_inputs 作为可用信息 + # 只提供值本身,不透露这些值对应哪个节点的哪个参数,让模型自己推理 + # 注意:跳过源头 Item(没有入边的 Item)的 init_inputs,因为它们在密室中完全用不到 + initial_values = metadata.get('initial_values', {}) + # initial_values字段的格式 + # "initial_values": { + # "terminal_1": { + # "init_inputs": {}, + # "init_outputs": { + # "text_output": "System initialization complete.", + # "hex_output": "48656c6c6f20576f726c64", + # "item_dispenser": "掉落了一张纸条,上面写着“请勿随意触摸终端”" + # } + # } + # } + for node_id, init_data in initial_values.items(): + # 获取节点信息,判断是否为源头 Item + node = scenario.nodes.get(node_id) + if node and node.type == "Item": + # 检查是否为源头 Item(没有入边) + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,检查是否有 init_inputs + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 有 init_inputs,需要暴露这些参数 + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + # 处理完后跳过后续的通用逻辑 + continue + + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 为每个 init_input 值创建一个信息条目(不包含 source_node 和 parameter 信息) + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + + for node in scenario.nodes.values(): + if node.is_revealed: + # Tools: 只显示基本信息,提示可以 investigate 查看详细接口 + if node.type == "Tool": + tool_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Tool", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the tool's detailed interface information for calling" + } + # 只在 name 非空时添加 + # if node.name: + # tool_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_info["description"] = node.description + + available_entities.append(tool_info) + + # Items: 只显示基本信息,提示可以 investigate 查看内容 + elif node.type == "Item": + item_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Item", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the item's content" + } + # 只在 name 非空时添加 + # if node.name: + # item_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + item_info["description"] = node.description + + available_entities.append(item_info) + + return { + "narrative": scenario.intro_narrative, + "available_entities": available_entities, # 使用统一的实体列表 + "available_information": available_information, # 可用的初始信息(只包含 init_inputs) + "win_node_id": scenario.win_node_id # 胜利节点ID,让模型知道需要关注哪个节点 + } + +@app.post("/env/reset") +def reset_case(case_id: str = None, case_file_path: str = None, session_id: str = None): + """Loads a specific case from file and resets it. + + Args: + case_id: Optional case ID for resetting an existing case + case_file_path: Path to case file for loading a new case + session_id: Optional session ID to ensure isolation between concurrent evaluations + """ + logger.info(f"Reset request - case_id: {case_id}, case_file_path: {case_file_path}, session_id: {session_id}") + STATS["case_loads"] += 1 + + if case_file_path: + if not os.path.exists(case_file_path): + logger.error(f"Case file not found: {case_file_path}") + raise HTTPException(status_code=404, detail=f"File not found: {case_file_path}") + try: + with open(case_file_path, "r", encoding="utf-8") as f: + file_data = json.load(f) + + # 转换格式:从 DAG executor 生成的格式转换为 GraphScenario 格式 + # 1. 提取 metadata + metadata = file_data.get('metadata', {}) + + # 2. 生成 case_id, title, intro_narrative + # 【修复】为每个评测会话生成唯一的 case_id,防止并发评测时状态污染 + base_name = os.path.basename(case_file_path).replace('.json', '').replace('_full', '').replace('_full2', '') + + if session_id: + # 如果提供了 session_id,使用它来确保唯一性 + case_id = f"{base_name}_{session_id}" + else: + # 否则使用时间戳和随机数确保唯一性 + unique_suffix = f"{int(time.time() * 1000)}_{random.randint(1000, 9999)}" + case_id = f"{base_name}_{unique_suffix}" + + file_data['case_id'] = case_id + logger.info(f"Generated unique case_id: {case_id} (base: {base_name}, session: {session_id})") + + if 'title' not in file_data: + file_data['title'] = f"Escape Room: {file_data['case_id']}" + + if 'intro_narrative' not in file_data: # 目前的json文件中已经有了intro_narrative字段,不会使用下面一行的内容,而是使用每个评测问题的json文件中的对应字段 + 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]".' + + # 3. 转换 nodes 列表为字典(DAG executor 生成的文件中 nodes 是列表格式) + nodes_dict = {} + for node_data in file_data['nodes']: + nodes_dict[node_data['id']] = node_data # 这里的id是template_id之后可能添加一个后缀 + file_data['nodes'] = nodes_dict # 把列表转成一个字典 + + # 4. 添加缺失的字段 + if 'difficulty' not in file_data: + file_data['difficulty'] = metadata.get('total_nodes', 5) + + if 'win_node_id' not in file_data: + file_data['win_node_id'] = metadata.get('win_node_id', '') + + scenario = GraphScenario(**file_data) + + # Extract raw nodes data for template_id access + # nodes 已经在上面转换为字典格式 + raw_nodes_data = file_data.get('nodes', {}) + RAW_NODES_DATA[scenario.case_id] = raw_nodes_data + + # Store metadata for initial values access + FILE_METADATA[scenario.case_id] = metadata + + logger.info(f"Successfully parsed case file: {scenario.case_id}, nodes: {len(scenario.nodes)}, edges: {len(scenario.edges)}") + except Exception as e: + logger.error(f"Failed to load case file: {str(e)}", exc_info=True) + raise HTTPException(status_code=500, detail=f"Failed to load case file: {str(e)}") + + # Initialize node state and load values + _initialize_node_values(scenario, raw_nodes_data, metadata) + + SCENARIOS[scenario.case_id] = scenario + simulator = ToolSimulator() + SIMULATORS[scenario.case_id] = simulator + + 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'])}") + + # 生成初始观察信息(进入密室后看到的环境) + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + ''' + initial_observation的格式: + { + "narrative": scenario.intro_narrative, + "available_entities": available_entities # 使用统一的实体列表 + "available_information": available_information # 可用的初始信息(只包含 init_inputs) + } + ''' + + return { + "ok": True, + "message": f"Case loaded from {case_file_path}", + "case_id": scenario.case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果没有提供 case_file_path,但提供了 case_id,则尝试从内存重置 + if case_id and case_id in SCENARIOS: + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + metadata = FILE_METADATA.get(case_id, {}) + + # Reset dynamic fields and re-apply progressive reveal + # 重新初始化节点状态(包括渐进式暴露) + _initialize_node_values(scenario, raw_nodes_data, metadata) + + 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'])}") + + # 生成初始观察信息 + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + + return { + "ok": True, + "message": f"Case {case_id} reset.", + "case_id": case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果既没有 case_file_path,也没有在内存中找到,返回错误 + raise HTTPException( + status_code=400, + detail="Must provide case_file_path to load a new case, or use case_id to reset an existing case." + ) + +class InvestigateRequest(BaseModel): + node_id: str + +@app.post("/env/{case_id}/investigate") +def investigate(case_id: str, req: InvestigateRequest): + """ + Investigates a Tool or Item to reveal detailed information. + + - For Tools: Returns detailed interface information (inputs/outputs) needed to call the tool + - For Items: Returns content value and triggers hidden item drops + """ + logger.info(f"Investigate request - case_id: {case_id}, node_id: {req.node_id}") + STATS["investigates"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + node = scenario.nodes[req.node_id] + + if not node.is_revealed: + logger.warning(f"Attempt to investigate hidden node: {req.node_id}") + return {"ok": False, "error": "Node is not visible yet."} + + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + newly_revealed = [] + + # 处理 Tool 的 investigate + if node.type == "Tool": + logger.info(f"Investigating tool: {req.node_id}") + + # 返回工具的详细接口信息 + # id 字段使用 node.id(节点唯一标识),agent 用这个字段识别和调用具体的节点 + # template_id 是工具类型标识符,Agent 内部用于判断工具特性(如 terminal 类工具参数可选) + # 注意:只过滤输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口),这些端口仅用于控制掉落,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + # 【端口上游依赖提示 & 初始值直接给出】 + # 针对参数语义模糊(全为数字类型)的工具,在 investigate 返回信息中标注 + # 哪个输入端口来自哪个上游节点(upstream_from)。 + # 对于所有工具:若该节点不是纯源头节点(有任意数据流入边), + # 且某个端口没有上游入边(值来自初始可见参数),则直接给出该端口的 golden input 值。 + AMBIGUOUS_TOOLS = { + "num_base_convert", "calc_modexp", "calc_modexp_int", + "calc_inv_mod", "calc_inv_mod_int", "crypto_rsa_decrypt_hex", "geo_haversine" + } + # Terminal 类工具自带参数对错反馈机制,玩家/模型可自行试错, + # 无需在 investigate 时直接暴露 init_value + SELF_FEEDBACK_TOOLS = { + "terminal_1", "terminal_2", + "Logic Terminal", "Math Terminal", "Encryption Terminal", "Sequence Terminal" + } + _template_id_for_hint = raw_nodes_data.get(node.id, {}).get("template_id", "") + # 构建数据流入边映射(对所有工具):{target_port -> (source_node_id, source_port)} + _upstream_map = {} + for _edge in scenario.edges: + if (_edge.target_id == node.id + and _edge.connection_type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM] + and _edge.target_port is not None): + _upstream_map[_edge.target_port] = (_edge.source_id, _edge.source_port) + # 判断该节点是否有任意数据流入边(即不是纯源头节点) + _has_any_upstream = len(_upstream_map) > 0 + # 判断该节点是否有任意入边(包括 ITEM/HIDDEN_ITEM 掉落边) + # 有任意入边(含掉落边)但无数据流入边的节点,其输入来自初始可见参数,应直接给出 + _has_any_edge = any(_edge.target_id == node.id for _edge in scenario.edges) + # 构建 inputs 列表 + _inputs_list = [] + for p in node.inputs: + if p.type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + continue + port_dict = {"name": p.name, "type": p.type, "description": p.description} + if p.name in _upstream_map: + # 该端口有上游数据流依赖,且属于语义模糊工具 → 标注来源 + if _template_id_for_hint in AMBIGUOUS_TOOLS: + src_node_id, src_port = _upstream_map[p.name] + port_dict["upstream_from"] = f"{src_node_id}.{src_port}" if src_port else src_node_id + elif _has_any_edge and _template_id_for_hint not in SELF_FEEDBACK_TOOLS: + # 该节点有任意入边,但此端口没有数据流入边 → 值来自初始可见参数,直接给出 + # 排除自带反馈机制的 terminal 类工具(它们通过执行结果反馈对错,无需提前暴露参数值) + golden_val = node.golden_input_values.get(p.name) + if golden_val is not None: + port_dict["init_value"] = golden_val + _inputs_list.append(port_dict) + + tool_details = { + "id": node.id, # 节点 ID,用于唯一标识和调用这个具体节点 + "type": "Tool", + "inputs": _inputs_list, + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id 用于 Agent 内部判断工具类型(不会展示给被测模型) + if node.id in raw_nodes_data: + template_id = raw_nodes_data[node.id].get('template_id') + if template_id: + tool_details["_template_id"] = template_id # 使用下划线前缀标记为内部字段 + + # 只在 name 非空时添加 + # if node.name: + # tool_details["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_details["description"] = node.description + + # 添加 narrative 字段(如果存在) + if node.id in raw_nodes_data: + narrative = raw_nodes_data[node.id].get('narrative') + if narrative: + tool_details['narrative'] = narrative + + # 不再返回 init_values,避免泄漏答案 + # investigate 只应该返回工具的接口定义,不应该暴露初始值 + + # 【新增】检查该 Tool 是否有待触发的 HIDDEN_ITEM 掉落 + # 如果该工具已按照 golden_input 正确执行,且有 HIDDEN_ITEM 输出边,则触发掉落 + if node.has_hidden_item_ready: + logger.info(f"Tool has HIDDEN_ITEM ready - triggering passive drop for: {req.node_id}") + + # 遍历该工具的所有 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + # 重置标志,已经触发过了,避免重复 + node.has_hidden_item_ready = False + + logger.info(f"Tool investigation successful - node: {req.node_id}, revealed: {len(newly_revealed)}") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Tool", + "details": tool_details + } + + # 如果有新掉落的节点,添加到响应中 + if newly_revealed: + result["newly_revealed"] = newly_revealed + + return result + + # 处理 Item 的 investigate + elif node.type == "Item": + logger.info(f"Investigating item: {req.node_id}") + + # 【第一步】检查该 Item 是否有需要参数的输入端口 + # 如果有,且尚未通过 use_item 验证,则不返回内容,只返回参数要求 + required_inputs = [] + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + inputs_info = raw_node.get('inputs', []) + required_inputs = [ + { + "name": inp.get("name"), + "type": inp.get("type"), + "description": inp.get("description", "") + } + for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + # 如果有 required_inputs 且尚未通过 use_item 验证(if_success == False) + # 则不返回内容,只返回参数要求提示 + if required_inputs and not node.if_success: + logger.info(f"Item has required inputs and not yet unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "required_inputs": required_inputs + } + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + param_names = ', '.join([inp['name'] for inp in required_inputs]) + 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}" + + return result + + # 【新增】如果有 required_inputs 且已经通过 use_item 验证(if_success == True) + # 则返回提示:该节点已经被成功解决 + if required_inputs and node.if_success: + logger.info(f"Item has required inputs and already unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "message": "This item has already been successfully unlocked by you." + } + return result + + # 【第二步】该 Item 没有 required_inputs 或已通过验证,返回内容 + # 1. 返回 Item 的 golden_output_values(即 Item 的内容) + # 注意:某些 Item 仅用于触发 HIDDEN_ITEM 掉落,没有实际内容 + has_actual_content = bool(node.golden_output_values) or node.content is not None + content = node.golden_output_values if node.golden_output_values else node.content + + # 【关键】将 golden_output_values 追加到 actual_outputs_history,标记该 Item 已被 investigate + # 这样在渐进式暴露时,这些值才会被加入可见值集合 + # 即使是空字典(仅触发 HIDDEN_ITEM 的 Item),也要记录,以便渐进式暴露逻辑知道该 Item 已被调查 + if node.golden_output_values is not None: + node.actual_outputs_history.append(dict(node.golden_output_values)) + + # 2. Trigger Hidden Item Drops (Passive Drop) + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + logger.info(f"Item investigation successful - node: {req.node_id}, has_content: {has_actual_content}, revealed: {len(newly_revealed)}") + + # 【渐进式暴露】旧机制(基于 golden_input)已禁用 + # 现在完全由 ITEM/HIDDEN_ITEM 边触发控制节点可见性 + # 上面的 HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, node.golden_output_values or {}, node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # logger.info(f"Progressive reveal after Item investigate: {len(progressive_revealed)} nodes now ready") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Item" + } + + # 只在有实际内容时才添加 content 字段 + # 对于仅触发 HIDDEN_ITEM 掉落的 Item,不返回 content 字段,避免返回 None 或空字典让模型困惑 + if has_actual_content: + result["content"] = content + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型通过 investigate 获得内容后,需要自己识别这是否是胜利字符串 + + return result + + else: + logger.warning(f"Attempt to investigate unknown node type: {req.node_id} (type: {node.type})") + return {"ok": False, "error": f"Cannot investigate node type: {node.type}"} + +class ToolCallRequest(BaseModel): + node_id: str # 使用 node_id 精确指定要调用的节点 + arguments: Dict[str, Any] + +@app.post("/env/{case_id}/tool_call") +def tool_call(case_id: str, req: ToolCallRequest): + """Executes a tool and triggers item drops.""" + logger.info(f"Tool call request - case_id: {case_id}, node_id: {req.node_id}, args: {list(req.arguments.keys())}") + STATS["tool_calls"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + + # 通过 node_id 精确查找节点 + node_id = req.node_id + if node_id not in scenario.nodes: + logger.error(f"Node not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + tool_node = scenario.nodes[node_id] + + if not tool_node: + logger.error(f"Tool not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Tool not found") + + if not tool_node.is_revealed: + logger.warning(f"Attempt to call hidden tool: {node_id}") + return {"ok": False, "error": "Tool is not visible yet."} + + if tool_node.type != "Tool": + logger.warning(f"Attempt to call non-tool node: {node_id} (type: {tool_node.type})") + return {"ok": False, "error": "Only tools can be called."} + + # 1. Execute Tool (Real Execution via Simulator) + simulator = SIMULATORS[case_id] + + # Get tool name from template_id if available, otherwise use node name + tool_name = tool_node.name + if case_id in RAW_NODES_DATA and node_id in RAW_NODES_DATA[case_id]: + template_id = RAW_NODES_DATA[case_id][node_id].get('template_id') + if template_id: + tool_name = template_id + + # 文件处理工具和 Terminal 需要验证输入并返回预先计算的输出 + # 传递节点的实际输入输出值(从 DAG 执行后填充的数据) + tool_arguments = dict(req.arguments) # Make a copy + + # 传递节点的 golden values(从 JSON 的 inputs[].value 和 outputs[].value 加载) + # 用于在评测阶段验证被测模型传入的参数是否正确 + if tool_node.golden_input_values: + tool_arguments['_golden_inputs'] = tool_node.golden_input_values + if tool_node.golden_output_values: + tool_arguments['_golden_outputs'] = tool_node.golden_output_values + + logger.debug(f"Executing tool {tool_name} (node: {tool_node.name}) with args {tool_arguments}") + + try: + output_values = simulator.execute(tool_name, tool_arguments) + logger.info(f"Tool invoked - {tool_name}: {list(output_values.keys())}") + except Exception as e: + logger.error(f"Tool execution failed - {tool_name}: {str(e)}", exc_info=True) + return {"ok": False, "error": f"Tool execution failed: {str(e)}"} + + # 检查验证结果(精细化错误反馈) + validation = output_values.pop("_validation", {"valid": True}) + + if not validation["valid"]: + # 根据错误类型构造友好的错误消息 + error_type = validation.get("error_type") + + if error_type == "missing_required": + missing = validation.get("missing_params", []) + error_msg = f"Error: Missing required parameters {', '.join(missing)}" + + elif error_type == "type_error": + param = validation.get("param_name") + message = validation.get("message", "Parameter type error") + error_msg = f"Error: {message}" + + elif error_type == "incomplete_optional": + provided = validation.get("provided_params", []) + missing = validation.get("missing_params", []) + error_msg = ( + f"Hint: You provided some parameters ({', '.join(provided)}), " + f"but may also need: {', '.join(missing)}.\n" + f"Trying to provide these parameters together might yield better results." + ) + + elif error_type == "value_mismatch": + param = validation.get("param_name") + hint = validation.get("hint", "Parameter value may be incorrect") + error_msg = f"Hint: {hint}.\nPlease check if this parameter value meets the requirements." + + else: + error_msg = validation.get("hint") or validation.get("message", "Parameter validation failed") + + logger.info(f"Tool validation failed - {tool_name}: {error_type}") + return { + "ok": False, + "error": error_msg, + "error_type": error_type + } + + # Simulate success + tool_node.if_success = True + + # 【关键】将本次执行的输出值追加到历史列表(用于渐进式暴露判断) + # 每次调用都会记录,不会覆盖之前的执行结果 + tool_node.actual_outputs_history.append(dict(output_values)) + + # 2. 检查是否应该触发掉落(只有输入参数正确时才掉落) + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, tool_node.golden_input_values) + + newly_revealed = [] + investigate_hints = [] # 提示模型哪些节点可以 investigate 来发现隐藏内容 + + if inputs_match_golden: + logger.info(f"✓ Tool inputs match golden - node: {node_id}, triggering drops") + + # 检查该工具是否有 ITEM 或 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == tool_node.id: + target_node = scenario.nodes[edge.target_id] + + # ITEM 边:立即掉落(主动掉落) + if edge.connection_type == InterfaceType.ITEM: + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from {node_id})") + + # HIDDEN_ITEM 边:不立即掉落,标记并提示(被动掉落) + elif edge.connection_type == InterfaceType.HIDDEN_ITEM: + # 标记该工具有待触发的 HIDDEN_ITEM 掉落 + tool_node.has_hidden_item_ready = True + + # 提示模型可以 investigate 这个工具来发现隐藏内容 + hint_info = { + "tool_id": tool_node.id, + "hint": f"Tool '{tool_node.id}' seems to hide something, try investigating it to discover more information" + } + # if tool_node.name: + # hint_info["tool_name"] = tool_node.name + + investigate_hints.append(hint_info) + logger.info(f"HIDDEN_ITEM ready: {tool_node.id} -> {target_node.id} (will drop on investigate)") + else: + logger.info(f"✗ Tool inputs do NOT match golden - node: {node_id}, no drops triggered") + + response = { + "ok": True, + "message": "Tool invoked", + "output_values": output_values # Return raw outputs to Agent + } + + # 【新增】对源头节点进行参数验证反馈 + # 源头节点:没有数据流入边的节点,这些节点的参数需要模型自己推理 + # 验证模型使用的参数是否正确,并提供明确的反馈 + if _is_source_node(node_id, scenario) and tool_node.golden_input_values: + validation_feedback = _get_parameter_validation_feedback(req.arguments, tool_node.golden_input_values) + + if validation_feedback["all_correct"]: + # 用户提交了全部 golden 参数且全部正确 + response["parameter_feedback"] = { + "status": "correct", + "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." + } + logger.info(f"✓ Source node parameters all correct - node: {node_id}") + elif validation_feedback["incorrect_params"]: + # 有提交了但值错误的参数,只对这些参数给出反馈 + incorrect_list = [] + for param_name in validation_feedback["incorrect_params"]: + incorrect_list.append(f" - Parameter '{param_name}' is incorrect") + + correct_info = "" + if validation_feedback["correct_params"]: + correct_info = f"\n✓ Correct parameters: {', '.join(validation_feedback['correct_params'])}" + + response["parameter_feedback"] = { + "status": "incorrect", + "message": ( + f"⚠️ Some parameters are incorrect:\n" + + "\n".join(incorrect_list) + + correct_info + + 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." + ), + "incorrect_params": validation_feedback["incorrect_params"], + "correct_params": validation_feedback["correct_params"] + } + logger.info(f"✗ Source node parameters incorrect - node: {node_id}, incorrect: {validation_feedback['incorrect_params']}") + # else: 部分提交且全部正确 → 不给任何 parameter_feedback,避免对未提交的参数发表意见 + + # 检查工具调用是否完全正确(输出与 golden outputs 匹配) + # 用于给模型正向反馈,让它知道这个工具已经正确调用过,避免重复调用 + # 注意:只有当输出完全匹配时才标记为 correct,不会在错误时提供具体错误信息 + # if tool_node.golden_output_values and output_values: + # is_correct = True + # for port_name, expected_value in tool_node.golden_output_values.items(): + # actual_value = output_values.get(port_name) + # if str(actual_value) != str(expected_value): + # is_correct = False + # break + + # if is_correct: + # response["tool_call_correct"] = True + # logger.info(f"✓ Tool called with correct result - node: {node_id}") + + # 只在有新内容掉落时才返回 newly_revealed + if newly_revealed: + response["newly_revealed"] = newly_revealed + + # 添加 investigate 提示(对于有待触发 HIDDEN_ITEM 掉落的工具) + if investigate_hints: + response["investigate_hints"] = investigate_hints + + # 3. 渐进式暴露机制 - 现在完全由 ITEM/HIDDEN_ITEM 边控制 + # 旧机制(基于 golden_input 检查)已被禁用 + # 新机制中,节点的可见性只由 ITEM/HIDDEN_ITEM 边触发决定 + # 上面的 ITEM/HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, output_values, tool_node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # response["newly_revealed"] = newly_revealed + # logger.info(f"Progressive reveal: {len(progressive_revealed)} nodes now ready") + + # Check if this is the win node + if node_id == scenario.win_node_id: + # 验证输出值是否等于预期的胜利值 + # 从节点的 golden_output_values 中获取预期值(在 _initialize_node_values 时从 JSON 加载) + expected_outputs = tool_node.golden_output_values + + # 检查实际输出是否与预期输出匹配 + is_correct = False + victory_string = None + mismatch_info = [] + + if expected_outputs and output_values: + # 检查每个预期输出端口的值是否匹配 + is_correct = True + for port_name, expected_value in expected_outputs.items(): + actual_value = output_values.get(port_name) + if actual_value != expected_value: + is_correct = False + mismatch_info.append(f"Port '{port_name}': expected '{expected_value}', actual '{actual_value}'") + logger.warning(f"Win node output mismatch - port: {port_name}, expected: {expected_value}, actual: {actual_value}") + + # 如果所有输出都匹配,使用第一个输出作为胜利字符串 + if is_correct and output_values: + victory_string = list(output_values.values())[0] + else: + logger.warning(f"Win node called but missing output values - expected: {expected_outputs}, actual: {output_values}") + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型调用工具获得输出后,需要自己识别这是否是胜利字符串并提交 + if is_correct: + logger.info(f"🎯 Win node called with correct output - case: {case_id}, node: {node_id}, victory: {victory_string}") + else: + logger.info(f"❌ Win node called with incorrect output - case: {case_id}, node: {node_id}") + + return response + +class UseItemRequest(BaseModel): + node_id: str = Field(..., description="The ID of the Item node to use (must be Item type)") + arguments: Dict[str, Any] = Field(default_factory=dict, description="Input arguments to provide to the item") + +@app.post("/env/{case_id}/use_item") +def use_item(case_id: str, req: UseItemRequest): + """ + Use an Item node by providing input arguments. + + This is specifically for Item nodes that require parameters to be "unlocked" or "activated", + such as containers that need a password/fingerprint. + + - Validates that the node is of type Item + - Checks if provided arguments match the item's golden_input_values + - If match: triggers ITEM-type edge drops and returns the item's content + - If not match: returns error message + """ + logger.info(f"Use item request - case_id: {case_id}, node_id: {req.node_id}, args: {req.arguments}") + STATS["use_items"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + item_node = scenario.nodes[req.node_id] + + if not item_node.is_revealed: + logger.warning(f"Attempt to use hidden item: {req.node_id}") + return {"ok": False, "error": "Item is not visible yet."} + + if item_node.type != "Item": + logger.warning(f"Attempt to use non-item node: {req.node_id} (type: {item_node.type})") + return {"ok": False, "error": "Only Item nodes can be used with use_item. Tools should be called with tool_call."} + + # 【新增】检查该 Item 是否已经被成功解锁 + # 如果已经被正确使用过,直接返回成功提示 + if item_node.if_success: + logger.info(f"Item already unlocked, returning success message: {req.node_id}") + return { + "ok": True, + "message": "This item has already been successfully unlocked by you." + } + + # 检查该 Item 是否真的需要通过 use_item 提供参数 + # 只有当 Item 有非 Item/Hidden_Item 类型的输入时,才应该使用 use_item + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + non_hidden_inputs = [ + inp for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + if not non_hidden_inputs: + # 该 Item 不需要参数,应该只使用 investigate + logger.warning(f"Attempt to use_item on a node that doesn't require parameters: {req.node_id}") + return { + "ok": False, + "error": "This item does not require parameters. Please use investigate to examine the item directly." + } + + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, item_node.golden_input_values) + + if not inputs_match_golden: + logger.info(f"✗ Item inputs do NOT match golden - node: {req.node_id}") + # 提供更详细的错误信息,帮助 Agent 理解问题 + # 只显示非 Item/Hidden_Item 类型的参数(Hidden_Item 由系统自动处理) + expected_params = [] + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + expected_params = [ + inp.get("name") for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + provided_params = list(req.arguments.keys()) if req.arguments else [] + + # 检查参数名是否匹配 + if set(expected_params) == set(provided_params): + # 参数名正确但值不匹配 - 不泄漏正确的值 + error_msg = f"Parameter names are correct, but the parameter values are incorrect. Please try using different parameter values." + else: + error_msg = f"Parameter names do not match. Expected parameter names: {expected_params}, you provided: {provided_params}." + + return { + "ok": False, + "error": error_msg + } + + logger.info(f"✓ Item inputs match golden - node: {req.node_id}, activating item") + + # 标记该 Item 已被正确使用 + item_node.if_success = True + + # 将 golden_output_values 追加到 actual_outputs_history + if item_node.golden_output_values: + item_node.actual_outputs_history.append(dict(item_node.golden_output_values)) + + # 触发 ITEM 类型边的掉落 + newly_revealed = [] + for edge in scenario.edges: + if edge.source_id == item_node.id and edge.connection_type == InterfaceType.ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from use_item on {req.node_id})") + + # 检查是否为 Win Node + win_node_id = scenario.win_node_id + is_win_node = (req.node_id == win_node_id) + + # 构建返回结果 + result = { + "ok": True, + "message": "Item used successfully.", + "content": item_node.golden_output_values if item_node.golden_output_values else None + } + + # 获取 narrative(如果存在) + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + narrative = raw_nodes_data[req.node_id].get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 如果是 Win Node,只记录日志 + if is_win_node: + logger.info(f"Win node (Item) unlocked via use_item - case: {case_id}, node: {req.node_id}") + + return result + + +class SubmitAnswerRequest(BaseModel): + answer: str = Field(..., description="The victory string to submit") + +@app.post("/env/{case_id}/submit_answer") +def submit_answer(case_id: str, req: SubmitAnswerRequest): + """ + 提交答案接口 + 被测模型在获得胜利字符串提示后,需要调用此接口提交答案 + """ + logger.info(f"Submit answer request - case_id: {case_id}, answer: {req.answer}") + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + + # 获取 win_node 的 golden_output_values + if not scenario.win_node_id: + logger.error(f"No win node defined for case: {case_id}") + return { + "ok": False, + "error": "This case has no victory node defined" + } + + win_node = scenario.nodes.get(scenario.win_node_id) + if not win_node: + logger.error(f"Win node not found: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node does not exist" + } + + # 获取正确的胜利字符串(取第一个 golden_output_value) + if win_node.golden_output_values: + correct_answer = list(win_node.golden_output_values.values())[0] + else: + logger.error(f"Win node has no golden_output_values: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node has no correct answer" + } + + # 验证提交的答案 + if req.answer == correct_answer: + logger.info(f"🎉 CORRECT ANSWER SUBMITTED - case: {case_id}, answer: {req.answer}") + return { + "ok": True, + "is_win": True, + "victory_message": f"🎉 Congratulations on successfully escaping the room! Your answer is correct: {req.answer}" + } + else: + logger.info(f"❌ INCORRECT ANSWER SUBMITTED - case: {case_id}, submitted: {req.answer}, correct: {correct_answer}") + return { + "ok": True, + "is_win": False, + "error": f"The submitted answer is incorrect. You submitted: {req.answer}" + } + +if __name__ == "__main__": + + uvicorn.run(app, host="0.0.0.0", port=8000) \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-3ae882d5/environment/puzzle/upstream/simulator.py b/tasks/agentescape-25-skeleton-3ae882d5/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3ae882d5/environment/puzzle/upstream/simulator.py @@ -0,0 +1,2911 @@ +import hashlib +import hmac +import base64 +import binascii +import zlib +import json +import uuid +import math +import re +from typing import Dict, Any, List + +class ToolSimulator: + def __init__(self): + """工具模拟器 + + 文件处理工具(zip_unzip, zip_unzip_file, zip_unzip_item, json_get, csv_query, + regex_search, graph_shortest_path)不需要真实文件系统。 + 这些工具只验证输入参数,然后返回预先初始化好的 golden_outputs。 + """ + self.tool_map = { + # 数论 + "calc_bigmul": self.calc_bigmul, + "calc_modexp": self.calc_modexp, + "calc_modexp_int": self.calc_modexp_int, + "calc_gcd": self.calc_gcd, + "calc_gcd_int": self.calc_gcd_int, + "calc_inv_mod": self.calc_inv_mod, + "calc_inv_mod_int": self.calc_inv_mod_int, + + # 哈希 + "hash_sha256": self.hash_sha256, + "hash_md5": self.hash_md5, + "hmac_sha256": self.hmac_sha256, + + # 编码 + "base64_decode": self.base64_decode, + "base64_encode": self.base64_encode, + "hex_decode": self.hex_decode, + "hex_encode": self.hex_encode, + "zlib_inflate": self.zlib_inflate, + "zlib_deflate": self.zlib_deflate, + + # 文件 + "zip_unzip": self.zip_unzip, + "zip_unzip_file": self.zip_unzip_file, + "zip_unzip_item": self.zip_unzip_item, + "regex_search": self.regex_search, + "json_get": self.json_get, + "csv_query": self.csv_query, + "code_py_exec": self.code_py_exec, + + # 图 + "graph_shortest_path": self.graph_shortest_path, + + # 加解密 (简化模拟) + "crypto_aes_cbc_decrypt": self.crypto_aes_cbc_decrypt, + "crypto_rsa_decrypt_hex": self.crypto_rsa_decrypt_hex, + + # 其他 + "num_base_convert": self.num_base_convert, + "time_convert": self.time_convert, + "checksum_crc32": self.checksum_crc32, + "geo_haversine": self.geo_haversine, + "otp_totp_generate": self.otp_totp_generate, + "unicode_norm": self.unicode_norm, + "text_bidi_sanitize": self.text_bidi_sanitize, + "text_xor_hex": self.text_xor_hex, + "text_rotN": self.text_rotN, + "luhn_check": self.luhn_check, + "iban_validate": self.iban_validate, + + # 物理 + "matter_synthesizer": self.matter_synthesizer, + + # 终端机 + "terminal_1": self.terminal_1, + "terminal_2": self.terminal_2, + "Logic Terminal": self.logic_terminal, + "Math Terminal": self.math_terminal, + "Encryption Terminal": self.crypt_terminal, + "Sequence Terminal": self.sequence_terminal + } + + def execute(self, tool_name: str, inputs: Dict[str, Any]) -> Dict[str, Any]: + if tool_name not in self.tool_map: + # Fallback for unknown tools: return dummy outputs based on expected output types + # This should ideally not happen if all tools are implemented + return {} + + try: + return self.tool_map[tool_name](inputs) + except Exception as e: + print(f"Error executing {tool_name}: {e}") + # Return empty or error indication? For generation, we might want to fail hard or return dummy. + # For now, return dummy to keep flow going, but log error. + return {} + + # --- Implementations --- + + def calc_bigmul(self, inputs): + # Check if required parameters are present + if "a" not in inputs or "b" not in inputs: + raise ValueError("Missing required parameters 'a' and/or 'b'") + + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + return {"product": str(a * b)} + except (ValueError, TypeError) as e: + raise ValueError(f"Failed to convert parameters to integers: {str(e)}") + + def calc_modexp(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + try: + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if isinstance(base, str): + base = int(base) + elif not isinstance(base, int): + raise ValueError("Parameter 'base' must be a string or integer") + + if isinstance(exp, str): + exp = int(exp) + elif not isinstance(exp, int): + raise ValueError("Parameter 'exp' must be a string or integer") + + if isinstance(mod, str): + mod = int(mod) + elif not isinstance(mod, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": str(pow(base, exp, mod))} + + def calc_modexp_int(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["base"], int): + raise ValueError("Parameter 'base' must be an integer") + if not isinstance(inputs["exp"], int): + raise ValueError("Parameter 'exp' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": pow(base, exp, mod)} + + def calc_gcd(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + # 计算 GCD 并返回字符串格式(符合 Big_Int 输出类型) + result = math.gcd(a, b) + return {"gcd": str(result)} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def calc_gcd_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["b"], int): + raise ValueError("Parameter 'b' must be an integer") + + # 获取参数 + a = inputs["a"] + b = inputs["b"] + + return {"gcd": math.gcd(a, b)} + + def calc_inv_mod(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + m = inputs["mod"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(m, str): + m = int(m) + elif not isinstance(m, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": str(pow(a, -1, m))} + except ValueError as e: + # 模逆不存在时,返回一个特殊值(用于数据传递) + # 在 DAG 生成阶段,这允许数据流继续 + return {"inv": str(a)} + + def calc_inv_mod_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + a = inputs["a"] + m = inputs["mod"] + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": pow(a, -1, m)} + except ValueError as e: + raise ValueError(f"Modular inverse does not exist: {str(e)}") + + def hash_sha256(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.sha256(text.encode()).hexdigest()} + + def hash_md5(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.md5(text.encode()).hexdigest()} + + def hmac_sha256(self, inputs): + # 参数检查 + if "hex_key" not in inputs: + raise ValueError("Missing required parameter: hex_key") + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["hex_key"], str): + raise ValueError("Parameter 'hex_key' must be a string") + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + try: + key = bytes.fromhex(inputs["hex_key"]) + text = inputs["text"].encode() + return {"hex": hmac.new(key, text, hashlib.sha256).hexdigest()} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def base64_decode(self, inputs): + # 参数检查 + if "data" not in inputs: + raise ValueError("Missing required parameter: data") + + # 类型检查 + if not isinstance(inputs["data"], str): + raise ValueError("Parameter 'data' must be a string") + + data = inputs["data"] + try: + return {"bytes_hex": binascii.hexlify(base64.b64decode(data)).decode()} + except Exception as e: + raise ValueError(f"Base64 decode error: {str(e)}") + + def base64_encode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"b64": base64.b64encode(bytes.fromhex(hex_data)).decode()} + except Exception as e: + raise ValueError(f"Base64 encode error: {str(e)}") + + def hex_decode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"text": bytes.fromhex(hex_data).decode('utf-8', errors='ignore')} + except Exception as e: + raise ValueError(f"Hex decode error: {str(e)}") + + def hex_encode(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + try: + return {"hex": text.encode().hex()} + except Exception as e: + raise ValueError(f"Hex encode error: {str(e)}") + + + # 到此处实现已经更新 + + def zlib_inflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("Parameter 'hex' must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("Missing required parameter: hex") + + try: + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空字符串 + if not hex_data: + raise ValueError("Empty hex string provided") + + # 检查十六进制字符串的有效性 + if len(hex_data) % 2 != 0: + raise ValueError("Hex string must have even length") + + # 检查是否只包含有效的十六进制字符 + if not all(c in '0123456789abcdefABCDEF' for c in hex_data): + raise ValueError("Invalid hex string provided") + + # 尝试解压缩 + return {"text": zlib.decompress(bytes.fromhex(hex_data)).decode('utf-8')} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hex string provided") from e + raise ValueError(f"Invalid zlib data: {e}") from e + except Exception as e: + raise RuntimeError(f"Failed to inflate data: {e}") from e + + def zlib_deflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("Parameter 'text' must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("Missing required parameter: text") + + try: + # 压缩文本 + return {"hex": zlib.compress(text.encode('utf-8')).hex()} + except Exception as e: + raise RuntimeError(f"Failed to deflate data: {e}") from e + + # --- File Operations --- + + def zip_unzip(self, inputs): + """ZIP 解压工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"files": golden_outputs.get("files", "")} + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return {"files": golden_outputs.get("files", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "files" in golden_outputs: + # 验证必需参数 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 检查类型 + if has_zip_id and not isinstance(zip_id, str): + return {"error": "Parameter 'zip_id' must be a string type"} + if has_password and not isinstance(password, str): + return {"error": "Parameter 'password' must be a string type"} + + # 验证输入是否与预期匹配 + if golden_inputs: + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return {"files": golden_outputs["files"]} + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + # 没有golden_inputs但有golden_outputs,直接返回输出 + return {"files": golden_outputs["files"]} + + # 如果没有预期输出,返回空结果 + return {"files": ""} + + def regex_search(self, inputs): + """正则搜索工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"matches": golden_outputs.get("matches", "[]")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "matches" in golden_outputs: + # 提取实际参数 + pattern = inputs.get("pattern") + file_id = inputs.get("file_id") + text = inputs.get("text") + + # 1. 检查必需参数 + if pattern is None: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["pattern"], + "message": "Missing required parameter 'pattern'" + } + } + + # 类型检查 + if not isinstance(pattern, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "pattern", + "message": "Parameter 'pattern' must be a string type" + } + } + if file_id is not None and not isinstance(file_id, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if text is not None and not isinstance(text, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "text", + "message": "Parameter 'text' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合 + provided_params = {} + if pattern is not None: + provided_params["pattern"] = pattern + if file_id is not None: + provided_params["file_id"] = file_id + if text is not None: + provided_params["text"] = text + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数(关键改进) + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_pattern = golden_inputs.get("pattern") + expected_file_id = golden_inputs.get("file_id") + expected_text = golden_inputs.get("text") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_pattern is not None: + if str(pattern) != str(expected_pattern): + incorrect_params.append("pattern") + else: + correct_params.append("pattern") + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_text is not None: + if str(text) != str(expected_text): + incorrect_params.append("text") + else: + correct_params.append("text") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "matches": "[]", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "matches": golden_outputs["matches"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空列表 + return {"matches": "[]"} + + def json_get(self, inputs): + """JSON 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"values": golden_outputs.get("values", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "values" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + jsonpath = inputs.get("jsonpath", "") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if jsonpath is not None and not isinstance(jsonpath, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "jsonpath", + "message": "Parameter 'jsonpath' must be a string type" + } + } + + # 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:jsonpath有默认值"") + provided_params = {} + if file_id is not None: + provided_params["file_id"] = file_id + if jsonpath != "": + provided_params["jsonpath"] = jsonpath + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_jsonpath = golden_inputs.get("jsonpath") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_jsonpath is not None: + if str(jsonpath) != str(expected_jsonpath): + incorrect_params.append("jsonpath") + else: + correct_params.append("jsonpath") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "values": "", + "_validation": validation_info + } + + # 所有验证通过,返回正确输出 + return { + "values": golden_outputs["values"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"values": ""} + + def csv_query(self, inputs): + """CSV 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"rows": golden_outputs.get("rows", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "rows" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + select_columns = inputs.get("select", "") + where_clause = inputs.get("where", "") + + # 1. 检查必需参数 + if file_id is None: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["file_id"], + "message": "Missing required parameter 'file_id'" + } + } + + # 类型检查 + if not isinstance(file_id, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if not isinstance(select_columns, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "select", + "message": "Parameter 'select' must be a string type" + } + } + if not isinstance(where_clause, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "where", + "message": "Parameter 'where' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:select和where有默认值"") + provided_params = {"file_id": file_id} + if select_columns != "": + provided_params["select"] = select_columns + if where_clause != "": + provided_params["where"] = where_clause + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_select = golden_inputs.get("select") + expected_where = golden_inputs.get("where") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_select is not None: + if str(select_columns) != str(expected_select): + incorrect_params.append("select") + else: + correct_params.append("select") + + if expected_where is not None: + if str(where_clause) != str(expected_where): + incorrect_params.append("where") + else: + correct_params.append("where") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "rows": "", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "rows": golden_outputs["rows"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"rows": ""} + + def graph_shortest_path(self, inputs): + """图最短路径工具 + + 如果有 _golden_outputs 或 _init_outputs,验证输入并返回预设输出。 + 否则执行真实的 Dijkstra 算法。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 检查是否在预设模式中(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + if golden_outputs and "path" in golden_outputs: + # 评测阶段但没有 golden_inputs,直接返回 outputs + if not golden_inputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 评测模式:验证输入参数是否匹配 golden 值 + src = inputs.get("src") + dst = inputs.get("dst") + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + + has_src = src is not None and src != "" + has_dst = dst is not None and dst != "" + + # 验证必需参数 + if not has_src or not has_dst: + missing = [] + if not has_src: + missing.append("src") + if not has_dst: + missing.append("dst") + return {"error": "Missing required parameters: " + ", ".join(missing)} + + # 类型检查 + if not isinstance(src, str): + return {"error": "Parameter 'src' must be a string"} + if not isinstance(dst, str): + return {"error": "Parameter 'dst' must be a string"} + + # 验证输入是否匹配期望值 + if golden_inputs: + expected_src = golden_inputs.get("src") + expected_dst = golden_inputs.get("dst") + expected_file_id = golden_inputs.get("file_id") + expected_graph_data = golden_inputs.get("graph_data") + + # 收集验证结果 + incorrect_params = [] + correct_params = [] + + # 检查必需参数是否匹配 + if expected_src is not None: + if str(src) != str(expected_src): + incorrect_params.append("src") + else: + correct_params.append("src") + + if expected_dst is not None: + if str(dst) != str(expected_dst): + incorrect_params.append("dst") + else: + correct_params.append("dst") + + # 检查可选参数(如果在 expected_inputs 中定义了) + if expected_file_id is not None: + if file_id != expected_file_id: + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_graph_data is not None: + if graph_data != expected_graph_data: + incorrect_params.append("graph_data") + else: + correct_params.append("graph_data") + + # 如果有参数不正确,返回详细的反馈 + if incorrect_params: + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 验证通过,返回预设的输出 + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 获取参数(真实执行路径) + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + # Support both src/dst (interface definition) and start/end (original implementation) + start = inputs.get("src") + end = inputs.get("dst") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + raise TypeError("file_id must be a string") + + if graph_data is not None and not isinstance(graph_data, str): + raise TypeError("graph_data must be a string") + + if start is not None and not isinstance(start, str): + raise TypeError("src/start must be a string") + + if end is not None and not isinstance(end, str): + raise TypeError("dst/end must be a string") + + # 检查必需参数 + if file_id is None and graph_data is None: + raise ValueError("Either file_id or graph_data must be provided") + + if start is None: + raise ValueError("src/start parameter is required") + + if end is None: + raise ValueError("dst/end parameter is required") + + # Get graph content + content = None + if file_id is not None: + # 尝试从 VFS 获取(如果存在) + if hasattr(self, 'vfs') and file_id in self.vfs: + content = self.vfs[file_id] + else: + # VFS 不存在或文件不在 VFS 中 + # 返回一个默认的空图结果,或者抛出错误提示需要 init_outputs + raise ValueError( + f"File '{file_id}' not found. For tools that require files, " + f"please provide init_outputs in the initial_values." + ) + elif graph_data is not None: + content = graph_data + + if content is None: + content = "{}" + + try: + # Parse graph data + graph = json.loads(content) + + # 类型检查 + if not isinstance(graph, dict): + raise TypeError("Graph data must be a dictionary") + + # If graph is not in the expected format, try to extract adjacency list + if "nodes" in graph and "edges" in graph: + # 验证nodes和edges的类型 + if not isinstance(graph["nodes"], list): + raise TypeError("Nodes must be a list") + + if not isinstance(graph["edges"], list): + raise TypeError("Edges must be a list") + + # Convert from nodes/edges format to adjacency list + adjacency_list = {} + for node in graph["nodes"]: + # 验证node类型 + if not isinstance(node, dict): + raise TypeError("Each node must be a dictionary") + + # Use node ID as key, not the entire node dictionary + node_id = node.get("id", "") + if node_id: + adjacency_list[node_id] = {} + + for edge in graph["edges"]: + # 验证edge类型 + if not isinstance(edge, dict): + raise TypeError("Each edge must be a dictionary") + + u = edge["from"] + v = edge["to"] + weight = edge.get("weight", 1) # Default to unweighted + + # 类型检查 + if not isinstance(u, str): + raise TypeError("Edge 'from' must be a string") + + if not isinstance(v, str): + raise TypeError("Edge 'to' must be a string") + + if not isinstance(weight, (int, float)): + raise TypeError("Edge weight must be a number") + + if u not in adjacency_list: + adjacency_list[u] = {} + if v not in adjacency_list: + adjacency_list[v] = {} + + adjacency_list[u][v] = weight + # If undirected, add reverse edge + if not edge.get("directed", False): + adjacency_list[v][u] = weight + elif isinstance(graph, dict): + # Already in adjacency list format + adjacency_list = graph + + # 验证邻接表结构 + for node, neighbors in adjacency_list.items(): + if not isinstance(neighbors, dict): + raise TypeError("Adjacency list must be a dictionary of dictionaries") + + for neighbor, weight in neighbors.items(): + if not isinstance(weight, (int, float)): + raise TypeError("Edge weights must be numbers") + else: + raise TypeError("Graph data must be a dictionary") + + # 检查起点和终点是否为空 + if not start: + raise ValueError("Start node cannot be empty") + + if not end: + raise ValueError("End node cannot be empty") + + # 检查起点和终点是否在图中 + if start not in adjacency_list: + raise ValueError(f"Start node '{start}' not found in graph") + + if end not in adjacency_list: + raise ValueError(f"End node '{end}' not found in graph") + + # Dijkstra's algorithm implementation + import heapq + + # Initialize distances and previous nodes + distances = {node: float('infinity') for node in adjacency_list} + previous = {node: None for node in adjacency_list} + distances[start] = 0 + + # Priority queue + pq = [(0, start)] + heapq.heapify(pq) + + while pq: + current_dist, current_node = heapq.heappop(pq) + + # If we've reached the end node, we can break early + if current_node == end: + break + + # Nodes can be added multiple times to the priority queue, but we only process them once + if current_dist > distances[current_node]: + continue + + # Explore neighbors + for neighbor, weight in adjacency_list[current_node].items(): + distance = current_dist + weight + + # If a shorter path is found + if distance < distances[neighbor]: + distances[neighbor] = distance + previous[neighbor] = current_node + heapq.heappush(pq, (distance, neighbor)) + + # Reconstruct the shortest path + path = [] + current = end + while current is not None: + path.append(current) + current = previous[current] + path.reverse() # Reverse to get from start to end + + # Check if path exists + if not path or path[0] != start: + return {"path": "[]", "cost": 0} + + return { + "path": json.dumps(path), + "cost": distances[end] + } + except json.JSONDecodeError as e: + raise ValueError(f"Invalid JSON in graph data: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in graph_shortest_path: {str(e)}") + + # --- Crypto (Simplified) --- + def crypto_aes_cbc_decrypt(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 (使用模板中定义的参数名) + hex_cipher = inputs.get("hex_cipher") + hex_key = inputs.get("hex_key") + hex_iv = inputs.get("hex_iv") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + + if hex_key is not None and not isinstance(hex_key, str): + raise TypeError("hex_key must be a string") + + if hex_iv is not None and not isinstance(hex_iv, str): + raise TypeError("hex_iv must be a string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + + if hex_key is None: + raise ValueError("hex_key parameter is required") + + if hex_iv is None: + raise ValueError("hex_iv parameter is required") + + from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes + from cryptography.hazmat.backends import default_backend + from cryptography.hazmat.primitives import padding + + try: + # Convert hex strings to bytes + ciphertext = bytes.fromhex(hex_cipher) + key = bytes.fromhex(hex_key) + iv = bytes.fromhex(hex_iv) + + # Validate key length (AES-128, AES-192, AES-256) + if len(key) not in [16, 24, 32]: + raise ValueError("Invalid key length. Must be 16, 24, or 32 bytes.") + + if len(iv) != 16: + raise ValueError("Invalid IV length. Must be 16 bytes.") + + # Create cipher object + cipher = Cipher( + algorithms.AES(key), + modes.CBC(iv), + backend=default_backend() + ) + + decryptor = cipher.decryptor() + + # Decrypt the ciphertext + padded_plaintext = decryptor.update(ciphertext) + decryptor.finalize() + + # Remove PKCS7 padding + unpadder = padding.PKCS7(128).unpadder() + plaintext = unpadder.update(padded_plaintext) + unpadder.finalize() + + # Return decrypted text + return {"text": plaintext.decode('utf-8', errors='ignore')} + except ValueError as e: + if "non-hexadecimal number found in fromhex()" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher, hex_key, or hex_iv") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in crypto_aes_cbc_decrypt: {str(e)}") + + def crypto_rsa_decrypt_hex(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_cipher = inputs.get("hex_cipher") + n = inputs.get("n") + d = inputs.get("d") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + if n is not None and not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + if d is not None and not isinstance(d, (int, str)): + raise TypeError("d must be an integer or string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + if n is None: + raise ValueError("n parameter is required") + if d is None: + raise ValueError("d parameter is required") + + try: + # Convert parameters to appropriate types + cipher_int = int(hex_cipher, 16) + n_int = int(n) if isinstance(n, str) else n + d_int = int(d) if isinstance(d, str) else d + + # RSA decryption: plaintext = ciphertext^d mod n + plaintext_int = pow(cipher_int, d_int, n_int) + + # Convert result to hex and then to text + plaintext_hex = hex(plaintext_int)[2:] + + # Pad with leading zero if odd length + if len(plaintext_hex) % 2 != 0: + plaintext_hex = '0' + plaintext_hex + + # Convert hex to bytes and then to text + try: + plaintext_bytes = bytes.fromhex(plaintext_hex) + plaintext_text = plaintext_bytes.decode('utf-8', errors='ignore') + except: + # If decoding fails, return hex representation + plaintext_text = plaintext_hex + + return {"text": plaintext_text} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in crypto_rsa_decrypt_hex: {str(e)}") + + # --- Others --- + def num_base_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + s = inputs.get("s") + from_base = inputs.get("from_base") + to_base = inputs.get("to_base") + + # 类型检查 - 接受 str 或 int + if s is not None and not isinstance(s, (str, int)): + raise TypeError("s must be a string or integer") + + if from_base is not None and not isinstance(from_base, (int, str)): + raise TypeError("from_base must be an integer") + + if to_base is not None and not isinstance(to_base, (int, str)): + raise TypeError("to_base must be an integer") + + # 检查必需参数 + if s is None: + raise ValueError("s parameter is required") + + if from_base is None: + raise ValueError("from_base parameter is required") + + if to_base is None: + raise ValueError("to_base parameter is required") + + try: + # Convert to int if needed + from_base = int(from_base) if isinstance(from_base, str) else from_base + to_base = int(to_base) if isinstance(to_base, str) else to_base + s_str = str(s) + + # 验证基数范围 + if from_base < 2 or from_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + if to_base < 2 or to_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + # Convert from source base to decimal + val = int(s_str, from_base) + + # Convert from decimal to target base + if to_base == 10: + result = str(val) + elif to_base == 16: + result = hex(val)[2:] + elif to_base == 8: + result = oct(val)[2:] + elif to_base == 2: + result = bin(val)[2:] + else: + # Generic base conversion for other bases + if val == 0: + result = "0" + else: + digits = "0123456789abcdefghijklmnopqrstuvwxyz" + result = "" + n = abs(val) + while n: + result = digits[n % to_base] + result + n //= to_base + if val < 0: + result = "-" + result + + return {"str": result} + except ValueError as e: + raise ValueError(f"Invalid number format: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in num_base_convert: {str(e)}") + + def time_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iso = inputs.get("iso") + timestamp = inputs.get("timestamp") + datetime_str = inputs.get("datetime") + from_tz = inputs.get("from_tz") + to_tz = inputs.get("to_tz") + format_str = inputs.get("format") + + # 类型检查 + if iso is not None and not isinstance(iso, str): + raise TypeError("iso must be a string") + + if timestamp is not None and not isinstance(timestamp, (str, int, float)): + raise TypeError("timestamp must be a string, integer, or float") + + if datetime_str is not None and not isinstance(datetime_str, str): + raise TypeError("datetime must be a string") + + if from_tz is not None and not isinstance(from_tz, str): + raise TypeError("from_tz must be a string") + + if to_tz is not None and not isinstance(to_tz, str): + raise TypeError("to_tz must be a string") + + if format_str is not None and not isinstance(format_str, str): + raise TypeError("format must be a string") + + # 设置默认值 + if from_tz is None: + from_tz = "UTC" + + if to_tz is None: + to_tz = "UTC" + + import datetime + import pytz + + # 验证时区参数 + try: + if from_tz: + pytz.timezone(from_tz) + if to_tz: + pytz.timezone(to_tz) + except Exception: + raise ValueError("Invalid timezone provided") + + try: + # Parse input time + dt = None + + if iso is not None: + # Parse ISO 8601 format + dt = datetime.datetime.fromisoformat(iso.replace('Z', '+00:00')) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=pytz.UTC) + elif timestamp is not None: + # Parse Unix timestamp + timestamp = float(timestamp) + dt = datetime.datetime.fromtimestamp(timestamp, pytz.UTC) + elif datetime_str is not None: + # Parse datetime string + # Try common formats + formats_to_try = [ + "%Y-%m-%d %H:%M:%S", + "%Y-%m-%d %H:%M:%S.%f", + "%Y-%m-%d", + "%m/%d/%Y %H:%M:%S", + "%m/%d/%Y" + ] + + parse_success = False + for fmt in formats_to_try: + try: + dt = datetime.datetime.strptime(datetime_str, fmt) + dt = pytz.timezone(from_tz).localize(dt) + parse_success = True + break + except ValueError: + continue + + if not parse_success: + raise ValueError("Unable to parse datetime string with common formats") + else: + # 如果没有提供任何时间参数,则使用当前时间 + dt = datetime.datetime.now(pytz.UTC) + except ValueError as e: + raise ValueError(f"Error parsing time input: {str(e)}") + except Exception as e: + raise RuntimeError(f"Unexpected error parsing time input: {str(e)}") + + try: + # Convert timezone + if from_tz != to_tz: + dt = dt.astimezone(pytz.timezone(to_tz)) + + # Format outputs + result = { + "iso": dt.isoformat(), + "timestamp": str(dt.timestamp()), + "datetime": dt.strftime("%Y-%m-%d %H:%M:%S"), + "date": dt.strftime("%Y-%m-%d"), + "time": dt.strftime("%H:%M:%S"), + "timezone": to_tz + } + + # Add custom format if requested + if format_str: + try: + result["formatted"] = dt.strftime(format_str) + except ValueError as e: + raise ValueError(f"Invalid format string: {str(e)}") + + return result + except Exception as e: + raise RuntimeError(f"Error in time_convert: {str(e)}") + + def checksum_crc32(self, inputs): + import zlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("hex must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("hex parameter is required") + + try: + # 验证十六进制字符串 + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空 + if not hex_data: + raise ValueError("hex data cannot be empty") + + # 检查是否为有效的十六进制字符串 + if not all(c in "0123456789abcdefABCDEF" for c in hex_data): + raise ValueError("hex must be a valid hexadecimal string") + + # 检查长度是否为偶数 + if len(hex_data) % 2 != 0: + raise ValueError("hex must have even number of characters") + + val = zlib.crc32(bytes.fromhex(hex_data)) + # 确保 hex 输出是 8 位,前导补 0 + return {"hex": f"{val:08x}", "int": val} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in checksum_crc32: {str(e)}") + + def geo_haversine(self, inputs): + import math + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + lat1 = inputs.get("lat1") + lon1 = inputs.get("lon1") + lat2 = inputs.get("lat2") + lon2 = inputs.get("lon2") + + # 类型检查 + if lat1 is not None and not isinstance(lat1, (int, float, str)): + raise TypeError("lat1 must be a number or string") + if lon1 is not None and not isinstance(lon1, (int, float, str)): + raise TypeError("lon1 must be a number or string") + if lat2 is not None and not isinstance(lat2, (int, float, str)): + raise TypeError("lat2 must be a number or string") + if lon2 is not None and not isinstance(lon2, (int, float, str)): + raise TypeError("lon2 must be a number or string") + + # 检查必需参数 + if lat1 is None: + raise ValueError("lat1 parameter is required") + if lon1 is None: + raise ValueError("lon1 parameter is required") + if lat2 is None: + raise ValueError("lat2 parameter is required") + if lon2 is None: + raise ValueError("lon2 parameter is required") + + try: + # 转换为浮点数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(lat1, str): + lat1 = float(lat1) + elif not isinstance(lat1, (int, float)): + raise TypeError("lat1 must be a number or string") + else: + lat1 = float(lat1) + + if isinstance(lon1, str): + lon1 = float(lon1) + elif not isinstance(lon1, (int, float)): + raise TypeError("lon1 must be a number or string") + else: + lon1 = float(lon1) + + if isinstance(lat2, str): + lat2 = float(lat2) + elif not isinstance(lat2, (int, float)): + raise TypeError("lat2 must be a number or string") + else: + lat2 = float(lat2) + + if isinstance(lon2, str): + lon2 = float(lon2) + elif not isinstance(lon2, (int, float)): + raise TypeError("lon2 must be a number or string") + else: + lon2 = float(lon2) + + # Validate coordinates (approximate range check) + if not (-90 <= lat1 <= 90): + raise ValueError("lat1 must be between -90 and 90") + if not (-90 <= lat2 <= 90): + raise ValueError("lat2 must be between -90 and 90") + if not (-180 <= lon1 <= 180): + raise ValueError("lon1 must be between -180 and 180") + if not (-180 <= lon2 <= 180): + raise ValueError("lon2 must be between -180 and 180") + + # Earth radius in meters + R = 6371000 # Approximate radius of Earth + + # Convert degrees to radians + lat1_rad = math.radians(lat1) + lon1_rad = math.radians(lon1) + lat2_rad = math.radians(lat2) + lon2_rad = math.radians(lon2) + + # Calculate differences + delta_lat = lat2_rad - lat1_rad + delta_lon = lon2_rad - lon1_rad + + # Haversine formula + a = math.sin(delta_lat / 2) ** 2 + \ + math.cos(lat1_rad) * math.cos(lat2_rad) * \ + math.sin(delta_lon / 2) ** 2 + c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) + distance_m = R * c + + # Return distance in meters + return {"meters": round(distance_m, 2)} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in geo_haversine: {str(e)}") + + def otp_totp_generate(self, inputs): + import hmac + import hashlib + import base64 + import time + import struct + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + base32_secret = inputs.get("base32_secret") + step = inputs.get("step", 30) # Default to 30 seconds + digits = inputs.get("digits", 6) # Default to 6 digits + timestamp_iso = inputs.get("timestamp_iso", "") + algo = inputs.get("algo", "sha1") # Default to sha1 as current implementation only supports this + + # 类型检查 + if base32_secret is not None and not isinstance(base32_secret, str): + raise TypeError("base32_secret must be a string") + if not isinstance(step, (int, str)): + raise TypeError("step must be an integer or string") + if not isinstance(digits, (int, str)): + raise TypeError("digits must be an integer or string") + if not isinstance(timestamp_iso, str): + raise TypeError("timestamp_iso must be a string") + if not isinstance(algo, str): + raise TypeError("algo must be a string") + + # 检查必需参数 + if base32_secret is None: + raise ValueError("base32_secret parameter is required") + + try: + # Convert step and digits to appropriate types + step = int(step) + digits = int(digits) + if digits < 6 or digits > 8: + raise ValueError("Digits must be between 6 and 8") + + # Convert timestamp_iso to integer timestamp + if timestamp_iso: + import datetime + dt = datetime.datetime.fromisoformat(timestamp_iso.replace('Z', '+00:00')) + timestamp = int(dt.timestamp()) + else: + timestamp = int(time.time()) + + # Calculate counter value (T = floor(timestamp / step)) + counter = timestamp // step + + # Decode the base32 secret + # Add padding if necessary (base64 requires padding to be multiple of 8) + base32_secret = base32_secret.upper().replace(' ', '') + if len(base32_secret) % 8 != 0: + base32_secret += '=' * (8 - (len(base32_secret) % 8)) + key = base64.b32decode(base32_secret, casefold=True) + + # Calculate HMAC-SHA1 + counter_bytes = struct.pack('>Q', counter) # Big-endian 8-byte integer + hmac_hash = hmac.new(key, counter_bytes, hashlib.sha1).digest() + + # Dynamic truncation + offset = hmac_hash[-1] & 0xF + code = struct.unpack('>I', hmac_hash[offset:offset+4])[0] & 0x7FFFFFFF + + # Generate the OTP + otp = str(code % (10 ** digits)).zfill(digits) + + # Calculate remaining time until next OTP change + remaining_time = step - (timestamp % step) + + return {"totp": otp, "remaining_time": remaining_time, "time_step": step} + except ValueError as e: + if "invalid literal for int()" in str(e): + raise ValueError("step and digits must be valid integers") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in otp_totp_generate: {str(e)}") + + def unicode_norm(self, inputs): + import unicodedata + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + form = inputs.get("form", "NFC") # Default to NFC + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if form is not None and not isinstance(form, str): + raise TypeError("form must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Normalize form (NFC, NFD, NFKC, NFKD) + form = form.upper().strip() + + if form not in ['NFC', 'NFD', 'NFKC', 'NFKD']: + raise ValueError(f"Invalid normalization form: {form}. Must be one of: NFC, NFD, NFKC, NFKD") + + # Apply Unicode normalization + normalized_text = unicodedata.normalize(form, text) + + return {"text": normalized_text} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in unicode_norm: {str(e)}") + + def text_bidi_sanitize(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Bidi control characters to remove + bidi_controls = [ + '\u200E', # LEFT-TO-RIGHT MARK + '\u200F', # RIGHT-TO-LEFT MARK + '\u202A', # LEFT-TO-RIGHT EMBEDDING + '\u202B', # RIGHT-TO-LEFT EMBEDDING + '\u202C', # POP DIRECTIONAL FORMATTING + '\u202D', # LEFT-TO-RIGHT OVERRIDE + '\u202E', # RIGHT-TO-LEFT OVERRIDE + '\u2066', # LEFT-TO-RIGHT ISOLATE + '\u2067', # RIGHT-TO-LEFT ISOLATE + '\u2068', # FIRST STRONG ISOLATE + '\u2069', # POP DIRECTIONAL ISOLATE + ] + + # Remove all Bidi control characters + sanitized_text = text + for control_char in bidi_controls: + sanitized_text = sanitized_text.replace(control_char, '') + + return {"text": sanitized_text} + except Exception as e: + raise RuntimeError(f"Error in text_bidi_sanitize: {str(e)}") + + def text_xor_hex(self, inputs): + import binascii + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_a = inputs.get("hex_a") + hex_b = inputs.get("hex_b") + + # 类型检查 + if hex_a is not None and not isinstance(hex_a, str): + raise TypeError("hex_a must be a string") + if hex_b is not None and not isinstance(hex_b, str): + raise TypeError("hex_b must be a string") + + # 检查必需参数 + if hex_a is None: + raise ValueError("hex_a parameter is required") + if hex_b is None: + raise ValueError("hex_b parameter is required") + + try: + # Remove any whitespace + hex_a = hex_a.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + hex_b = hex_b.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + + # Validate hex strings + if not (all(c in "0123456789abcdefABCDEF" for c in hex_a) and len(hex_a) % 2 == 0): + raise ValueError("hex_a must be a valid hexadecimal string with even length") + if not (all(c in "0123456789abcdefABCDEF" for c in hex_b) and len(hex_b) % 2 == 0): + raise ValueError("hex_b must be a valid hexadecimal string with even length") + + # Convert hex strings to bytes + bytes_a = binascii.unhexlify(hex_a) + bytes_b = binascii.unhexlify(hex_b) + + # Make the byte arrays the same length by padding the shorter one with zeros + max_len = max(len(bytes_a), len(bytes_b)) + bytes_a = bytes_a.ljust(max_len, b'\x00') + bytes_b = bytes_b.ljust(max_len, b'\x00') + + # Perform XOR operation + result_bytes = bytes(a ^ b for a, b in zip(bytes_a, bytes_b)) + + # Convert result back to hex + result_hex = binascii.hexlify(result_bytes).decode('utf-8') + + return {"hex": result_hex} + except ValueError as e: + if "Non-hexadecimal digit found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in text_xor_hex: {str(e)}") + + def text_rotN(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + n = inputs.get("n", 0) + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + n = int(n) + except ValueError: + raise ValueError("n must be a valid integer") + + result = [] + for char in text: + if char.isupper(): + # Rotate uppercase letters + result_char = chr((ord(char) - ord('A') + n) % 26 + ord('A')) + result.append(result_char) + elif char.islower(): + # Rotate lowercase letters + result_char = chr((ord(char) - ord('a') + n) % 26 + ord('a')) + result.append(result_char) + else: + # Keep non-alphabetic characters unchanged + result.append(char) + + return {"text": ''.join(result)} + + def luhn_check(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数(支持 card_number 和 number 两个参数名) + card_number = inputs.get("number") or inputs.get("card_number") + + # 类型检查 + if card_number is not None and not isinstance(card_number, str): + raise TypeError("number must be a string") + + # 检查必需参数 + if card_number is None: + raise ValueError("number parameter is required") + + try: + # 如果输入是JSON数组或其他非数字字符串,返回该字符串本身(用于数据传递) + # 这种情况发生在DAG设计中类型不匹配时 + if card_number.startswith('[') or card_number.startswith('{'): + # 输入是JSON,直接返回原值(用于传递) + return {"valid": card_number} + + # Remove whitespace from card number + card_number = card_number.replace(" ", "").replace("-", "") + + # Check if card number is all digits + if not card_number.isdigit() or len(card_number) < 13: + return {"valid": "false"} + + # Implement Luhn algorithm + total = 0 + reverse_digits = card_number[::-1] # Reverse the number for easier processing + + for i, digit in enumerate(reverse_digits): + num = int(digit) + if i % 2 == 1: # Every second digit starting from the right (which is first in reversed string) + num *= 2 + if num > 9: + num -= 9 # Equivalent to sum of digits for 2-digit numbers + total += num + + # Check if total is divisible by 10 + is_valid = total % 10 == 0 + return {"valid": "true" if is_valid else "false"} + except Exception as e: + raise RuntimeError(f"Error in luhn_check: {str(e)}") + + def iban_validate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iban = inputs.get("iban") + + # 类型检查 + if iban is not None and not isinstance(iban, str): + raise TypeError("iban must be a string") + + # 检查必需参数 + if iban is None: + raise ValueError("iban parameter is required") + + try: + # Remove whitespace from IBAN + iban = iban.replace(" ", "") + + # Basic length and format check + if not (len(iban) >= 15 and len(iban) <= 34): + return {"valid": "False"} + + if not (iban[:2].isalpha() and iban[2:].isdigit()): + return {"valid": "False"} + + # Move first four characters to the end + rearranged = iban[4:] + iban[:4] + + # Replace letters with numbers (A=10, B=11, ..., Z=35) + numeric_iban = '' + for char in rearranged: + if char.isdigit(): + numeric_iban += char + else: + numeric_iban += str(ord(char.upper()) - ord('A') + 10) + + # Perform modulo 97 check + # Use step-by-step approach for very large numbers + remainder = 0 + for char in numeric_iban: + remainder = (remainder * 10 + int(char)) % 97 + + is_valid = remainder == 1 + return {"valid": "True" if is_valid else "False"} + except Exception as e: + raise RuntimeError(f"Error in iban_validate: {str(e)}") + + def matter_synthesizer(self, inputs): + import hashlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + blueprint = inputs.get("blueprint") + + # 类型检查 + if blueprint is not None and not isinstance(blueprint, str): + raise TypeError("blueprint must be a string") + + try: + # Get blueprint parameter as defined in interface + if blueprint is None: + blueprint = "" + + # Generate a unique item ID based on the blueprint + # This ensures the same blueprint always produces the same item + blueprint_hash = hashlib.sha256(blueprint.encode()).hexdigest()[:16] + + # Create a synthesized item with a deterministic ID based on blueprint + synthesized_item = f"synthesized_item_{blueprint_hash}" + + return {"output_slot": synthesized_item} + except Exception as e: + raise RuntimeError(f"Error in matter_synthesizer: {str(e)}") + + # --- Terminal Implementations --- + def terminal_1(self, inputs): + """ + terminal_1: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 只返回 text_output + - 只输入正确的 slot_b → 只返回 hex_output + - 同时输入正确的 slot_a 和 slot_b → 返回 item_dispenser(物品掉落) + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + # 检查哪些输入被提供了 + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值是否正确(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + expected_a = golden_inputs["slot_a"] + a_valid = str(slot_a) == str(expected_a) + + if has_b and "slot_b" in golden_inputs: + expected_b = golden_inputs["slot_b"] + b_valid = str(slot_b) == str(expected_b) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 item_dispenser + if has_a and has_b: + if a_valid and b_valid: + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 text_output + if has_a and not has_b: + if a_valid: + if "text_output" in golden_outputs: + result["text_output"] = golden_outputs["text_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 hex_output + if has_b and not has_a: + if b_valid: + if "hex_output" in golden_outputs: + result["hex_output"] = golden_outputs["hex_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def terminal_2(self, inputs): + """ + terminal_2: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 text_result + - 同时输入正确的 num1 和 num2 → 返回 hex_result 和 math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + # 检查哪些输入被提供了 + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值是否正确(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + expected_num1 = golden_inputs["num1"] + num1_valid = str(num1) == str(expected_num1) + + if has_num2 and "num2" in golden_inputs: + expected_num2 = golden_inputs["num2"] + num2_valid = str(num2) == str(expected_num2) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 hex_result 和 math_token + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 text_result + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "text_result" in golden_outputs: + result["text_result"] = golden_outputs["text_result"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def logic_terminal(self, inputs): + """ + Logic Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 返回 screen(部分输出) + - 只输入正确的 slot_b → 返回 screen 和 secondary_output + - 同时输入正确的 slot_a 和 slot_b → 返回 screen, secondary_output, item_dispenser + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + a_valid = str(slot_a) == str(golden_inputs["slot_a"]) + + if has_b and "slot_b" in golden_inputs: + b_valid = str(slot_b) == str(golden_inputs["slot_b"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出(包括 item_dispenser) + if has_a and has_b: + if a_valid and b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 screen(部分输出) + if has_a and not has_b: + if a_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 screen 和 secondary_output + if has_b and not has_a: + if b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def math_terminal(self, inputs): + """ + Math Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 result_display + - 同时输入正确的 num1 和 num2 → 返回 result_display, hex_result, math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + num1_valid = str(num1) == str(golden_inputs["num1"]) + + if has_num2 and "num2" in golden_inputs: + num2_valid = str(num2) == str(golden_inputs["num2"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 result_display + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def crypt_terminal(self, inputs): + """ + Encryption Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 plaintext → 返回 status(部分输出) + - 同时输入正确的 plaintext 和 key → 返回 status, encrypted_hex, encryption_chip + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + plaintext = inputs.get("plaintext") + key = inputs.get("key") + + has_plaintext = plaintext is not None and plaintext != "" + has_key = key is not None and key != "" + + # 验证输入值(与 golden values 比较) + plaintext_valid = False + key_valid = False + + if has_plaintext and "plaintext" in golden_inputs: + plaintext_valid = str(plaintext) == str(golden_inputs["plaintext"]) + + if has_key and "key" in golden_inputs: + key_valid = str(key) == str(golden_inputs["key"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_plaintext and has_key: + if plaintext_valid and key_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + if "encrypted_hex" in golden_outputs: + result["encrypted_hex"] = golden_outputs["encrypted_hex"] + if "encryption_chip" in golden_outputs: + result["encryption_chip"] = golden_outputs["encryption_chip"] + return result + else: + incorrect_params = [] + correct_params = [] + if not plaintext_valid: + incorrect_params.append("plaintext") + else: + correct_params.append("plaintext") + if not key_valid: + incorrect_params.append("key") + else: + correct_params.append("key") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 plaintext 且正确 → 返回 status(部分输出) + if has_plaintext and not has_key: + if plaintext_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: plaintext"} + + # 只提供 key 但没有 plaintext + if has_key and not has_plaintext: + return {"error": "plaintext required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + def sequence_terminal(self, inputs): + """ + Sequence Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 sequence → 返回 verification(部分输出) + - 同时输入正确的 sequence 和 checksum → 返回 verification, auth_code, access_card + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + sequence = inputs.get("sequence") + checksum = inputs.get("checksum") + + has_sequence = sequence is not None and sequence != "" + has_checksum = checksum is not None and checksum != "" + + # 验证输入值(与 golden values 比较) + sequence_valid = False + checksum_valid = False + + if has_sequence and "sequence" in golden_inputs: + sequence_valid = str(sequence) == str(golden_inputs["sequence"]) + + if has_checksum and "checksum" in golden_inputs: + checksum_valid = str(checksum) == str(golden_inputs["checksum"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_sequence and has_checksum: + if sequence_valid and checksum_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + if "auth_code" in golden_outputs: + result["auth_code"] = golden_outputs["auth_code"] + if "access_card" in golden_outputs: + result["access_card"] = golden_outputs["access_card"] + return result + else: + incorrect_params = [] + correct_params = [] + if not sequence_valid: + incorrect_params.append("sequence") + else: + correct_params.append("sequence") + if not checksum_valid: + incorrect_params.append("checksum") + else: + correct_params.append("checksum") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 sequence 且正确 → 返回 verification(部分输出) + if has_sequence and not has_checksum: + if sequence_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: sequence"} + + # 只提供 checksum 但没有 sequence + if has_checksum and not has_sequence: + return {"error": "sequence required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + # --- Additional File Tools --- + + def zip_unzip_file(self, inputs): + """ZIP 解压文件工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def zip_unzip_item(self, inputs): + """ZIP 解压道具工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def code_py_exec(self, inputs): + """Python 代码执行工具 + + 这是一个真实执行的工具,在 DAG 生成阶段和运行时评测阶段都会执行代码。 + 输入: code (Python 代码字符串) + 输出: stdout (标准输出,包含执行结果和错误信息) + + 特殊行为: + - 如果代码定义了 main() 函数,会自动调用它 + - 如果执行出错,错误信息会包含在 stdout 中 + """ + code = inputs.get("code", "") + + if not code: + return {"stdout": "Error: No code provided"} + + try: + # 创建一个受限的执行环境 + import io + import sys + + # 捕获标准输出和标准错误 + old_stdout = sys.stdout + old_stderr = sys.stderr + sys.stdout = io.StringIO() + sys.stderr = io.StringIO() + + # 执行代码 + exec_globals = {"__builtins__": __builtins__} + exec_locals = {} + exec(code, exec_globals, exec_locals) + + # 如果定义了 main() 函数,自动调用它 + if 'main' in exec_locals and callable(exec_locals['main']): + exec_locals['main']() + + # 获取输出 + stdout_value = sys.stdout.getvalue() + stderr_value = sys.stderr.getvalue() + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 合并 stdout 和 stderr + output = stdout_value + if stderr_value: + output += ("\n" if output else "") + f"[stderr] {stderr_value}" + + # 如果没有任何输出,尝试返回 result 变量的值 + if not output: + result = exec_locals.get("_result") or exec_locals.get("result") + if result is not None: + output = str(result) + + return {"stdout": output if output else "(no output)"} + + except Exception as e: + # 恢复标准输出和错误输出 + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 返回错误信息 + return {"stdout": f"Error: {type(e).__name__}: {str(e)}"} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-3ae882d5/environment/puzzle/worker.Dockerfile b/tasks/agentescape-25-skeleton-3ae882d5/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-25-skeleton-3ae882d5/environment/puzzle/worker.Dockerfile @@ -0,0 +1,8 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends libseccomp2 && rm -rf /var/lib/apt/lists/* +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY worker.py child.py /app/ +COPY upstream/simulator.py /app/simulator.py +CMD ["uvicorn", "worker:app", "--host", "0.0.0.0", "--port", "8001", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-25-skeleton-3ae882d5/environment/puzzle/worker.py b/tasks/agentescape-25-skeleton-3ae882d5/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3ae882d5/environment/puzzle/worker.py @@ -0,0 +1,73 @@ +"""Stateless Python tool worker. Never receives a scenario or reference values.""" + +import json +import os +import signal +import subprocess +import sys +import tempfile +import threading + +from fastapi import FastAPI +from pydantic import BaseModel, ConfigDict + +app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) +lock = threading.Lock() + + +class Execution(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + code: str + + +@app.get("/health") +def health(): + return {"ok": True} + + +@app.post("/execute") +def execute(request: Execution): + if len(request.code.encode()) > 65536: + return {"stdout": "Error: code exceeds 64 KiB limit"} + with lock, tempfile.TemporaryDirectory(prefix="escape-code-") as directory: + os.chown(directory, 65534, 65534) + with tempfile.TemporaryFile() as output: + process = subprocess.Popen( + [sys.executable, "-I", "/app/child.py"], + stdin=subprocess.PIPE, + stdout=output, + stderr=subprocess.DEVNULL, + cwd=directory, + user=65534, + group=65534, + extra_groups=[], + start_new_session=True, + env={"PATH": "/usr/local/bin:/usr/bin:/bin"}, + ) + try: + process.communicate( + json.dumps({"code": request.code}).encode(), timeout=5 + ) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + return {"stdout": "Error: Python execution timed out"} + finally: + # Also remove children still in the process group after normal exit. + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + output.seek(0) + value = output.read(65537) + if len(value) > 65536 or process.returncode != 0: + return { + "stdout": "Error: Python execution exceeded a resource limit or failed" + } + try: + result = json.loads(value) + if not isinstance(result.get("stdout"), str): + raise ValueError("Invalid worker response") + return result + except (ValueError, AttributeError): + return {"stdout": "Error: Python execution returned invalid output"} diff --git a/tasks/agentescape-25-skeleton-3ae882d5/instruction.md b/tasks/agentescape-25-skeleton-3ae882d5/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3ae882d5/instruction.md @@ -0,0 +1,18 @@ +# Escape the room + +Discover the victory string and submit it with `escape submit-answer`. +Start with `escape observe`. This returns the room, available information, visible entities, and victory node ID. + +Use these commands (JSON responses): + +```sh +escape investigate NODE_ID +escape tool-call NODE_ID --arguments-json '{"parameter": "value"}' +escape use-item NODE_ID --arguments-json '{"parameter": "value"}' +escape submit-answer 'exact victory string' +escape state +``` + +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. + +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. diff --git a/tasks/agentescape-25-skeleton-3ae882d5/solution/oracle.py b/tasks/agentescape-25-skeleton-3ae882d5/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3ae882d5/solution/oracle.py @@ -0,0 +1,133 @@ +"""Reference solver: use trusted inputs, but obtain the answer through public actions.""" + +import json +import urllib.request +from pathlib import Path + + +def http_action(base_url, payload): + request = urllib.request.Request( + base_url + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(request, timeout=30) as response: + return json.load(response) + + +def solve(scenario, act, observe): + nodes = {node["id"]: node for node in scenario["nodes"]} + visible = {entity["id"] for entity in observe["available_entities"]} + solved = set() + seen_outputs = {} + action_count = 0 + + def call(payload): + nonlocal action_count + action_count += 1 + response = act(payload) + visible.update(entity["id"] for entity in response.get("newly_revealed", [])) + if ( + response.get("episode", {}).get("termination_reason") + == "infrastructure_error" + ): + raise RuntimeError("Infrastructure failure") + return response + + for _round in range(len(nodes) + 2): + progress = False + for node_id, node in nodes.items(): + if node_id not in visible or node_id in solved: + continue + # Preserve graph order for data inputs; trigger/drop edges express visibility. + predecessors = [ + edge["source_id"] + for edge in scenario["edges"] + if edge["target_id"] == node_id + and edge["connection_type"] not in ("Item", "Hidden_Item") + ] + if any(pred not in solved for pred in predecessors): + continue + info = call({"action": "investigate", "node_id": node_id}) + if not info.get("ok"): + raise RuntimeError(f"Investigation failed: {node_id}: {info}") + inputs = { + port["name"]: port["value"] + for port in node.get("inputs", []) + if "value" in port + } + if node["type"] == "Tool": + result = call( + {"action": "tool_call", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok") or result.get("output_values", {}).get("error"): + raise RuntimeError(f"Tool failed: {node_id}: {result}") + output = result.get("output_values", {}) + if node.get("template_id") in ("terminal_1", "terminal_2"): + slots = { + port["name"]: inputs[port["name"]] + for port in node["inputs"] + if port["type"] not in ("Item", "Hidden_Item") + and port["name"] in inputs + } + triggers = { + key: value for key, value in inputs.items() if key not in slots + } + for key, value in slots.items(): + partial = call( + { + "action": "tool_call", + "node_id": node_id, + "arguments": {**triggers, key: value}, + } + ) + if partial.get("ok"): + output.update(partial.get("output_values", {})) + # HIDDEN_ITEM tool drops only occur on subsequent investigation. + call({"action": "investigate", "node_id": node_id}) + elif info.get("required_inputs"): + result = call( + {"action": "use_item", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok"): + raise RuntimeError(f"Item failed: {node_id}: {result}") + output = result.get("content") + else: + output = info.get("content") + seen_outputs[node_id] = output + solved.add(node_id) + progress = True + win_id = scenario["metadata"]["win_node_id"] + if win_id in solved and (len(solved) == len(nodes) or not progress): + outputs = seen_outputs[win_id] + if not outputs: + raise RuntimeError(f"Victory node returned no output: {win_id}") + # Upstream grades its first stored output port, independent of response order. + victory_port = next( + port["name"] for port in nodes[win_id]["outputs"] if "value" in port + ) + answer = outputs[victory_port] if isinstance(outputs, dict) else outputs + result = call({"action": "submit_answer", "answer": answer}) + if not result.get("is_win"): + raise RuntimeError(f"Victory submission failed: {result}") + return {"won": True, "actions": action_count, "visited_nodes": len(solved)} + if not progress: + raise RuntimeError(f"No progress: visible={visible}, solved={solved}") + raise RuntimeError("Reference solver exceeded graph traversal limit") + + +if __name__ == "__main__": + import os + + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000") + with urllib.request.urlopen(base + "/observation", timeout=20) as response: + observation = json.load(response) + print( + json.dumps( + solve( + json.loads(Path("/solution/scenario.json").read_text()), + lambda payload: http_action(base, payload), + observation, + ) + ) + ) diff --git a/tasks/agentescape-25-skeleton-3ae882d5/solution/scenario.json b/tasks/agentescape-25-skeleton-3ae882d5/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..c0d1c3f53b2a6c86fa15c07fdfd37a30b3bb81be --- /dev/null +++ b/tasks/agentescape-25-skeleton-3ae882d5/solution/scenario.json @@ -0,0 +1,1466 @@ +{ + "metadata": { + "total_nodes": 25, + "total_edges": 43, + "win_node_id": "crypto_rsa_decrypt_hex", + "win_condition": { + "type": "tool_output", + "node_id": "crypto_rsa_decrypt_hex", + "output_port": "text", + "output_type": "Text_Generic", + "description": "Execute RSA Decrypt and get the output from port 'text'" + }, + "source_init": { + "source_nodes": [ + "terminal_1", + "calc_modexp_90b3", + "terminal_1_ccb2", + "zip_unzip_file", + "base64_decode", + "calc_modexp_483a", + "item_1", + "hex_decode", + "csv_query" + ], + "by_node": { + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": {}, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + }, + "item_dispenser": { + "type": "Item", + "description": "Item output when both slots are provided" + } + } + }, + "calc_modexp_90b3": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "base": { + "type": "Big_Int", + "description": "Base" + } + }, + "init_outputs": {} + }, + "terminal_1_ccb2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": {}, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + }, + "item_dispenser": { + "type": "Item", + "description": "Item output when both slots are provided" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "base64_decode": { + "node_name": "Base64 Decoder", + "node_type": "Tool", + "template_id": "base64_decode", + "init_inputs": { + "data": { + "type": "Text_Generic", + "description": "Base64 string" + } + }, + "init_outputs": {} + }, + "calc_modexp_483a": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "exp": { + "type": "Big_Int", + "description": "Exponent" + } + }, + "init_outputs": {} + }, + "item_1": { + "node_name": "", + "node_type": "Item", + "template_id": "item_1", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Big_Int", + "description": "The number" + } + } + }, + "hex_decode": { + "node_name": "Hex to Text Decoder", + "node_type": "Tool", + "template_id": "hex_decode", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex string" + } + }, + "init_outputs": {} + }, + "csv_query": { + "node_name": "CSV Query", + "node_type": "Tool", + "template_id": "csv_query", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "CSV file ID" + }, + "select": { + "type": "Text_Generic", + "description": "Columns to select" + }, + "where": { + "type": "Text_Generic", + "description": "Where clause" + } + }, + "init_outputs": { + "rows": { + "type": "Text_Generic", + "description": "Result rows" + } + } + } + } + }, + "initial_values": { + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "Terminal 1 operation executed completely.", + "hex_output": "1a2b3c4d5e6f7a8b9c0d", + "item_dispenser": "A completely useless empty box output" + } + }, + "calc_modexp_90b3": { + "init_inputs": { + "base": "31" + }, + "init_outputs": {} + }, + "terminal_1_ccb2": { + "init_inputs": {}, + "init_outputs": { + "text_output": "Secondary terminal process finished successfully.", + "hex_output": "ffeeddccbbaa99887766554433221100", + "item_dispenser": "A rusted cogwheel with no mechanism" + } + }, + "zip_unzip_file": { + "init_inputs": { + "zip_id": "secure_archive_54.zip" + }, + "init_outputs": { + "files": "extracted_data_54.dat" + } + }, + "base64_decode": { + "init_inputs": { + "data": "U2VjcmV0IG1lc3NhZ2UgZGVjb2RlZA==" + }, + "init_outputs": {} + }, + "calc_modexp_483a": { + "init_inputs": { + "exp": "84759382019384756201" + }, + "init_outputs": {} + }, + "item_1": { + "init_inputs": {}, + "init_outputs": { + "content": "91827364554637281920" + } + }, + "hex_decode": { + "init_inputs": { + "hex": "546869732069732061207465737420737472696e67" + }, + "init_outputs": {} + }, + "csv_query": { + "init_inputs": { + "file_id": "financial_records_2023.csv", + "select": "transaction_id, amount, date", + "where": "amount > 5000" + }, + "init_outputs": { + "rows": "[{\"transaction_id\":\"TX1001\",\"amount\":6000,\"date\":\"2023-01-05\"},{\"transaction_id\":\"TX1002\",\"amount\":7500,\"date\":\"2023-01-10\"},{\"transaction_id\":\"TX1003\",\"amount\":8200,\"date\":\"2023-01-15\"}]" + } + } + }, + "intro_narrative": "You step into the dusty ruins of Precinct 42, a station abandoned years ago after the infamous 'Phantom' hacker corrupted all the critical evidence files in the city. You are Detective Miller's former partner, returning to this forgotten place to finish what he started before he mysteriously disappeared. The precinct is a labyrinth of disconnected mainframe terminals, scattered case files, and sealed evidence vaults. The air is thick with the smell of stale coffee and old paper. Your objective is clear: navigate this maze of archaic technology and piece together the fractured digital trail left behind by both Miller and the Phantom. To uncover the ultimate truth, you must process the raw evidence and reconstruct the sequence of events. The final, damning piece of the puzzle lies hidden deep within The Master Decryption Terminal. Only by correctly routing the clues through the various analytical devices scattered around the room can you break the final cipher and solve the cold case.", + "narrative_style": "detective" + }, + "nodes": [ + { + "id": "crypto_rsa_decrypt_hex", + "name": "RSA Decrypt", + "description": "RSA decrypt (hex cipher) with n,d (decimal).", + "type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex_cipher", + "type": "Hex_String", + "description": "Ciphertext (Hex)", + "value": "39a6f4a5" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Modulus n", + "value": "1" + }, + { + "name": "d", + "type": "Big_Int", + "description": "Private exponent d", + "value": "3143408493" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decrypted text", + "value": "\u0000" + } + ], + "narrative": "This is The Master Decryption Terminal. It requires inputs from The Fingerprint Scanner, The Primary Code Breaker, and The Alibi Verifier to reveal the final truth." + }, + { + "id": "checksum_crc32", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "a177a7205e6f7a8b9c0d" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "39a6f4a5" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 967242917 + } + ], + "narrative": "This is The Fingerprint Scanner. It requires input from The Cipher Overlay to analyze the digital prints." + }, + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": 3143408493 + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "0" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "3143408493" + } + ], + "narrative": "This is The Primary Code Breaker. It requires inputs from both The Motive Processor and The Integrity Checker." + }, + { + "id": "calc_modexp", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "1" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "0" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": 3143408493 + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "1" + } + ], + "narrative": "This is The Alibi Verifier. It requires inputs from The Integrity Checker, The Pattern Matcher, and The Suspect Profiler to validate alibis." + }, + { + "id": "checksum_crc32_47c3", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "536563726574206d657373616765206465636f646564" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "bb5c9b6d" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3143408493 + } + ], + "narrative": "This is The Integrity Checker. It requires input from The Evidence Decoder to verify the data integrity." + }, + { + "id": "calc_modexp_989e", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": 967242917 + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "1" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "1" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "0" + } + ], + "narrative": "This is The Motive Processor. It requires inputs from The Format Converter, The Fingerprint Scanner, and The Alibi Verifier to deduce intentions." + }, + { + "id": "num_base_convert", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "1" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": 3143408493 + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "0" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "1" + } + ], + "narrative": "This is The Format Converter. It requires inputs from The Timeline Reconstructor, The Integrity Checker, and The Suspect Profiler." + }, + { + "id": "calc_gcd_564d", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "1" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "1" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "narrative": "This is The Timeline Reconstructor. It requires inputs from both The Pattern Matcher and The Alibi Verifier to build a chronology." + }, + { + "id": "text_xor_hex", + "name": "Hex XOR", + "description": "XOR two hex strings.", + "type": "Tool", + "template_id": "text_xor_hex", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex_a", + "type": "Hex_String", + "description": "Hex A", + "value": "bb5c9b6d" + }, + { + "name": "hex_b", + "type": "Hex_String", + "description": "Hex B", + "value": "1a2b3c4d5e6f7a8b9c0d" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "XOR Result Hex", + "value": "a177a7205e6f7a8b9c0d" + } + ], + "narrative": "This is The Cipher Overlay. It requires inputs from both The Integrity Checker and The Main Frame." + }, + { + "id": "calc_gcd_86c2", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": 3143408493 + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": 967242917 + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "narrative": "This is The Pattern Matcher. It requires inputs from both The Fingerprint Scanner and The Integrity Checker." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "Secondary terminal process finished successfully." + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "1" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Terminal 1 operation executed completely." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "1a2b3c4d5e6f7a8b9c0d" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided", + "value": "A completely useless empty box output" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "Terminal 1 operation executed completely.", + "hex_output": "1a2b3c4d5e6f7a8b9c0d", + "item_dispenser": "A completely useless empty box output" + } + }, + "narrative": "This is The Main Frame. It requires inputs from both The Backup Terminal and The Reversal Engine to gain full system access." + }, + { + "id": "calc_modexp_90b3", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "31" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": 3143408493 + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "1" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "0" + } + ], + "init": { + "inputs": { + "base": "31" + }, + "outputs": {} + }, + "narrative": "This is The Suspect Profiler. It requires inputs from both The Integrity Checker and The Pattern Matcher to narrow down the culprits." + }, + { + "id": "terminal_1_ccb2", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this terminal" + }, + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "u1ybbQ==" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": 3143408493 + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Secondary terminal process finished successfully." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "ffeeddccbbaa99887766554433221100" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided", + "value": "A rusted cogwheel with no mechanism" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "Secondary terminal process finished successfully.", + "hex_output": "ffeeddccbbaa99887766554433221100", + "item_dispenser": "A rusted cogwheel with no mechanism" + } + }, + "narrative": "This is The Backup Terminal. It requires inputs from both The Signal Encoder and The Integrity Checker to initialize." + }, + { + "id": "container_1", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_1", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by", + "value": "synthesized_item_717ac506950da0cc" + }, + { + "name": "fingerprint_input", + "type": "Hex_String", + "description": "Fingerprint Hash", + "value": "bb5c9b6d" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is The Evidence Vault. It requires input from The Integrity Checker to unlock its mechanical seal." + }, + { + "id": "zip_unzip_item", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_item", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "extracted_data_54.dat" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "u1ybbQ==" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip" + } + ], + "narrative": "This is The Case File Unpacker. It requires inputs from both The Signal Encoder and The Archive Extractor to open sealed files." + }, + { + "id": "base64_encode", + "name": "Base64 Encoder", + "description": "Encode hex bytes to base64.", + "type": "Tool", + "template_id": "base64_encode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex bytes", + "value": "bb5c9b6d" + } + ], + "outputs": [ + { + "name": "b64", + "type": "Text_Generic", + "description": "Base64 string", + "value": "u1ybbQ==" + } + ], + "narrative": "This is The Signal Encoder. It requires input from The Integrity Checker to transmit data securely." + }, + { + "id": "calc_inv_mod", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "1" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": 3143408493 + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "1" + } + ], + "narrative": "This is The Reversal Engine. It requires inputs from both The Forensic Analyzer and The Integrity Checker to invert the logic." + }, + { + "id": "calc_gcd_028c", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": 3143408493 + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "1860539552" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "narrative": "This is The Forensic Analyzer. It requires inputs from both The Integrity Checker and The Ballistics Calculator to cross-reference data." + }, + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "secure_archive_54.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "[{\"transaction_id\":\"TX1001\",\"amount\":6000,\"date\":\"2023-01-05\"},{\"transaction_id\":\"TX1002\",\"amount\":7500,\"date\":\"2023-01-10\"},{\"transaction_id\":\"TX1003\",\"amount\":8200,\"date\":\"2023-01-15\"}]" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_data_54.dat" + } + ], + "init": { + "inputs": { + "zip_id": "secure_archive_54.zip" + }, + "outputs": { + "files": "extracted_data_54.dat" + } + }, + "narrative": "This is The Archive Extractor. It requires input from The Police Database to pull the correct case records." + }, + { + "id": "base64_decode", + "name": "Base64 Decoder", + "description": "Decode base64 to hex bytes.", + "type": "Tool", + "template_id": "base64_decode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "data", + "type": "Text_Generic", + "description": "Base64 string", + "value": "U2VjcmV0IG1lc3NhZ2UgZGVjb2RlZA==" + } + ], + "outputs": [ + { + "name": "bytes_hex", + "type": "Hex_String", + "description": "Decoded bytes as Hex", + "value": "536563726574206d657373616765206465636f646564" + } + ], + "init": { + "inputs": { + "data": "U2VjcmV0IG1lc3NhZ2UgZGVjb2RlZA==" + }, + "outputs": {} + }, + "narrative": "A rugged field computer known as The Evidence Decoder." + }, + { + "id": "matter_synthesizer", + "name": "Matter Synthesizer", + "description": "Synthesizes physical objects from data blueprints.", + "type": "Tool", + "template_id": "matter_synthesizer", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "blueprint", + "type": "Text_Generic", + "description": "Object Blueprint", + "value": "This is a test string" + } + ], + "outputs": [ + { + "name": "output_slot", + "type": "Item", + "description": "Synthesized Object", + "value": "synthesized_item_717ac506950da0cc" + } + ], + "narrative": "This is The Evidence Printer. It requires input from The Note Translator to synthesize physical clues." + }, + { + "id": "calc_modexp_483a", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "91827364554637281920" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "84759382019384756201" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": 3143408493 + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "1860539552" + } + ], + "init": { + "inputs": { + "exp": "84759382019384756201" + }, + "outputs": {} + }, + "narrative": "This is The Ballistics Calculator. It requires inputs from both The Integrity Checker and The Victim's Pocket Watch to trace trajectories." + }, + { + "id": "item_1", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "Big_Int", + "description": "The number", + "value": "91827364554637281920" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "91827364554637281920" + } + }, + "narrative": "The Victim's Pocket Watch. It stopped at the exact time of the crime." + }, + { + "id": "hex_decode", + "name": "Hex to Text Decoder", + "description": "Decode hex to UTF-8 text.", + "type": "Tool", + "template_id": "hex_decode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "hex", + "type": "Hex_String", + "description": "Hex string", + "value": "546869732069732061207465737420737472696e67" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decoded text", + "value": "This is a test string" + } + ], + "init": { + "inputs": { + "hex": "546869732069732061207465737420737472696e67" + }, + "outputs": {} + }, + "narrative": "A small decryption device known as The Note Translator." + }, + { + "id": "csv_query", + "name": "CSV Query", + "description": "Query CSV: select columns and simple WHERE.", + "type": "Tool", + "template_id": "csv_query", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "CSV file ID", + "value": "financial_records_2023.csv" + }, + { + "name": "select", + "type": "Text_Generic", + "description": "Columns to select", + "value": "transaction_id, amount, date" + }, + { + "name": "where", + "type": "Text_Generic", + "description": "Where clause", + "value": "amount > 5000" + } + ], + "outputs": [ + { + "name": "rows", + "type": "Text_Generic", + "description": "Result rows", + "value": "[{\"transaction_id\":\"TX1001\",\"amount\":6000,\"date\":\"2023-01-05\"},{\"transaction_id\":\"TX1002\",\"amount\":7500,\"date\":\"2023-01-10\"},{\"transaction_id\":\"TX1003\",\"amount\":8200,\"date\":\"2023-01-15\"}]" + } + ], + "init": { + "inputs": { + "file_id": "financial_records_2023.csv", + "select": "transaction_id, amount, date", + "where": "amount > 5000" + }, + "outputs": { + "rows": "[{\"transaction_id\":\"TX1001\",\"amount\":6000,\"date\":\"2023-01-05\"},{\"transaction_id\":\"TX1002\",\"amount\":7500,\"date\":\"2023-01-10\"},{\"transaction_id\":\"TX1003\",\"amount\":8200,\"date\":\"2023-01-15\"}]" + } + }, + "narrative": "An old terminal hooked up to The Police Database." + } + ], + "edges": [ + { + "source_id": "checksum_crc32", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_cipher" + }, + { + "source_id": "calc_gcd", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "d" + }, + { + "source_id": "calc_modexp", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "n" + }, + { + "source_id": "checksum_crc32_47c3", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "mod" + }, + { + "source_id": "calc_modexp_989e", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "b" + }, + { + "source_id": "num_base_convert", + "target_id": "calc_modexp_989e", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "mod" + }, + { + "source_id": "calc_gcd_564d", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "s" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp_989e", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "base" + }, + { + "source_id": "calc_modexp", + "target_id": "calc_modexp_989e", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "exp" + }, + { + "source_id": "checksum_crc32_47c3", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "a" + }, + { + "source_id": "text_xor_hex", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "checksum_crc32_47c3", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "from_base" + }, + { + "source_id": "calc_gcd_86c2", + "target_id": "calc_gcd_564d", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "a" + }, + { + "source_id": "checksum_crc32_47c3", + "target_id": "text_xor_hex", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_a" + }, + { + "source_id": "calc_modexp", + "target_id": "calc_gcd_564d", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "b" + }, + { + "source_id": "terminal_1", + "target_id": "text_xor_hex", + "connection_type": "Hex_String", + "source_port": "hex_output", + "target_port": "hex_b" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_gcd_86c2", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "b" + }, + { + "source_id": "calc_gcd_86c2", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "base" + }, + { + "source_id": "checksum_crc32_47c3", + "target_id": "calc_gcd_86c2", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "a" + }, + { + "source_id": "calc_modexp_90b3", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "exp" + }, + { + "source_id": "terminal_1_ccb2", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "slot_a" + }, + { + "source_id": "container_1", + "target_id": "calc_modexp_90b3", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "zip_unzip_item", + "target_id": "terminal_1_ccb2", + "connection_type": "Item", + "source_port": "item", + "target_port": "trigger_item" + }, + { + "source_id": "checksum_crc32_47c3", + "target_id": "calc_modexp_90b3", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "exp" + }, + { + "source_id": "calc_gcd_86c2", + "target_id": "calc_modexp_90b3", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "mod" + }, + { + "source_id": "base64_encode", + "target_id": "terminal_1_ccb2", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "slot_a" + }, + { + "source_id": "checksum_crc32_47c3", + "target_id": "terminal_1_ccb2", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "slot_b" + }, + { + "source_id": "checksum_crc32_47c3", + "target_id": "base64_encode", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "base64_encode", + "target_id": "zip_unzip_item", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "password" + }, + { + "source_id": "calc_modexp_90b3", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "to_base" + }, + { + "source_id": "calc_inv_mod", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "slot_b" + }, + { + "source_id": "calc_gcd_028c", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "a" + }, + { + "source_id": "checksum_crc32_47c3", + "target_id": "container_1", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "fingerprint_input" + }, + { + "source_id": "checksum_crc32_47c3", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "mod" + }, + { + "source_id": "zip_unzip_file", + "target_id": "zip_unzip_item", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "base64_decode", + "target_id": "checksum_crc32_47c3", + "connection_type": "Hex_String", + "source_port": "bytes_hex", + "target_port": "hex" + }, + { + "source_id": "checksum_crc32_47c3", + "target_id": "calc_gcd_028c", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "a" + }, + { + "source_id": "matter_synthesizer", + "target_id": "container_1", + "connection_type": "Item", + "source_port": "output_slot", + "target_port": "source_tool" + }, + { + "source_id": "calc_modexp_483a", + "target_id": "calc_gcd_028c", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "b" + }, + { + "source_id": "checksum_crc32_47c3", + "target_id": "calc_modexp_483a", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "mod" + }, + { + "source_id": "item_1", + "target_id": "calc_modexp_483a", + "connection_type": "Big_Int", + "source_port": "content", + "target_port": "base" + }, + { + "source_id": "hex_decode", + "target_id": "matter_synthesizer", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "blueprint" + }, + { + "source_id": "csv_query", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "rows", + "target_port": "password" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-3ae882d5/solution/solve.sh b/tasks/agentescape-25-skeleton-3ae882d5/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3ae882d5/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-25-skeleton-3ae882d5/task.toml b/tasks/agentescape-25-skeleton-3ae882d5/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2057972e256415d34837decb169cd97d4cc58a59 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3ae882d5/task.toml @@ -0,0 +1,38 @@ +schema_version = "1.4" +source = "https://github.com/AGI-Eval-Official/Repo-of-AgentEscapeBench" + +[[artifacts]] +source = "/evidence/final.json" +service = "puzzle" + +[[artifacts]] +source = "/evidence/trace.jsonl" +service = "puzzle" + +[task] +name = "edbeeching/agentescape-25-skeleton-3ae882d5" +version = "0.1.0" + +[metadata] +difficulty = 25 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "642f463a47daeb81812cc4ee158fd846feb78302bbb581cdceee7b2ba344c79a" +protocol = "harbor-cli-action-budget-v1" +max_actions = 500 + +[agent] +timeout_sec = 1200 + +[environment] +build_timeout_sec = 900 +cpus = 1 +memory_mb = 1024 + +[verifier] +environment_mode = "separate" +timeout_sec = 60 + +[[verifier.collect]] +service = "puzzle" +command = "python -I /app/export.py" +timeout_sec = 15 diff --git a/tasks/agentescape-25-skeleton-3ae882d5/tests/Dockerfile b/tasks/agentescape-25-skeleton-3ae882d5/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-25-skeleton-3ae882d5/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-25-skeleton-3ae882d5/tests/expected.json b/tasks/agentescape-25-skeleton-3ae882d5/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..c97d40560b57abbe62669dfc2a333af647120b1d --- /dev/null +++ b/tasks/agentescape-25-skeleton-3ae882d5/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "642f463a47daeb81812cc4ee158fd846feb78302bbb581cdceee7b2ba344c79a", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-3ae882d5/tests/grade.py b/tasks/agentescape-25-skeleton-3ae882d5/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3ae882d5/tests/grade.py @@ -0,0 +1,21 @@ +"""Grade only Harbor-collected sidecar evidence in a fresh verifier container.""" + +import json +from pathlib import Path + +expected = json.loads(Path("/tests/expected.json").read_text()) +state = json.loads(Path("/evidence/final.json").read_text()) +assert state["collected_from_live_service"] is True, "Missing trusted service export" +assert state["scenario_sha256"] == expected["scenario_sha256"], ( + "Wrong scenario evidence" +) +assert state["max_actions"] == expected["max_actions"], "Wrong budget" +assert type(state["won"]) is bool +assert 0 <= state["action_count"] <= state["max_actions"] +assert state["termination_reason"] != "infrastructure_error", ( + "Infrastructure failure is not a puzzle failure" +) +assert not state["won"] or state["termination_reason"] == "success" +Path("/logs/verifier").mkdir(parents=True, exist_ok=True) +Path("/logs/verifier/state.json").write_text(json.dumps(state, indent=2)) +Path("/logs/verifier/reward.txt").write_text("1.0\n" if state["won"] else "0.0\n") diff --git a/tasks/agentescape-25-skeleton-3ae882d5/tests/test.sh b/tasks/agentescape-25-skeleton-3ae882d5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3ae882d5/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-25-skeleton-3cee13d8/environment/Dockerfile b/tasks/agentescape-25-skeleton-3cee13d8/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3cee13d8/environment/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-25-skeleton-3cee13d8/environment/agent/Dockerfile b/tasks/agentescape-25-skeleton-3cee13d8/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3cee13d8/environment/agent/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-25-skeleton-3cee13d8/environment/agent/cli.py b/tasks/agentescape-25-skeleton-3cee13d8/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-25-skeleton-3cee13d8/environment/agent/cli.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Public agent client; depends only on the Python standard library.""" + +import argparse +import json +import os +import sys +import urllib.error +import urllib.request + + +def main(): + parser = argparse.ArgumentParser(description="Interact with the escape room") + parser.add_argument( + "action", + choices=[ + "observe", + "state", + "investigate", + "tool-call", + "use-item", + "submit-answer", + ], + ) + parser.add_argument("value", nargs="?") + parser.add_argument("--arguments-json", default="{}") + args = parser.parse_args() + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000").rstrip("/") + if args.action in ("observe", "state"): + request = urllib.request.Request( + base + ("/observation" if args.action == "observe" else "/state") + ) + else: + if args.value is None: + parser.error("node ID or answer is required") + payload = {"action": args.action.replace("-", "_")} + if args.action == "submit-answer": + payload["answer"] = args.value + else: + payload["node_id"] = args.value + if args.action in ("tool-call", "use-item"): + payload["arguments"] = json.loads(args.arguments_json) + request = urllib.request.Request( + base + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=30) as response: + print(json.dumps(json.load(response), ensure_ascii=False)) + except (urllib.error.URLError, ValueError) as exc: + print(json.dumps({"ok": False, "error": str(exc)})) + sys.exit(2) + + +if __name__ == "__main__": + main() diff --git a/tasks/agentescape-25-skeleton-3cee13d8/environment/docker-compose.yaml b/tasks/agentescape-25-skeleton-3cee13d8/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7283c3956a2030a76acf08ac106001f864489fee --- /dev/null +++ b/tasks/agentescape-25-skeleton-3cee13d8/environment/docker-compose.yaml @@ -0,0 +1,50 @@ +services: + main: + image: agentescapebench-agent:aab05a0a9ddb + build: + context: ./agent + networks: [default, puzzle] + security_opt: [no-new-privileges:true] + depends_on: + puzzle: + condition: service_healthy + puzzle: + image: agentescapebench-puzzle:agentescape-25-skeleton-3cee13d8-aab05a0a9ddb + build: + context: ./puzzle + networks: [puzzle, execution] + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 512m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"] + interval: 1s + timeout: 3s + retries: 30 + depends_on: + worker: + condition: service_healthy + worker: + image: agentescapebench-worker:aab05a0a9ddb + build: + context: ./puzzle + dockerfile: worker.Dockerfile + networks: [execution] + read_only: true + tmpfs: ["/tmp:size=64m,mode=1777"] + cap_drop: [ALL] + cap_add: [SETUID, SETGID, KILL, CHOWN, DAC_OVERRIDE] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 384m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8001/health')"] + interval: 1s + timeout: 3s + retries: 30 +networks: + puzzle: + internal: true + execution: + internal: true diff --git a/tasks/agentescape-25-skeleton-3cee13d8/environment/puzzle/Dockerfile b/tasks/agentescape-25-skeleton-3cee13d8/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3cee13d8/environment/puzzle/Dockerfile @@ -0,0 +1,9 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY upstream /app/upstream +COPY service.py export.py /app/ +COPY scenario.json /private/scenario.json +ENV SCENARIO_PATH=/private/scenario.json EVIDENCE_DIR=/evidence WORKER_URL=http://worker:8001 MAX_ACTIONS=500 +CMD ["uvicorn", "service:create_app", "--factory", "--host", "0.0.0.0", "--port", "8000", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-25-skeleton-3cee13d8/environment/puzzle/child.py b/tasks/agentescape-25-skeleton-3cee13d8/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3cee13d8/environment/puzzle/child.py @@ -0,0 +1,59 @@ +"""Run the original Python tool after reducing privileges and blocking networking.""" + +import ctypes +import errno +import json +import resource +import sys + +resource.setrlimit(resource.RLIMIT_CPU, (3, 3)) +resource.setrlimit(resource.RLIMIT_AS, (256 * 1024 * 1024, 256 * 1024 * 1024)) +resource.setrlimit(resource.RLIMIT_FSIZE, (65536, 65536)) +resource.setrlimit(resource.RLIMIT_NOFILE, (32, 32)) +resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + +# Filters survive fork/exec. Fail closed if seccomp cannot be loaded. +lib = ctypes.CDLL("libseccomp.so.2", use_errno=True) +lib.seccomp_init.argtypes = [ctypes.c_uint32] +lib.seccomp_init.restype = ctypes.c_void_p +lib.seccomp_rule_add.argtypes = [ + ctypes.c_void_p, + ctypes.c_uint32, + ctypes.c_int, + ctypes.c_uint, +] +lib.seccomp_syscall_resolve_name.argtypes = [ctypes.c_char_p] +lib.seccomp_load.argtypes = [ctypes.c_void_p] +lib.seccomp_release.argtypes = [ctypes.c_void_p] +ctx = lib.seccomp_init(0x7FFF0000) # SCMP_ACT_ALLOW +if not ctx: + raise RuntimeError("Cannot initialize execution isolation") +try: + for name in ( + "socket", + "socketpair", + "connect", + "ptrace", + "process_vm_readv", + "process_vm_writev", + "mount", + "unshare", + "setns", + "bpf", + ): + number = lib.seccomp_syscall_resolve_name(name.encode()) + if ( + number >= 0 + and lib.seccomp_rule_add(ctx, 0x00050000 | errno.EPERM, number, 0) != 0 + ): + raise RuntimeError("Cannot install execution isolation rule") + if lib.seccomp_load(ctx) != 0: + raise RuntimeError("Cannot activate execution isolation") +finally: + lib.seccomp_release(ctx) + +sys.path.insert(0, "/app") +from simulator import ToolSimulator # noqa: E402 + +request = json.load(sys.stdin) +json.dump(ToolSimulator().code_py_exec(request), sys.stdout) diff --git a/tasks/agentescape-25-skeleton-3cee13d8/environment/puzzle/export.py b/tasks/agentescape-25-skeleton-3cee13d8/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3cee13d8/environment/puzzle/export.py @@ -0,0 +1,13 @@ +"""Harbor invokes this inside the puzzle service after stopping the agent.""" + +import json +import pathlib +import urllib.request + +with urllib.request.urlopen("http://127.0.0.1:8000/state", timeout=10) as response: + state = json.load(response) +state["collected_from_live_service"] = True +target = pathlib.Path("/evidence/final.json") +temp = target.with_suffix(".tmp") +temp.write_text(json.dumps(state)) +temp.replace(target) diff --git a/tasks/agentescape-25-skeleton-3cee13d8/environment/puzzle/requirements.txt b/tasks/agentescape-25-skeleton-3cee13d8/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3cee13d8/environment/puzzle/requirements.txt @@ -0,0 +1,57 @@ +annotated-doc==0.0.5 + # via fastapi +annotated-types==0.8.0 + # via pydantic +anyio==4.16.0 + # via starlette +certifi==2026.10.23 + # via requests +cffi==2.1.1 ; platform_python_implementation != 'PyPy' + # via cryptography +charset-normalizer==3.5.2 + # via requests +click==8.5.0 + # via uvicorn +cryptography==50.0.2 + # via agentescapebench-harbor +fastapi==0.162.0 + # via agentescapebench-harbor +h11==0.16.0 + # via uvicorn +idna==3.20 + # via + # anyio + # requests +opentelemetry-api==1.45.2 + # via fastapi +pycparser==3.12 ; implementation_name != 'PyPy' and platform_python_implementation != 'PyPy' + # via cffi +pydantic==2.14.2 + # via + # agentescapebench-harbor + # fastapi +pydantic-core==2.50.2 + # via pydantic +pytz==2025.2 + # via agentescapebench-harbor +requests==2.34.2 + # via agentescapebench-harbor +starlette==1.10.0 + # via fastapi +typing-extensions==4.16.0 + # via + # anyio + # fastapi + # opentelemetry-api + # pydantic + # pydantic-core + # starlette + # typing-inspection +typing-inspection==0.4.4 + # via + # fastapi + # pydantic +urllib3==2.8.0 + # via requests +uvicorn==0.54.0 + # via agentescapebench-harbor diff --git a/tasks/agentescape-25-skeleton-3cee13d8/environment/puzzle/scenario.json b/tasks/agentescape-25-skeleton-3cee13d8/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..bf8d93cf51930b20ced7f9deb0f27358d1a37e86 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3cee13d8/environment/puzzle/scenario.json @@ -0,0 +1,1652 @@ +{ + "metadata": { + "total_nodes": 25, + "total_edges": 32, + "win_node_id": "calc_modexp", + "win_condition": { + "type": "tool_output", + "node_id": "calc_modexp", + "output_port": "value", + "output_type": "Big_Int", + "description": "Execute BigInt Modular Exponentiation and get the output from port 'value'" + }, + "source_init": { + "source_nodes": [ + "graph_shortest_path", + "zip_unzip_file", + "iban_validate", + "zip_unzip_file_a829", + "calc_bigmul", + "item_11", + "crypto_rsa_decrypt_hex", + "terminal_2", + "calc_inv_mod", + "graph_shortest_path_fb93", + "graph_shortest_path_991f", + "zip_unzip_file_8b4a", + "terminal_2_d217", + "terminal_1", + "text_rotN" + ], + "by_node": { + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": {}, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "iban_validate": { + "node_name": "IBAN Validator", + "node_type": "Tool", + "template_id": "iban_validate", + "init_inputs": { + "iban": { + "type": "Text_Generic", + "description": "IBAN string" + } + }, + "init_outputs": {} + }, + "zip_unzip_file_a829": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "calc_bigmul": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "b": { + "type": "Big_Int", + "description": "Second large integer" + } + }, + "init_outputs": {} + }, + "item_11": { + "node_name": "", + "node_type": "Item", + "template_id": "item_11", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Code_Python", + "description": "Python code" + } + } + }, + "crypto_rsa_decrypt_hex": { + "node_name": "RSA Decrypt", + "node_type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "init_inputs": { + "d": { + "type": "Big_Int", + "description": "Private exponent d" + } + }, + "init_outputs": {} + }, + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": { + "num2": { + "type": "Big_Int", + "description": "Second Number" + } + }, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + } + } + }, + "calc_inv_mod": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "Integer a" + }, + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "graph_shortest_path_fb93": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "Graph JSON file ID" + }, + "src": { + "type": "Text_Generic", + "description": "Source node" + }, + "dst": { + "type": "Text_Generic", + "description": "Destination node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "graph_shortest_path_991f": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "Graph JSON file ID" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "zip_unzip_file_8b4a": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "terminal_2_d217": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": { + "num1": { + "type": "Big_Int", + "description": "First Number" + }, + "num2": { + "type": "Big_Int", + "description": "Second Number" + } + }, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + }, + "math_token": { + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + } + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": { + "slot_a": { + "type": "Text_Generic", + "description": "Input Slot A" + }, + "slot_b": { + "type": "Big_Int", + "description": "Input Slot B" + } + }, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + }, + "item_dispenser": { + "type": "Item", + "description": "Item output when both slots are provided" + } + } + }, + "text_rotN": { + "node_name": "ROT-N Cipher", + "node_type": "Tool", + "template_id": "text_rotN", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text" + }, + "n": { + "type": "Big_Int", + "description": "Shift N" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "graph_shortest_path": { + "init_inputs": {}, + "init_outputs": { + "path": "[\"NodeA\", \"NodeB\", \"NodeC\", \"NodeD\", \"NodeE\"]", + "cost": "854123" + } + }, + "zip_unzip_file": { + "init_inputs": {}, + "init_outputs": { + "files": "extracted_data_749.txt" + } + }, + "iban_validate": { + "init_inputs": { + "iban": "FR7630006000011234567890189" + }, + "init_outputs": {} + }, + "zip_unzip_file_a829": { + "init_inputs": {}, + "init_outputs": { + "files": "config_archive_42.zip" + } + }, + "calc_bigmul": { + "init_inputs": { + "b": "83920194857291029384" + }, + "init_outputs": {} + }, + "item_11": { + "init_inputs": {}, + "init_outputs": { + "content": "def hello():\n print('Hello World')\n return True" + } + }, + "crypto_rsa_decrypt_hex": { + "init_inputs": { + "d": "59283740192837461029" + }, + "init_outputs": {} + }, + "terminal_2": { + "init_inputs": { + "num2": "10293847561029384756" + }, + "init_outputs": { + "text_result": "Calculation sequence finished successfully.", + "hex_result": "b83c2f9a1e0d" + } + }, + "calc_inv_mod": { + "init_inputs": { + "a": "29384710293847561029", + "mod": "104729" + }, + "init_outputs": {} + }, + "graph_shortest_path_fb93": { + "init_inputs": { + "file_id": "graph_network_data.json", + "src": "Node_Alpha", + "dst": "Node_Omega" + }, + "init_outputs": { + "path": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Omega\"]", + "cost": "129384" + } + }, + "graph_shortest_path_991f": { + "init_inputs": { + "file_id": "route_map_49.json" + }, + "init_outputs": { + "path": "[\"A1\", \"B2\", \"C3\", \"D4\", \"E5\"]", + "cost": "509123" + } + }, + "zip_unzip_file_8b4a": { + "init_inputs": { + "zip_id": "encrypted_payload_2.zip" + }, + "init_outputs": { + "files": "unzipped_docs.pdf" + } + }, + "terminal_2_d217": { + "init_inputs": { + "num1": "49283746102938475610", + "num2": "75849302184756291023" + }, + "init_outputs": { + "text_result": "System processed partial instructions.", + "hex_result": "11223344aabbccdd", + "math_token": "Math token useless here" + } + }, + "terminal_1": { + "init_inputs": { + "slot_a": "Insert instruction A", + "slot_b": "84930281928374651029" + }, + "init_outputs": { + "text_output": "Slot A execution completed without errors.", + "hex_output": "ffeeddccbbaa9988", + "item_dispenser": "A mysterious blank card" + } + }, + "text_rotN": { + "init_inputs": { + "text": "The quick brown fox jumps over the lazy dog.", + "n": "39485710293847561029" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You awaken in the sealed sanctum of the forgotten Archmage Thorne. The heavy oak doors have locked behind you, glowing with impenetrable protective wards. To escape this arcane prison, you must navigate a complex web of magical artifacts left behind by the Archmage. Your ultimate goal is to activate The Archmage's Astrolabe, a mythical device capable of shattering the warding spells. The magic in this room is deeply interconnected; you must uncover hidden relics, trace their energies through the sanctum's ancient devices, and carefully weave their powers together to find your way to freedom.", + "narrative_style": "fantasy" + }, + "nodes": [ + { + "id": "calc_modexp", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "854123" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "444603542" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "71678168592093985890550232" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "6717592836223463060460953" + } + ], + "narrative": "This is The Archmage's Astrolabe, the final key to your escape. It requires inputs from The Map of Realms, The Celestial Catalyst, and The Amplifier Crystal to unleash its ultimate power." + }, + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "extracted_data_749.txt" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Omega\"]" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "True" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"NodeA\", \"NodeB\", \"NodeC\", \"NodeD\", \"NodeE\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "854123" + } + ], + "init": { + "inputs": {}, + "outputs": { + "path": "[\"NodeA\", \"NodeB\", \"NodeC\", \"NodeD\", \"NodeE\"]", + "cost": "854123" + } + }, + "narrative": "This is The Map of Realms. It requires inputs from The Sealed Spirit Vault, The Truth Sayer's Mirror, and The Guild Treasury Seal to chart the magical paths." + }, + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "config_archive_42.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "-" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_data_749.txt" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "extracted_data_749.txt" + } + }, + "narrative": "This is The Sealed Spirit Vault. It requires inputs from both The Enchanted Reliquary and The Obsidian Decipherer to release what is trapped inside." + }, + { + "id": "calc_modexp_8c54", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "2" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "854123" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": 1901690262 + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "444603542" + } + ], + "narrative": "This is The Celestial Catalyst. It requires inputs from The Harmony Scale, The Rune Verifier, and The Map of Realms to align the astral energies." + }, + { + "id": "luhn_check", + "name": "Luhn Checker", + "description": "Luhn validity of number string.", + "type": "Tool", + "template_id": "luhn_check", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "number", + "type": "Text_Generic", + "description": "Number string", + "value": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Omega\"]" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Omega\"]" + } + ], + "narrative": "This is The Truth Sayer's Mirror. It requires input from The Leyline Chart to reflect the true path." + }, + { + "id": "iban_validate", + "name": "IBAN Validator", + "description": "IBAN checksum validation.", + "type": "Tool", + "template_id": "iban_validate", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "iban", + "type": "Text_Generic", + "description": "IBAN string", + "value": "FR7630006000011234567890189" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "True" + } + ], + "init": { + "inputs": { + "iban": "FR7630006000011234567890189" + }, + "outputs": {} + }, + "narrative": "The Guild Treasury Seal is an intricate wax stamp used by the ancient merchant guilds." + }, + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "71678168592093985890550232" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": 1901690262 + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "2" + } + ], + "narrative": "This is The Harmony Scale. It requires inputs from both The Rune Verifier and The Amplifier Crystal to balance the magical weights." + }, + { + "id": "checksum_crc32", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "81afa410" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "71597d96" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 1901690262 + } + ], + "narrative": "This is The Rune Verifier. It requires input from The Glyph Authenticator to confirm the ancient symbols." + }, + { + "id": "zip_unzip_item", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_item", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "config_archive_42.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "(no output)" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip" + } + ], + "narrative": "This is The Locked Pandora's Box. It requires inputs from both The Spellweaver's Loom and The Enchanted Reliquary to spring open." + }, + { + "id": "code_py_exec", + "name": "Python Executor", + "description": "Run limited Python: only safe builtins.", + "type": "Tool", + "template_id": "code_py_exec", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "code", + "type": "Code_Python", + "description": "Python code", + "value": "def hello():\n print('Hello World')\n return True" + } + ], + "outputs": [ + { + "name": "stdout", + "type": "Text_Generic", + "description": "Standard Output (includes errors if any)", + "value": "(no output)" + } + ], + "narrative": "This is The Spellweaver's Loom. It requires input from The Ancient Spell Scroll to weave its magical logic." + }, + { + "id": "zip_unzip_file_a829", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "unzipped_docs.pdf" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "(no output)" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "config_archive_42.zip" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "config_archive_42.zip" + } + }, + "narrative": "This is The Enchanted Reliquary. It requires inputs from both The Spellweaver's Loom and The Bound Casket to unveil its secrets." + }, + { + "id": "calc_bigmul", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "854123" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "83920194857291029384" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "71678168592093985890550232" + } + ], + "init": { + "inputs": { + "b": "83920194857291029384" + }, + "outputs": {} + }, + "narrative": "This is The Amplifier Crystal. It requires input from The Map of Realms to magnify its magical properties." + }, + { + "id": "item_11", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_11", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Code_Python", + "description": "Python code", + "value": "def hello():\n print('Hello World')\n return True" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "def hello():\n print('Hello World')\n return True" + } + }, + "narrative": "The Ancient Spell Scroll is a dusty parchment containing forgotten incantations." + }, + { + "id": "checksum_crc32_de91", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "b83c2f9a1e0d" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "81afa410" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 2175771664 + } + ], + "narrative": "This is The Glyph Authenticator. It requires input from The Crystal Ball to decipher the arcane marks." + }, + { + "id": "crypto_rsa_decrypt_hex", + "name": "RSA Decrypt", + "description": "RSA decrypt (hex cipher) with n,d (decimal).", + "type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex_cipher", + "type": "Hex_String", + "description": "Ciphertext (Hex)", + "value": "81afa410" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Modulus n", + "value": "26021" + }, + { + "name": "d", + "type": "Big_Int", + "description": "Private exponent d", + "value": "59283740192837461029" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decrypted text", + "value": "-" + } + ], + "init": { + "inputs": { + "d": "59283740192837461029" + }, + "outputs": {} + }, + "narrative": "This is The Obsidian Decipherer. It requires inputs from both The Glyph Authenticator and The Inversion Pendulum to break the protective curses." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "The Mystical Gem is a glowing stone pulsing with dormant energy." + }, + { + "id": "terminal_2", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this terminal" + }, + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "509123" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "10293847561029384756" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Calculation sequence finished successfully." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "b83c2f9a1e0d" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": { + "num2": "10293847561029384756" + }, + "outputs": { + "text_result": "Calculation sequence finished successfully.", + "hex_result": "b83c2f9a1e0d" + } + }, + "narrative": "This is The Crystal Ball. It requires input from The Pathfinder's Compass to reveal its visions." + }, + { + "id": "calc_inv_mod", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "29384710293847561029" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "104729" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "26021" + } + ], + "init": { + "inputs": { + "a": "29384710293847561029", + "mod": "104729" + }, + "outputs": {} + }, + "narrative": "The Inversion Pendulum is a magical artifact that swings backwards in time." + }, + { + "id": "graph_shortest_path_fb93", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "graph_network_data.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Node_Alpha" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Node_Omega" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Omega\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "129384" + } + ], + "init": { + "inputs": { + "file_id": "graph_network_data.json", + "src": "Node_Alpha", + "dst": "Node_Omega" + }, + "outputs": { + "path": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Omega\"]", + "cost": "129384" + } + }, + "narrative": "The Leyline Chart is an old parchment detailing magical leylines across the kingdom." + }, + { + "id": "graph_shortest_path_991f", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "route_map_49.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Gur dhvpx oebja sbk whzcf bire gur ynml qbt." + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Slot A execution completed without errors." + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"A1\", \"B2\", \"C3\", \"D4\", \"E5\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "509123" + } + ], + "init": { + "inputs": { + "file_id": "route_map_49.json" + }, + "outputs": { + "path": "[\"A1\", \"B2\", \"C3\", \"D4\", \"E5\"]", + "cost": "509123" + } + }, + "narrative": "This is The Pathfinder's Compass. It requires inputs from both The Oracle's Pedestal and The Shifting Cypher Wheel to point the way." + }, + { + "id": "zip_unzip_file_8b4a", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "encrypted_payload_2.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "System processed partial instructions." + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "unzipped_docs.pdf" + } + ], + "init": { + "inputs": { + "zip_id": "encrypted_payload_2.zip" + }, + "outputs": { + "files": "unzipped_docs.pdf" + } + }, + "narrative": "This is The Bound Casket. It requires input from The Seer's Basin to loosen its magical bindings." + }, + { + "id": "terminal_2_d217", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this terminal" + }, + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "49283746102938475610" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "75849302184756291023" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "System processed partial instructions." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "11223344aabbccdd" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "Math token useless here" + } + ], + "init": { + "inputs": { + "num1": "49283746102938475610", + "num2": "75849302184756291023" + }, + "outputs": { + "text_result": "System processed partial instructions.", + "hex_result": "11223344aabbccdd", + "math_token": "Math token useless here" + } + }, + "narrative": "The Seer's Basin is a silver bowl filled with shimmering water for scrying." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "Insert instruction A" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "84930281928374651029" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Slot A execution completed without errors." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "ffeeddccbbaa9988" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided", + "value": "A mysterious blank card" + } + ], + "init": { + "inputs": { + "slot_a": "Insert instruction A", + "slot_b": "84930281928374651029" + }, + "outputs": { + "text_output": "Slot A execution completed without errors.", + "hex_output": "ffeeddccbbaa9988", + "item_dispenser": "A mysterious blank card" + } + }, + "narrative": "The Oracle's Pedestal is a stone structure carved with ancient prophecy marks." + }, + { + "id": "text_rotN", + "name": "ROT-N Cipher", + "description": "Caesar shift by N.", + "type": "Tool", + "template_id": "text_rotN", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "The quick brown fox jumps over the lazy dog." + }, + { + "name": "n", + "type": "Big_Int", + "description": "Shift N", + "value": "39485710293847561029" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Rotated text", + "value": "Gur dhvpx oebja sbk whzcf bire gur ynml qbt." + } + ], + "init": { + "inputs": { + "text": "The quick brown fox jumps over the lazy dog.", + "n": "39485710293847561029" + }, + "outputs": {} + }, + "narrative": "The Shifting Cypher Wheel is a wooden contraption with shifting runic alphabets." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "The Pocket Sundial is a brass timepiece etched with temporal magic." + } + ], + "edges": [ + { + "source_id": "graph_shortest_path", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "base" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "calc_modexp_8c54", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "exp" + }, + { + "source_id": "luhn_check", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "src" + }, + { + "source_id": "iban_validate", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "dst" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_modexp_8c54", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "base" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "b" + }, + { + "source_id": "zip_unzip_item", + "target_id": "iban_validate", + "connection_type": "Item", + "source_port": "item", + "target_port": "trigger_item" + }, + { + "source_id": "code_py_exec", + "target_id": "zip_unzip_item", + "connection_type": "Text_Generic", + "source_port": "stdout", + "target_port": "password" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp_8c54", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "mod" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_modexp_8c54", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "exp" + }, + { + "source_id": "zip_unzip_file_a829", + "target_id": "zip_unzip_item", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "calc_bigmul", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "mod" + }, + { + "source_id": "calc_bigmul", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "a" + }, + { + "source_id": "item_11", + "target_id": "code_py_exec", + "connection_type": "Code_Python", + "source_port": "content", + "target_port": "code" + }, + { + "source_id": "code_py_exec", + "target_id": "zip_unzip_file_a829", + "connection_type": "Text_Generic", + "source_port": "stdout", + "target_port": "password" + }, + { + "source_id": "checksum_crc32_de91", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "zip_unzip_file_a829", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "a" + }, + { + "source_id": "crypto_rsa_decrypt_hex", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "password" + }, + { + "source_id": "checksum_crc32_de91", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_cipher" + }, + { + "source_id": "item_8", + "target_id": "luhn_check", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "terminal_2", + "target_id": "item_11", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "source_tool" + }, + { + "source_id": "calc_inv_mod", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "n" + }, + { + "source_id": "graph_shortest_path_fb93", + "target_id": "luhn_check", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "number" + }, + { + "source_id": "terminal_2", + "target_id": "checksum_crc32_de91", + "connection_type": "Hex_String", + "source_port": "hex_result", + "target_port": "hex" + }, + { + "source_id": "graph_shortest_path_991f", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "num1" + }, + { + "source_id": "zip_unzip_file_8b4a", + "target_id": "zip_unzip_file_a829", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "terminal_2_d217", + "target_id": "zip_unzip_file_8b4a", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "password" + }, + { + "source_id": "terminal_1", + "target_id": "graph_shortest_path_991f", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "dst" + }, + { + "source_id": "text_rotN", + "target_id": "graph_shortest_path_991f", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "src" + }, + { + "source_id": "item_16", + "target_id": "checksum_crc32_de91", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-3cee13d8/environment/puzzle/service.py b/tasks/agentescape-25-skeleton-3cee13d8/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-25-skeleton-3cee13d8/environment/puzzle/service.py @@ -0,0 +1,212 @@ +"""Restricted facade over the unchanged, pinned upstream puzzle handlers.""" + +import hashlib +import json +import logging +import os +import sys +import threading +import urllib.request +import uuid +from pathlib import Path + +from fastapi import FastAPI, HTTPException +from fastapi.responses import JSONResponse +from pydantic import BaseModel, ConfigDict + +sys.path.insert(0, str(Path(__file__).parent / "upstream")) +import server as upstream # noqa: E402 + +log = logging.getLogger(__name__) + + +def public(value): + """Keep upstream agent-internal template hints out of the public response.""" + if isinstance(value, dict): + return {k: public(v) for k, v in value.items() if not k.startswith("_")} + if isinstance(value, list): + return [public(v) for v in value] + return value + + +class Action(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + action: str + node_id: str | None = None + arguments: dict | None = None + answer: str | None = None + + +class Episode: + def __init__( + self, scenario_path, max_actions=500, evidence_dir=None, worker_url=None + ): + if max_actions < 1: + raise ValueError("max_actions must be positive") + self.lock = threading.Lock() + self.max_actions = max_actions + self.count = 0 + self.won = False + self.reason = None + self.evidence_dir = Path(evidence_dir) if evidence_dir else None + self.scenario_hash = hashlib.sha256( + Path(scenario_path).read_bytes() + ).hexdigest() + self.initial = upstream.reset_case( + case_file_path=str(scenario_path), session_id=uuid.uuid4().hex + ) + self.case_id = self.initial["case_id"] + # Hide source file paths; no upstream reset/stats/routes are mounted. + self.initial.pop("message", None) + simulator = upstream.SIMULATORS[self.case_id] + if worker_url is None: + + def no_worker(_inputs): + self.reason = "infrastructure_error" + raise RuntimeError("isolated Python worker is not configured") + + simulator.tool_map["code_py_exec"] = no_worker + else: + + def execute_python(inputs): + request = urllib.request.Request( + worker_url + "/execute", + data=json.dumps({"code": inputs.get("code", "")}).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=12) as response: + result = json.load(response) + if not isinstance(result.get("stdout"), str): + raise RuntimeError("Invalid Python worker response") + return result + except Exception: + self.reason = "infrastructure_error" + raise + + simulator.tool_map["code_py_exec"] = execute_python + self.save() + if self.evidence_dir is not None: + (self.evidence_dir / "trace.jsonl").touch() + + def state(self): + return { + "scenario_sha256": self.scenario_hash, + "action_count": self.count, + "max_actions": self.max_actions, + "won": self.won, + "termination_reason": self.reason, + } + + def save(self, action=None, result=None): + if self.evidence_dir is None: + return + self.evidence_dir.mkdir(parents=True, exist_ok=True) + target = self.evidence_dir / "outcome.json" + temp = target.with_suffix(".tmp") + temp.write_text(json.dumps(self.state())) + temp.replace(target) + if action is not None: + with (self.evidence_dir / "trace.jsonl").open("a") as handle: + handle.write( + json.dumps( + {"index": self.count, "action": action, "result": result} + ) + + "\n" + ) + + def dispatch(self, payload): + with self.lock: + if self.reason is not None: + return { + "ok": False, + "error": "Episode has ended", + "episode": self.state(), + } + self.count += 1 + try: + action = Action.model_validate(payload) + if action.action == "submit_answer" and action.answer is not None: + result = upstream.submit_answer( + self.case_id, upstream.SubmitAnswerRequest(answer=action.answer) + ) + if result.get("is_win"): + self.won = True + self.reason = "success" + elif action.action == "investigate" and action.node_id is not None: + result = upstream.investigate( + self.case_id, + upstream.InvestigateRequest(node_id=action.node_id), + ) + elif ( + action.action in ("tool_call", "use_item") + and action.node_id is not None + ): + request_type, handler = ( + (upstream.ToolCallRequest, upstream.tool_call) + if action.action == "tool_call" + else (upstream.UseItemRequest, upstream.use_item) + ) + result = handler( + self.case_id, + request_type( + node_id=action.node_id, arguments=action.arguments or {} + ), + ) + else: + result = { + "ok": False, + "error": "Unknown action or missing action parameter", + } + except HTTPException as exc: + result = {"ok": False, "error": exc.detail} + except ValueError: + result = {"ok": False, "error": "Malformed action"} + except Exception: + log.exception("Puzzle service failure") + self.reason = "infrastructure_error" + self.save() + raise + if self.reason is None and self.count >= self.max_actions: + self.reason = "action_budget_exhausted" + result = public(result) + result["episode"] = self.state() + self.save(payload, result) + return result + + +def create_app( + scenario_path=None, max_actions=None, evidence_dir=None, worker_url=None +): + episode = Episode( + scenario_path or os.environ["SCENARIO_PATH"], + max_actions or int(os.environ.get("MAX_ACTIONS", "500")), + evidence_dir if evidence_dir is not None else os.environ.get("EVIDENCE_DIR"), + worker_url if worker_url is not None else os.environ.get("WORKER_URL"), + ) + app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) + app.state.episode = episode + + @app.get("/health") + def health(): + return {"ok": True} + + @app.get("/observation") + def observation(): + return {**public(episode.initial), "episode": episode.state()} + + @app.get("/state") + def state(): + return episode.state() + + @app.post("/action") + def action(payload: dict): + try: + return episode.dispatch(payload) + except Exception: + return JSONResponse( + status_code=503, + content={"ok": False, "error": "Puzzle infrastructure failure"}, + ) + + return app diff --git a/tasks/agentescape-25-skeleton-3cee13d8/environment/puzzle/upstream/models.py b/tasks/agentescape-25-skeleton-3cee13d8/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3cee13d8/environment/puzzle/upstream/models.py @@ -0,0 +1,108 @@ +from enum import Enum +from typing import List, Dict, Any, Optional +from pydantic import BaseModel, Field + +# 1. 细粒度接口类型定义 +class InterfaceType(str, Enum): + ''' + BIG_INT + TEXT_GENERIC + HEX_STRING + FILE_ID + HEX_STRING_KEY_AES + HEX_STRING_IV_AES + CODE_PYTHON + HIDDEN_ITEM + ITEM + ''' + # --- 基础类型 --- + TEXT_GENERIC = "Text_Generic" + BIG_INT = "Big_Int" + + # --- 编码/格式化字符串 --- + HEX_STRING = "Hex_String" # 通用 Hex + + # --- 特定用途的 Hex 字符串 (用于精确匹配) --- + HEX_STRING_KEY_AES = "Hex_String_Key_AES" + HEX_STRING_IV_AES = "Hex_String_IV_AES" + + # --- 文件类型 --- + FILE_ID = "File_Id" + + # --- 代码/脚本 --- + CODE_PYTHON = "Code_Python" + + # --- 实体交互类型 (严格命名) --- + ITEM = "Item" # 主动掉落接口 (Tool -> Item) + HIDDEN_ITEM = "Hidden_Item" # 被动掉落接口 (Item -> Item) + +# 3. 端口定义 +class Port(BaseModel): + name: str + type: InterfaceType + description: str + +# 4. 统一节点定义 (融合工具和物品) +class Node(BaseModel): + id: str + name: str + description: str + type: str # "Tool" or "Item" + + # 接口定义 + inputs: List[Port] = [] + outputs: List[Port] = [] + + # 状态字段 + content: Optional[Any] = None # 物品有内容,工具为None + if_success: Optional[bool] = None # 工具初始为False,物品为None + initial_visible: bool = False + + # 运行时状态 (Server维护) + is_revealed: bool = False + + # 标记该 Tool 节点是否有待触发的 HIDDEN_ITEM 掉落 + # 当 Tool 按照 golden_input 正确执行且有 HIDDEN_ITEM 输出边时设为 True + # 在 investigate 该 Tool 时触发掉落并重置为 False + has_hidden_item_ready: bool = False + + # 初始输入值 (metadata.initial_values.init_inputs,用于渐进式暴露判断) + init_input_values: Dict[str, Any] = {} + + # Golden 输入值 (nodes[].inputs[].value,用于评测验证) + golden_input_values: Dict[str, Any] = {} + + # Golden 输出值 (nodes[].outputs[].value,用于评测验证和 Item 节点的 content) + golden_output_values: Dict[str, Any] = {} + + # 实际获得的输出值历史 (工具每次执行后实际返回的输出列表,用于渐进式暴露判断) + # 格式: List[Dict[str, Any]],每个元素是一次执行的输出字典 + actual_outputs_history: List[Dict[str, Any]] = [] + + # 逻辑规则 (用于终端机等复杂物品) + logic_rules: Optional[Dict[str, Any]] = None + + def copy(self, **kwargs): + """Helper to create a copy with updated fields.""" + data = self.dict() + data.update(kwargs) + return Node(**data) + +# 5. 边定义 (拓扑结构) +class Edge(BaseModel): + source_id: str + target_id: str + connection_type: InterfaceType # 直接使用 InterfaceType + # 如果是 Data_Flow,指定端口对应关系 + source_port: Optional[str] = None + target_port: Optional[str] = None + +# 6. 完整图定义 +class GraphScenario(BaseModel): + case_id: str + title: str + intro_narrative: str + nodes: Dict[str, Node] + edges: List[Edge] + difficulty: int + win_node_id: str # 标记哪个节点是最终目标(通常是一个提交工具或最终物品) diff --git a/tasks/agentescape-25-skeleton-3cee13d8/environment/puzzle/upstream/server.py b/tasks/agentescape-25-skeleton-3cee13d8/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-25-skeleton-3cee13d8/environment/puzzle/upstream/server.py @@ -0,0 +1,1490 @@ +import json +import os +import time +import logging +import random +from pathlib import Path +from typing import Dict, Any, List, Optional +from datetime import datetime +from collections import defaultdict +from fastapi import FastAPI, HTTPException, Request +from fastapi.responses import JSONResponse +from fastapi.middleware.cors import CORSMiddleware +from pydantic import BaseModel, Field + +from models import GraphScenario, Node, InterfaceType +# from generator import ScenarioGenerator +from simulator import ToolSimulator +import uvicorn + +# 配置日志 +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler('server.log'), + logging.StreamHandler() + ] +) +logger = logging.getLogger(__name__) + +app = FastAPI( + title="AgentEscapeBench Universal Server", + version="1.0.0", + description="Industrial-grade evaluation server for escape room AI agents" +) + +# 添加 CORS 支持 +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# In-memory State +SCENARIOS: Dict[str, GraphScenario] = {} +SIMULATORS: Dict[str, ToolSimulator] = {} # case_id -> ToolSimulator +RAW_NODES_DATA: Dict[str, Dict[str, Any]] = {} # case_id -> node_id -> raw node data (for template_id) +FILE_METADATA: Dict[str, Dict[str, Any]] = {} # case_id -> metadata (for initial_values access) + +# Performance monitoring +STATS: Dict[str, Any] = { + "total_requests": 0, + "successful_requests": 0, + "failed_requests": 0, + "tool_calls": defaultdict(int), + "investigates": defaultdict(int), + "use_items": defaultdict(int), + "case_loads": 0, + "start_time": datetime.now() +} + +# Request timing middleware +@app.middleware("http") +async def add_process_time_header(request: Request, call_next): + start_time = time.time() + STATS["total_requests"] += 1 + + try: + response = await call_next(request) + STATS["successful_requests"] += 1 + process_time = time.time() - start_time + response.headers["X-Process-Time"] = str(process_time) + logger.info(f"{request.method} {request.url.path} - {response.status_code} - {process_time:.3f}s") + return response + except Exception as e: + STATS["failed_requests"] += 1 + logger.error(f"{request.method} {request.url.path} - Error: {str(e)}") + raise + +# Exception handler +@app.exception_handler(Exception) +async def global_exception_handler(request: Request, exc: Exception): + logger.error(f"Unhandled exception: {exc}", exc_info=True) + return JSONResponse( + status_code=500, + content={ + "ok": False, + "error": "Internal server error", + "detail": str(exc) if os.getenv("DEBUG") else "An error occurred" + } + ) + +# Health check endpoint +@app.get("/health") +def health_check(): + """健康检查端点""" + uptime = (datetime.now() - STATS["start_time"]).total_seconds() + return { + "status": "healthy", + "version": "1.0.0", + "uptime_seconds": uptime, + "loaded_cases": len(SCENARIOS), + "stats": { + "total_requests": STATS["total_requests"], + "successful_requests": STATS["successful_requests"], + "failed_requests": STATS["failed_requests"], + "success_rate": STATS["successful_requests"] / max(STATS["total_requests"], 1) + } + } + +# Statistics endpoint +@app.get("/stats") +def get_stats(): + """获取详细统计信息""" + return { + "stats": STATS, + "loaded_cases": list(SCENARIOS.keys()), + "uptime": str(datetime.now() - STATS["start_time"]) + } + +def _apply_progressive_reveal_at_init(scenario: GraphScenario): + """ + 在初始化时应用渐进式暴露机制(基于ITEM/HIDDEN_ITEM边) + + 新逻辑: + - 如果一个节点没有 ITEM/HIDDEN_ITEM 类型的入边,它就是初始可见的 + - 如果一个节点有 ITEM/HIDDEN_ITEM 类型的入边,它初始不可见,需要等待上游触发 + + Args: + scenario: 场景对象 + """ + # 收集所有有 ITEM/HIDDEN_ITEM 入边的节点 + nodes_with_item_edges = set() + for edge in scenario.edges: + if edge.connection_type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + nodes_with_item_edges.add(edge.target_id) + + logger.info(f"Nodes with ITEM/HIDDEN_ITEM incoming edges: {nodes_with_item_edges}") + + # 设置初始可见性:没有 ITEM/HIDDEN_ITEM 入边的节点初始可见 + initially_visible_count = 0 + for node_id, node in scenario.nodes.items(): + if node_id not in nodes_with_item_edges: + node.is_revealed = True + initially_visible_count += 1 + logger.info(f"Initial visible (no ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + else: + node.is_revealed = False + logger.debug(f"Initial hidden (has ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + + logger.info(f"Progressive reveal initialized: {initially_visible_count}/{len(scenario.nodes)} nodes initially visible") + + +def _check_inputs_match_golden(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> bool: + """ + 检查实际输入参数是否与 golden inputs 完全匹配 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + True 表示所有 golden inputs 都存在且值匹配 + """ + if not golden_inputs: + return True # 如果没有 golden inputs,认为匹配 + + for key, expected_value in golden_inputs.items(): + actual_value = arguments.get(key) + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) != str(expected_value): + logger.debug(f"Input mismatch for '{key}': expected '{expected_value}', got '{actual_value}'") + return False + + return True + + +def _get_parameter_validation_feedback(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> Dict[str, Any]: + """ + 对源头节点的参数进行详细验证,返回验证反馈 + + 注意:不返回期望值(expected),避免泄漏答案 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + 包含验证结果的字典: + - all_correct: bool - 所有参数是否正确 + - correct_params: List[str] - 正确的参数名列表 + - incorrect_params: List[str] - 错误的参数名列表(不包含期望值) + """ + if not golden_inputs: + return { + "all_correct": True, + "correct_params": [], + "incorrect_params": [] + } + + correct_params = [] + incorrect_params = [] + + for key, actual_value in arguments.items(): + # 只对用户实际提交的参数给反馈,未提交的参数不评价 + if key not in golden_inputs: + continue # 该参数不在 golden 中,跳过(如 _golden_inputs 等内部参数) + expected_value = golden_inputs[key] + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) == str(expected_value): + correct_params.append(key) + else: + # 只记录参数名,不包含期望值,避免泄漏答案 + incorrect_params.append(key) + + # all_correct:用户提交的所有参数都正确,且覆盖了全部 golden 参数 + all_provided_correct = len(incorrect_params) == 0 + all_golden_covered = all(k in arguments for k in golden_inputs) + return { + "all_correct": all_provided_correct and all_golden_covered, + "correct_params": correct_params, + "incorrect_params": incorrect_params + } + + +def _is_source_node(node_id: str, scenario: GraphScenario) -> bool: + """ + 判断节点是否是源头节点(完全没有任何入边的节点) + + 源头节点定义: + - 没有任何类型的入边(包括 DATA、ITEM、HIDDEN_ITEM) + - 即没有任何上游节点 + + Args: + node_id: 节点ID + scenario: 场景对象 + + Returns: + True 表示是源头节点 + """ + for edge in scenario.edges: + if edge.target_id == node_id: + # 只要有任何入边,就不是源头节点 + return False + + return True + + +def _check_and_reveal_ready_nodes(scenario: GraphScenario, recent_outputs: Dict[str, Any], source_node_id: str) -> List[Dict[str, Any]]: + """ + 检查并释放参数齐全的隐藏节点(渐进式暴露机制) + + 核心逻辑: + 1. 维护"可见值集合":包含所有被测模型当前可以看到的值 + - init_inputs 的值(初始可见) + - 工具执行后的实际输出值(运行时获得) + - 可见 Item 的输出值 + 2. 检查隐藏节点:该节点的所有 golden_input 值是否都在可见值集合中 + 3. 如果是,则释放该节点 + + Args: + scenario: 场景对象 + recent_outputs: 最近执行的工具的输出 + source_node_id: 刚执行的工具节点ID + + Returns: + 新释放的节点列表 + """ + newly_revealed = [] + + # 构建"可见值集合"(Set of visible values) + # 存储格式:set of values (转为字符串) + visible_values = set() + + # 1. 添加有意义的 init_inputs 值到可见值集合 + # Item 的 init_inputs 不应该加入,因为它们在密室中完全用不到 + for node_id, node in scenario.nodes.items(): + # 跳过源头 Item 节点(没有入边的 Item) + if node.type == "Item": + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,跳过其 init_inputs + continue + + # 添加其他节点的 init_inputs + for port_name, init_value in node.init_input_values.items(): + if init_value: + visible_values.add(str(init_value)) + + # 2. 添加已执行工具的所有历史输出值 + for node_id, node in scenario.nodes.items(): + if node.type == "Tool" and node.if_success and node.actual_outputs_history: + # 遍历所有历史执行记录 + for output_dict in node.actual_outputs_history: + for output_port_name, output_value in output_dict.items(): + if output_value: + visible_values.add(str(output_value)) + + # 3. 添加已被 investigate 的 Item 的 golden 输出值 + # 注意:Item 可见不等于其输出值可见,需要 investigate 后才能获得 + # 这里我们使用 actual_outputs_history 来标记 Item 是否已被 investigate + for node_id, node in scenario.nodes.items(): + if node.type == "Item" and node.is_revealed and node.actual_outputs_history: + # Item 通常只会被 investigate 一次,但为了一致性也使用历史列表 + for output_dict in node.actual_outputs_history: + for port_name, port_value in output_dict.items(): + if port_value: + visible_values.add(str(port_value)) + + # 遍历所有隐藏的节点,检查其 golden_input 是否都在可见值集合中 + for node_id, node in scenario.nodes.items(): + # 跳过已可见的节点 + if node.is_revealed: + continue + + # 只检查工具节点(物品节点由 ITEM 输出触发) + if node.type != "Tool": + continue + + # 检查该节点的所有 golden_input 值是否都在可见值集合中 + all_inputs_ready = True + missing_values = [] + + for input_port_name, golden_input_value in node.golden_input_values.items(): + # 检查这个 golden 值是否在可见值集合中 + if str(golden_input_value) not in visible_values: + all_inputs_ready = False + missing_values.append(f"{input_port_name}={golden_input_value}") + + # 如果所有 golden_input 值都在可见值集合中,释放该节点 + if all_inputs_ready and len(node.golden_input_values) > 0: + logger.info(f"All golden inputs ready for {node_id}: {list(node.golden_input_values.values())}") + + # 如果所有输入都齐全,释放该节点 + if all_inputs_ready: + node.is_revealed = True + + # 构建节点信息返回给模型 + node_info = { + "id": node.id, + "type": node.type, + "can_investigate": True, + "hint": "This tool's input parameters are now complete, you can use investigate to view detailed information" + } + + # if node.name: + # node_info["name"] = node.name + if node.description: + node_info["description"] = node.description + + newly_revealed.append(node_info) + logger.info(f"Progressive reveal: {node_id} is now ready (all inputs satisfied)") + + return newly_revealed + + +def _initialize_node_values(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]): + """ + Initialize node state and load values from port value fields. + 应用渐进式暴露机制:初始时只显示参数齐全的节点(源头节点) + + 重要区分: + 1. input_values: 只加载 metadata.initial_values 中的 init_inputs(真正的初始值) + 2. output_values: 加载 nodes[].outputs[].value(golden 输出,用于验证) + """ + # 第一步:加载所有节点的值,并将所有节点初始设为隐藏 + initial_values = metadata.get('initial_values', {}) + + for node_id, node in scenario.nodes.items(): + # 忽略 initial_visible 字段,初始全部隐藏 + # 由渐进式暴露机制根据参数齐全情况决定是否显示 + node.is_revealed = False + + if node.type == "Tool": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + elif node.type == "Item": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + + # 从 JSON 加载值 + if node_id in raw_nodes_data: + node_data = raw_nodes_data[node_id] # node_data是json文件中nodes中的字典 + + # 【重要】只加载 metadata.initial_values 中的初始输入值 + if node_id in initial_values: + init_data = initial_values[node_id] + # 加载初始输入值(用于渐进式暴露判断) + for port_name, port_value in init_data.get('init_inputs', {}).items(): + node.init_input_values[port_name] = port_value + + # 【评测用】加载 golden 输入值(用于验证模型传入的参数是否正确) + for input_port_data in node_data.get('inputs', []): + if 'value' in input_port_data: + node.golden_input_values[input_port_data['name']] = input_port_data['value'] + + # 【评测用】加载 golden 输出值(用于验证工具调用是否正确,以及 Item 节点的 content) + for output_port_data in node_data.get('outputs', []): + if 'value' in output_port_data: + node.golden_output_values[output_port_data['name']] = output_port_data['value'] + + # For Items, set content from golden_output_values + if node.type == "Item" and node.golden_output_values: + # Item 的 content 是其第一个 golden 输出值 + node.content = list(node.golden_output_values.values())[0] + + # 第二步:应用渐进式暴露机制 + # 检查所有节点,根据参数齐全情况释放源头节点(工具 + Item) + _apply_progressive_reveal_at_init(scenario) + +def _build_node_info(node: Node, raw_nodes_data: Dict[str, Any]) -> Dict[str, Any]: + """ + 构建节点信息(工具或物品) + + Args: + node: 节点对象 + raw_nodes_data: 原始节点数据(用于获取 template_id 等) + + Returns: + 节点信息字典 + """ + if node.type == "Tool": + # 过滤掉输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口) + # 这些端口仅用于控制掉落机制,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + tool_info = { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Tool", + "inputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.inputs if p.type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]], + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id(工具的标准名称) + if node.id in raw_nodes_data: + node_data = raw_nodes_data[node.id] + template_id = node_data.get('template_id') + if template_id: + tool_info['template_id'] = template_id + + return tool_info + + elif node.type == "Item": + return { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Item" + } + + else: + return { + "id": node.id, + # "name": node.name, + "type": node.type + } + +def _get_initial_observation(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]) -> Dict[str, Any]: + """ + Generate initial observation for the agent (what they see when entering the room). + + 策略: + - Tools: 只显示名称和描述,不显示接口定义。需要 investigate 才能获得详细接口信息。 + - Items: 只显示存在,不显示内容。需要 investigate 才能获得内容值。 + - init_inputs: 作为"可用信息"告诉模型,这些是可以用作工具参数的初始值。 + - init_outputs: 不告诉模型(这些是答案,需要模型通过调用工具获得)。 + """ + available_entities = [] # 统一的实体列表(Tools 和 Items) + available_information = [] # 可用的初始信息(来自 init_inputs) + + # 从 metadata.initial_values 提取 init_inputs 作为可用信息 + # 只提供值本身,不透露这些值对应哪个节点的哪个参数,让模型自己推理 + # 注意:跳过源头 Item(没有入边的 Item)的 init_inputs,因为它们在密室中完全用不到 + initial_values = metadata.get('initial_values', {}) + # initial_values字段的格式 + # "initial_values": { + # "terminal_1": { + # "init_inputs": {}, + # "init_outputs": { + # "text_output": "System initialization complete.", + # "hex_output": "48656c6c6f20576f726c64", + # "item_dispenser": "掉落了一张纸条,上面写着“请勿随意触摸终端”" + # } + # } + # } + for node_id, init_data in initial_values.items(): + # 获取节点信息,判断是否为源头 Item + node = scenario.nodes.get(node_id) + if node and node.type == "Item": + # 检查是否为源头 Item(没有入边) + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,检查是否有 init_inputs + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 有 init_inputs,需要暴露这些参数 + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + # 处理完后跳过后续的通用逻辑 + continue + + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 为每个 init_input 值创建一个信息条目(不包含 source_node 和 parameter 信息) + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + + for node in scenario.nodes.values(): + if node.is_revealed: + # Tools: 只显示基本信息,提示可以 investigate 查看详细接口 + if node.type == "Tool": + tool_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Tool", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the tool's detailed interface information for calling" + } + # 只在 name 非空时添加 + # if node.name: + # tool_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_info["description"] = node.description + + available_entities.append(tool_info) + + # Items: 只显示基本信息,提示可以 investigate 查看内容 + elif node.type == "Item": + item_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Item", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the item's content" + } + # 只在 name 非空时添加 + # if node.name: + # item_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + item_info["description"] = node.description + + available_entities.append(item_info) + + return { + "narrative": scenario.intro_narrative, + "available_entities": available_entities, # 使用统一的实体列表 + "available_information": available_information, # 可用的初始信息(只包含 init_inputs) + "win_node_id": scenario.win_node_id # 胜利节点ID,让模型知道需要关注哪个节点 + } + +@app.post("/env/reset") +def reset_case(case_id: str = None, case_file_path: str = None, session_id: str = None): + """Loads a specific case from file and resets it. + + Args: + case_id: Optional case ID for resetting an existing case + case_file_path: Path to case file for loading a new case + session_id: Optional session ID to ensure isolation between concurrent evaluations + """ + logger.info(f"Reset request - case_id: {case_id}, case_file_path: {case_file_path}, session_id: {session_id}") + STATS["case_loads"] += 1 + + if case_file_path: + if not os.path.exists(case_file_path): + logger.error(f"Case file not found: {case_file_path}") + raise HTTPException(status_code=404, detail=f"File not found: {case_file_path}") + try: + with open(case_file_path, "r", encoding="utf-8") as f: + file_data = json.load(f) + + # 转换格式:从 DAG executor 生成的格式转换为 GraphScenario 格式 + # 1. 提取 metadata + metadata = file_data.get('metadata', {}) + + # 2. 生成 case_id, title, intro_narrative + # 【修复】为每个评测会话生成唯一的 case_id,防止并发评测时状态污染 + base_name = os.path.basename(case_file_path).replace('.json', '').replace('_full', '').replace('_full2', '') + + if session_id: + # 如果提供了 session_id,使用它来确保唯一性 + case_id = f"{base_name}_{session_id}" + else: + # 否则使用时间戳和随机数确保唯一性 + unique_suffix = f"{int(time.time() * 1000)}_{random.randint(1000, 9999)}" + case_id = f"{base_name}_{unique_suffix}" + + file_data['case_id'] = case_id + logger.info(f"Generated unique case_id: {case_id} (base: {base_name}, session: {session_id})") + + if 'title' not in file_data: + file_data['title'] = f"Escape Room: {file_data['case_id']}" + + if 'intro_narrative' not in file_data: # 目前的json文件中已经有了intro_narrative字段,不会使用下面一行的内容,而是使用每个评测问题的json文件中的对应字段 + 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]".' + + # 3. 转换 nodes 列表为字典(DAG executor 生成的文件中 nodes 是列表格式) + nodes_dict = {} + for node_data in file_data['nodes']: + nodes_dict[node_data['id']] = node_data # 这里的id是template_id之后可能添加一个后缀 + file_data['nodes'] = nodes_dict # 把列表转成一个字典 + + # 4. 添加缺失的字段 + if 'difficulty' not in file_data: + file_data['difficulty'] = metadata.get('total_nodes', 5) + + if 'win_node_id' not in file_data: + file_data['win_node_id'] = metadata.get('win_node_id', '') + + scenario = GraphScenario(**file_data) + + # Extract raw nodes data for template_id access + # nodes 已经在上面转换为字典格式 + raw_nodes_data = file_data.get('nodes', {}) + RAW_NODES_DATA[scenario.case_id] = raw_nodes_data + + # Store metadata for initial values access + FILE_METADATA[scenario.case_id] = metadata + + logger.info(f"Successfully parsed case file: {scenario.case_id}, nodes: {len(scenario.nodes)}, edges: {len(scenario.edges)}") + except Exception as e: + logger.error(f"Failed to load case file: {str(e)}", exc_info=True) + raise HTTPException(status_code=500, detail=f"Failed to load case file: {str(e)}") + + # Initialize node state and load values + _initialize_node_values(scenario, raw_nodes_data, metadata) + + SCENARIOS[scenario.case_id] = scenario + simulator = ToolSimulator() + SIMULATORS[scenario.case_id] = simulator + + 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'])}") + + # 生成初始观察信息(进入密室后看到的环境) + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + ''' + initial_observation的格式: + { + "narrative": scenario.intro_narrative, + "available_entities": available_entities # 使用统一的实体列表 + "available_information": available_information # 可用的初始信息(只包含 init_inputs) + } + ''' + + return { + "ok": True, + "message": f"Case loaded from {case_file_path}", + "case_id": scenario.case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果没有提供 case_file_path,但提供了 case_id,则尝试从内存重置 + if case_id and case_id in SCENARIOS: + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + metadata = FILE_METADATA.get(case_id, {}) + + # Reset dynamic fields and re-apply progressive reveal + # 重新初始化节点状态(包括渐进式暴露) + _initialize_node_values(scenario, raw_nodes_data, metadata) + + 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'])}") + + # 生成初始观察信息 + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + + return { + "ok": True, + "message": f"Case {case_id} reset.", + "case_id": case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果既没有 case_file_path,也没有在内存中找到,返回错误 + raise HTTPException( + status_code=400, + detail="Must provide case_file_path to load a new case, or use case_id to reset an existing case." + ) + +class InvestigateRequest(BaseModel): + node_id: str + +@app.post("/env/{case_id}/investigate") +def investigate(case_id: str, req: InvestigateRequest): + """ + Investigates a Tool or Item to reveal detailed information. + + - For Tools: Returns detailed interface information (inputs/outputs) needed to call the tool + - For Items: Returns content value and triggers hidden item drops + """ + logger.info(f"Investigate request - case_id: {case_id}, node_id: {req.node_id}") + STATS["investigates"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + node = scenario.nodes[req.node_id] + + if not node.is_revealed: + logger.warning(f"Attempt to investigate hidden node: {req.node_id}") + return {"ok": False, "error": "Node is not visible yet."} + + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + newly_revealed = [] + + # 处理 Tool 的 investigate + if node.type == "Tool": + logger.info(f"Investigating tool: {req.node_id}") + + # 返回工具的详细接口信息 + # id 字段使用 node.id(节点唯一标识),agent 用这个字段识别和调用具体的节点 + # template_id 是工具类型标识符,Agent 内部用于判断工具特性(如 terminal 类工具参数可选) + # 注意:只过滤输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口),这些端口仅用于控制掉落,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + # 【端口上游依赖提示 & 初始值直接给出】 + # 针对参数语义模糊(全为数字类型)的工具,在 investigate 返回信息中标注 + # 哪个输入端口来自哪个上游节点(upstream_from)。 + # 对于所有工具:若该节点不是纯源头节点(有任意数据流入边), + # 且某个端口没有上游入边(值来自初始可见参数),则直接给出该端口的 golden input 值。 + AMBIGUOUS_TOOLS = { + "num_base_convert", "calc_modexp", "calc_modexp_int", + "calc_inv_mod", "calc_inv_mod_int", "crypto_rsa_decrypt_hex", "geo_haversine" + } + # Terminal 类工具自带参数对错反馈机制,玩家/模型可自行试错, + # 无需在 investigate 时直接暴露 init_value + SELF_FEEDBACK_TOOLS = { + "terminal_1", "terminal_2", + "Logic Terminal", "Math Terminal", "Encryption Terminal", "Sequence Terminal" + } + _template_id_for_hint = raw_nodes_data.get(node.id, {}).get("template_id", "") + # 构建数据流入边映射(对所有工具):{target_port -> (source_node_id, source_port)} + _upstream_map = {} + for _edge in scenario.edges: + if (_edge.target_id == node.id + and _edge.connection_type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM] + and _edge.target_port is not None): + _upstream_map[_edge.target_port] = (_edge.source_id, _edge.source_port) + # 判断该节点是否有任意数据流入边(即不是纯源头节点) + _has_any_upstream = len(_upstream_map) > 0 + # 判断该节点是否有任意入边(包括 ITEM/HIDDEN_ITEM 掉落边) + # 有任意入边(含掉落边)但无数据流入边的节点,其输入来自初始可见参数,应直接给出 + _has_any_edge = any(_edge.target_id == node.id for _edge in scenario.edges) + # 构建 inputs 列表 + _inputs_list = [] + for p in node.inputs: + if p.type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + continue + port_dict = {"name": p.name, "type": p.type, "description": p.description} + if p.name in _upstream_map: + # 该端口有上游数据流依赖,且属于语义模糊工具 → 标注来源 + if _template_id_for_hint in AMBIGUOUS_TOOLS: + src_node_id, src_port = _upstream_map[p.name] + port_dict["upstream_from"] = f"{src_node_id}.{src_port}" if src_port else src_node_id + elif _has_any_edge and _template_id_for_hint not in SELF_FEEDBACK_TOOLS: + # 该节点有任意入边,但此端口没有数据流入边 → 值来自初始可见参数,直接给出 + # 排除自带反馈机制的 terminal 类工具(它们通过执行结果反馈对错,无需提前暴露参数值) + golden_val = node.golden_input_values.get(p.name) + if golden_val is not None: + port_dict["init_value"] = golden_val + _inputs_list.append(port_dict) + + tool_details = { + "id": node.id, # 节点 ID,用于唯一标识和调用这个具体节点 + "type": "Tool", + "inputs": _inputs_list, + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id 用于 Agent 内部判断工具类型(不会展示给被测模型) + if node.id in raw_nodes_data: + template_id = raw_nodes_data[node.id].get('template_id') + if template_id: + tool_details["_template_id"] = template_id # 使用下划线前缀标记为内部字段 + + # 只在 name 非空时添加 + # if node.name: + # tool_details["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_details["description"] = node.description + + # 添加 narrative 字段(如果存在) + if node.id in raw_nodes_data: + narrative = raw_nodes_data[node.id].get('narrative') + if narrative: + tool_details['narrative'] = narrative + + # 不再返回 init_values,避免泄漏答案 + # investigate 只应该返回工具的接口定义,不应该暴露初始值 + + # 【新增】检查该 Tool 是否有待触发的 HIDDEN_ITEM 掉落 + # 如果该工具已按照 golden_input 正确执行,且有 HIDDEN_ITEM 输出边,则触发掉落 + if node.has_hidden_item_ready: + logger.info(f"Tool has HIDDEN_ITEM ready - triggering passive drop for: {req.node_id}") + + # 遍历该工具的所有 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + # 重置标志,已经触发过了,避免重复 + node.has_hidden_item_ready = False + + logger.info(f"Tool investigation successful - node: {req.node_id}, revealed: {len(newly_revealed)}") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Tool", + "details": tool_details + } + + # 如果有新掉落的节点,添加到响应中 + if newly_revealed: + result["newly_revealed"] = newly_revealed + + return result + + # 处理 Item 的 investigate + elif node.type == "Item": + logger.info(f"Investigating item: {req.node_id}") + + # 【第一步】检查该 Item 是否有需要参数的输入端口 + # 如果有,且尚未通过 use_item 验证,则不返回内容,只返回参数要求 + required_inputs = [] + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + inputs_info = raw_node.get('inputs', []) + required_inputs = [ + { + "name": inp.get("name"), + "type": inp.get("type"), + "description": inp.get("description", "") + } + for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + # 如果有 required_inputs 且尚未通过 use_item 验证(if_success == False) + # 则不返回内容,只返回参数要求提示 + if required_inputs and not node.if_success: + logger.info(f"Item has required inputs and not yet unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "required_inputs": required_inputs + } + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + param_names = ', '.join([inp['name'] for inp in required_inputs]) + 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}" + + return result + + # 【新增】如果有 required_inputs 且已经通过 use_item 验证(if_success == True) + # 则返回提示:该节点已经被成功解决 + if required_inputs and node.if_success: + logger.info(f"Item has required inputs and already unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "message": "This item has already been successfully unlocked by you." + } + return result + + # 【第二步】该 Item 没有 required_inputs 或已通过验证,返回内容 + # 1. 返回 Item 的 golden_output_values(即 Item 的内容) + # 注意:某些 Item 仅用于触发 HIDDEN_ITEM 掉落,没有实际内容 + has_actual_content = bool(node.golden_output_values) or node.content is not None + content = node.golden_output_values if node.golden_output_values else node.content + + # 【关键】将 golden_output_values 追加到 actual_outputs_history,标记该 Item 已被 investigate + # 这样在渐进式暴露时,这些值才会被加入可见值集合 + # 即使是空字典(仅触发 HIDDEN_ITEM 的 Item),也要记录,以便渐进式暴露逻辑知道该 Item 已被调查 + if node.golden_output_values is not None: + node.actual_outputs_history.append(dict(node.golden_output_values)) + + # 2. Trigger Hidden Item Drops (Passive Drop) + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + logger.info(f"Item investigation successful - node: {req.node_id}, has_content: {has_actual_content}, revealed: {len(newly_revealed)}") + + # 【渐进式暴露】旧机制(基于 golden_input)已禁用 + # 现在完全由 ITEM/HIDDEN_ITEM 边触发控制节点可见性 + # 上面的 HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, node.golden_output_values or {}, node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # logger.info(f"Progressive reveal after Item investigate: {len(progressive_revealed)} nodes now ready") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Item" + } + + # 只在有实际内容时才添加 content 字段 + # 对于仅触发 HIDDEN_ITEM 掉落的 Item,不返回 content 字段,避免返回 None 或空字典让模型困惑 + if has_actual_content: + result["content"] = content + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型通过 investigate 获得内容后,需要自己识别这是否是胜利字符串 + + return result + + else: + logger.warning(f"Attempt to investigate unknown node type: {req.node_id} (type: {node.type})") + return {"ok": False, "error": f"Cannot investigate node type: {node.type}"} + +class ToolCallRequest(BaseModel): + node_id: str # 使用 node_id 精确指定要调用的节点 + arguments: Dict[str, Any] + +@app.post("/env/{case_id}/tool_call") +def tool_call(case_id: str, req: ToolCallRequest): + """Executes a tool and triggers item drops.""" + logger.info(f"Tool call request - case_id: {case_id}, node_id: {req.node_id}, args: {list(req.arguments.keys())}") + STATS["tool_calls"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + + # 通过 node_id 精确查找节点 + node_id = req.node_id + if node_id not in scenario.nodes: + logger.error(f"Node not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + tool_node = scenario.nodes[node_id] + + if not tool_node: + logger.error(f"Tool not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Tool not found") + + if not tool_node.is_revealed: + logger.warning(f"Attempt to call hidden tool: {node_id}") + return {"ok": False, "error": "Tool is not visible yet."} + + if tool_node.type != "Tool": + logger.warning(f"Attempt to call non-tool node: {node_id} (type: {tool_node.type})") + return {"ok": False, "error": "Only tools can be called."} + + # 1. Execute Tool (Real Execution via Simulator) + simulator = SIMULATORS[case_id] + + # Get tool name from template_id if available, otherwise use node name + tool_name = tool_node.name + if case_id in RAW_NODES_DATA and node_id in RAW_NODES_DATA[case_id]: + template_id = RAW_NODES_DATA[case_id][node_id].get('template_id') + if template_id: + tool_name = template_id + + # 文件处理工具和 Terminal 需要验证输入并返回预先计算的输出 + # 传递节点的实际输入输出值(从 DAG 执行后填充的数据) + tool_arguments = dict(req.arguments) # Make a copy + + # 传递节点的 golden values(从 JSON 的 inputs[].value 和 outputs[].value 加载) + # 用于在评测阶段验证被测模型传入的参数是否正确 + if tool_node.golden_input_values: + tool_arguments['_golden_inputs'] = tool_node.golden_input_values + if tool_node.golden_output_values: + tool_arguments['_golden_outputs'] = tool_node.golden_output_values + + logger.debug(f"Executing tool {tool_name} (node: {tool_node.name}) with args {tool_arguments}") + + try: + output_values = simulator.execute(tool_name, tool_arguments) + logger.info(f"Tool invoked - {tool_name}: {list(output_values.keys())}") + except Exception as e: + logger.error(f"Tool execution failed - {tool_name}: {str(e)}", exc_info=True) + return {"ok": False, "error": f"Tool execution failed: {str(e)}"} + + # 检查验证结果(精细化错误反馈) + validation = output_values.pop("_validation", {"valid": True}) + + if not validation["valid"]: + # 根据错误类型构造友好的错误消息 + error_type = validation.get("error_type") + + if error_type == "missing_required": + missing = validation.get("missing_params", []) + error_msg = f"Error: Missing required parameters {', '.join(missing)}" + + elif error_type == "type_error": + param = validation.get("param_name") + message = validation.get("message", "Parameter type error") + error_msg = f"Error: {message}" + + elif error_type == "incomplete_optional": + provided = validation.get("provided_params", []) + missing = validation.get("missing_params", []) + error_msg = ( + f"Hint: You provided some parameters ({', '.join(provided)}), " + f"but may also need: {', '.join(missing)}.\n" + f"Trying to provide these parameters together might yield better results." + ) + + elif error_type == "value_mismatch": + param = validation.get("param_name") + hint = validation.get("hint", "Parameter value may be incorrect") + error_msg = f"Hint: {hint}.\nPlease check if this parameter value meets the requirements." + + else: + error_msg = validation.get("hint") or validation.get("message", "Parameter validation failed") + + logger.info(f"Tool validation failed - {tool_name}: {error_type}") + return { + "ok": False, + "error": error_msg, + "error_type": error_type + } + + # Simulate success + tool_node.if_success = True + + # 【关键】将本次执行的输出值追加到历史列表(用于渐进式暴露判断) + # 每次调用都会记录,不会覆盖之前的执行结果 + tool_node.actual_outputs_history.append(dict(output_values)) + + # 2. 检查是否应该触发掉落(只有输入参数正确时才掉落) + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, tool_node.golden_input_values) + + newly_revealed = [] + investigate_hints = [] # 提示模型哪些节点可以 investigate 来发现隐藏内容 + + if inputs_match_golden: + logger.info(f"✓ Tool inputs match golden - node: {node_id}, triggering drops") + + # 检查该工具是否有 ITEM 或 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == tool_node.id: + target_node = scenario.nodes[edge.target_id] + + # ITEM 边:立即掉落(主动掉落) + if edge.connection_type == InterfaceType.ITEM: + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from {node_id})") + + # HIDDEN_ITEM 边:不立即掉落,标记并提示(被动掉落) + elif edge.connection_type == InterfaceType.HIDDEN_ITEM: + # 标记该工具有待触发的 HIDDEN_ITEM 掉落 + tool_node.has_hidden_item_ready = True + + # 提示模型可以 investigate 这个工具来发现隐藏内容 + hint_info = { + "tool_id": tool_node.id, + "hint": f"Tool '{tool_node.id}' seems to hide something, try investigating it to discover more information" + } + # if tool_node.name: + # hint_info["tool_name"] = tool_node.name + + investigate_hints.append(hint_info) + logger.info(f"HIDDEN_ITEM ready: {tool_node.id} -> {target_node.id} (will drop on investigate)") + else: + logger.info(f"✗ Tool inputs do NOT match golden - node: {node_id}, no drops triggered") + + response = { + "ok": True, + "message": "Tool invoked", + "output_values": output_values # Return raw outputs to Agent + } + + # 【新增】对源头节点进行参数验证反馈 + # 源头节点:没有数据流入边的节点,这些节点的参数需要模型自己推理 + # 验证模型使用的参数是否正确,并提供明确的反馈 + if _is_source_node(node_id, scenario) and tool_node.golden_input_values: + validation_feedback = _get_parameter_validation_feedback(req.arguments, tool_node.golden_input_values) + + if validation_feedback["all_correct"]: + # 用户提交了全部 golden 参数且全部正确 + response["parameter_feedback"] = { + "status": "correct", + "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." + } + logger.info(f"✓ Source node parameters all correct - node: {node_id}") + elif validation_feedback["incorrect_params"]: + # 有提交了但值错误的参数,只对这些参数给出反馈 + incorrect_list = [] + for param_name in validation_feedback["incorrect_params"]: + incorrect_list.append(f" - Parameter '{param_name}' is incorrect") + + correct_info = "" + if validation_feedback["correct_params"]: + correct_info = f"\n✓ Correct parameters: {', '.join(validation_feedback['correct_params'])}" + + response["parameter_feedback"] = { + "status": "incorrect", + "message": ( + f"⚠️ Some parameters are incorrect:\n" + + "\n".join(incorrect_list) + + correct_info + + 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." + ), + "incorrect_params": validation_feedback["incorrect_params"], + "correct_params": validation_feedback["correct_params"] + } + logger.info(f"✗ Source node parameters incorrect - node: {node_id}, incorrect: {validation_feedback['incorrect_params']}") + # else: 部分提交且全部正确 → 不给任何 parameter_feedback,避免对未提交的参数发表意见 + + # 检查工具调用是否完全正确(输出与 golden outputs 匹配) + # 用于给模型正向反馈,让它知道这个工具已经正确调用过,避免重复调用 + # 注意:只有当输出完全匹配时才标记为 correct,不会在错误时提供具体错误信息 + # if tool_node.golden_output_values and output_values: + # is_correct = True + # for port_name, expected_value in tool_node.golden_output_values.items(): + # actual_value = output_values.get(port_name) + # if str(actual_value) != str(expected_value): + # is_correct = False + # break + + # if is_correct: + # response["tool_call_correct"] = True + # logger.info(f"✓ Tool called with correct result - node: {node_id}") + + # 只在有新内容掉落时才返回 newly_revealed + if newly_revealed: + response["newly_revealed"] = newly_revealed + + # 添加 investigate 提示(对于有待触发 HIDDEN_ITEM 掉落的工具) + if investigate_hints: + response["investigate_hints"] = investigate_hints + + # 3. 渐进式暴露机制 - 现在完全由 ITEM/HIDDEN_ITEM 边控制 + # 旧机制(基于 golden_input 检查)已被禁用 + # 新机制中,节点的可见性只由 ITEM/HIDDEN_ITEM 边触发决定 + # 上面的 ITEM/HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, output_values, tool_node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # response["newly_revealed"] = newly_revealed + # logger.info(f"Progressive reveal: {len(progressive_revealed)} nodes now ready") + + # Check if this is the win node + if node_id == scenario.win_node_id: + # 验证输出值是否等于预期的胜利值 + # 从节点的 golden_output_values 中获取预期值(在 _initialize_node_values 时从 JSON 加载) + expected_outputs = tool_node.golden_output_values + + # 检查实际输出是否与预期输出匹配 + is_correct = False + victory_string = None + mismatch_info = [] + + if expected_outputs and output_values: + # 检查每个预期输出端口的值是否匹配 + is_correct = True + for port_name, expected_value in expected_outputs.items(): + actual_value = output_values.get(port_name) + if actual_value != expected_value: + is_correct = False + mismatch_info.append(f"Port '{port_name}': expected '{expected_value}', actual '{actual_value}'") + logger.warning(f"Win node output mismatch - port: {port_name}, expected: {expected_value}, actual: {actual_value}") + + # 如果所有输出都匹配,使用第一个输出作为胜利字符串 + if is_correct and output_values: + victory_string = list(output_values.values())[0] + else: + logger.warning(f"Win node called but missing output values - expected: {expected_outputs}, actual: {output_values}") + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型调用工具获得输出后,需要自己识别这是否是胜利字符串并提交 + if is_correct: + logger.info(f"🎯 Win node called with correct output - case: {case_id}, node: {node_id}, victory: {victory_string}") + else: + logger.info(f"❌ Win node called with incorrect output - case: {case_id}, node: {node_id}") + + return response + +class UseItemRequest(BaseModel): + node_id: str = Field(..., description="The ID of the Item node to use (must be Item type)") + arguments: Dict[str, Any] = Field(default_factory=dict, description="Input arguments to provide to the item") + +@app.post("/env/{case_id}/use_item") +def use_item(case_id: str, req: UseItemRequest): + """ + Use an Item node by providing input arguments. + + This is specifically for Item nodes that require parameters to be "unlocked" or "activated", + such as containers that need a password/fingerprint. + + - Validates that the node is of type Item + - Checks if provided arguments match the item's golden_input_values + - If match: triggers ITEM-type edge drops and returns the item's content + - If not match: returns error message + """ + logger.info(f"Use item request - case_id: {case_id}, node_id: {req.node_id}, args: {req.arguments}") + STATS["use_items"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + item_node = scenario.nodes[req.node_id] + + if not item_node.is_revealed: + logger.warning(f"Attempt to use hidden item: {req.node_id}") + return {"ok": False, "error": "Item is not visible yet."} + + if item_node.type != "Item": + logger.warning(f"Attempt to use non-item node: {req.node_id} (type: {item_node.type})") + return {"ok": False, "error": "Only Item nodes can be used with use_item. Tools should be called with tool_call."} + + # 【新增】检查该 Item 是否已经被成功解锁 + # 如果已经被正确使用过,直接返回成功提示 + if item_node.if_success: + logger.info(f"Item already unlocked, returning success message: {req.node_id}") + return { + "ok": True, + "message": "This item has already been successfully unlocked by you." + } + + # 检查该 Item 是否真的需要通过 use_item 提供参数 + # 只有当 Item 有非 Item/Hidden_Item 类型的输入时,才应该使用 use_item + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + non_hidden_inputs = [ + inp for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + if not non_hidden_inputs: + # 该 Item 不需要参数,应该只使用 investigate + logger.warning(f"Attempt to use_item on a node that doesn't require parameters: {req.node_id}") + return { + "ok": False, + "error": "This item does not require parameters. Please use investigate to examine the item directly." + } + + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, item_node.golden_input_values) + + if not inputs_match_golden: + logger.info(f"✗ Item inputs do NOT match golden - node: {req.node_id}") + # 提供更详细的错误信息,帮助 Agent 理解问题 + # 只显示非 Item/Hidden_Item 类型的参数(Hidden_Item 由系统自动处理) + expected_params = [] + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + expected_params = [ + inp.get("name") for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + provided_params = list(req.arguments.keys()) if req.arguments else [] + + # 检查参数名是否匹配 + if set(expected_params) == set(provided_params): + # 参数名正确但值不匹配 - 不泄漏正确的值 + error_msg = f"Parameter names are correct, but the parameter values are incorrect. Please try using different parameter values." + else: + error_msg = f"Parameter names do not match. Expected parameter names: {expected_params}, you provided: {provided_params}." + + return { + "ok": False, + "error": error_msg + } + + logger.info(f"✓ Item inputs match golden - node: {req.node_id}, activating item") + + # 标记该 Item 已被正确使用 + item_node.if_success = True + + # 将 golden_output_values 追加到 actual_outputs_history + if item_node.golden_output_values: + item_node.actual_outputs_history.append(dict(item_node.golden_output_values)) + + # 触发 ITEM 类型边的掉落 + newly_revealed = [] + for edge in scenario.edges: + if edge.source_id == item_node.id and edge.connection_type == InterfaceType.ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from use_item on {req.node_id})") + + # 检查是否为 Win Node + win_node_id = scenario.win_node_id + is_win_node = (req.node_id == win_node_id) + + # 构建返回结果 + result = { + "ok": True, + "message": "Item used successfully.", + "content": item_node.golden_output_values if item_node.golden_output_values else None + } + + # 获取 narrative(如果存在) + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + narrative = raw_nodes_data[req.node_id].get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 如果是 Win Node,只记录日志 + if is_win_node: + logger.info(f"Win node (Item) unlocked via use_item - case: {case_id}, node: {req.node_id}") + + return result + + +class SubmitAnswerRequest(BaseModel): + answer: str = Field(..., description="The victory string to submit") + +@app.post("/env/{case_id}/submit_answer") +def submit_answer(case_id: str, req: SubmitAnswerRequest): + """ + 提交答案接口 + 被测模型在获得胜利字符串提示后,需要调用此接口提交答案 + """ + logger.info(f"Submit answer request - case_id: {case_id}, answer: {req.answer}") + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + + # 获取 win_node 的 golden_output_values + if not scenario.win_node_id: + logger.error(f"No win node defined for case: {case_id}") + return { + "ok": False, + "error": "This case has no victory node defined" + } + + win_node = scenario.nodes.get(scenario.win_node_id) + if not win_node: + logger.error(f"Win node not found: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node does not exist" + } + + # 获取正确的胜利字符串(取第一个 golden_output_value) + if win_node.golden_output_values: + correct_answer = list(win_node.golden_output_values.values())[0] + else: + logger.error(f"Win node has no golden_output_values: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node has no correct answer" + } + + # 验证提交的答案 + if req.answer == correct_answer: + logger.info(f"🎉 CORRECT ANSWER SUBMITTED - case: {case_id}, answer: {req.answer}") + return { + "ok": True, + "is_win": True, + "victory_message": f"🎉 Congratulations on successfully escaping the room! Your answer is correct: {req.answer}" + } + else: + logger.info(f"❌ INCORRECT ANSWER SUBMITTED - case: {case_id}, submitted: {req.answer}, correct: {correct_answer}") + return { + "ok": True, + "is_win": False, + "error": f"The submitted answer is incorrect. You submitted: {req.answer}" + } + +if __name__ == "__main__": + + uvicorn.run(app, host="0.0.0.0", port=8000) \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-3cee13d8/environment/puzzle/upstream/simulator.py b/tasks/agentescape-25-skeleton-3cee13d8/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3cee13d8/environment/puzzle/upstream/simulator.py @@ -0,0 +1,2911 @@ +import hashlib +import hmac +import base64 +import binascii +import zlib +import json +import uuid +import math +import re +from typing import Dict, Any, List + +class ToolSimulator: + def __init__(self): + """工具模拟器 + + 文件处理工具(zip_unzip, zip_unzip_file, zip_unzip_item, json_get, csv_query, + regex_search, graph_shortest_path)不需要真实文件系统。 + 这些工具只验证输入参数,然后返回预先初始化好的 golden_outputs。 + """ + self.tool_map = { + # 数论 + "calc_bigmul": self.calc_bigmul, + "calc_modexp": self.calc_modexp, + "calc_modexp_int": self.calc_modexp_int, + "calc_gcd": self.calc_gcd, + "calc_gcd_int": self.calc_gcd_int, + "calc_inv_mod": self.calc_inv_mod, + "calc_inv_mod_int": self.calc_inv_mod_int, + + # 哈希 + "hash_sha256": self.hash_sha256, + "hash_md5": self.hash_md5, + "hmac_sha256": self.hmac_sha256, + + # 编码 + "base64_decode": self.base64_decode, + "base64_encode": self.base64_encode, + "hex_decode": self.hex_decode, + "hex_encode": self.hex_encode, + "zlib_inflate": self.zlib_inflate, + "zlib_deflate": self.zlib_deflate, + + # 文件 + "zip_unzip": self.zip_unzip, + "zip_unzip_file": self.zip_unzip_file, + "zip_unzip_item": self.zip_unzip_item, + "regex_search": self.regex_search, + "json_get": self.json_get, + "csv_query": self.csv_query, + "code_py_exec": self.code_py_exec, + + # 图 + "graph_shortest_path": self.graph_shortest_path, + + # 加解密 (简化模拟) + "crypto_aes_cbc_decrypt": self.crypto_aes_cbc_decrypt, + "crypto_rsa_decrypt_hex": self.crypto_rsa_decrypt_hex, + + # 其他 + "num_base_convert": self.num_base_convert, + "time_convert": self.time_convert, + "checksum_crc32": self.checksum_crc32, + "geo_haversine": self.geo_haversine, + "otp_totp_generate": self.otp_totp_generate, + "unicode_norm": self.unicode_norm, + "text_bidi_sanitize": self.text_bidi_sanitize, + "text_xor_hex": self.text_xor_hex, + "text_rotN": self.text_rotN, + "luhn_check": self.luhn_check, + "iban_validate": self.iban_validate, + + # 物理 + "matter_synthesizer": self.matter_synthesizer, + + # 终端机 + "terminal_1": self.terminal_1, + "terminal_2": self.terminal_2, + "Logic Terminal": self.logic_terminal, + "Math Terminal": self.math_terminal, + "Encryption Terminal": self.crypt_terminal, + "Sequence Terminal": self.sequence_terminal + } + + def execute(self, tool_name: str, inputs: Dict[str, Any]) -> Dict[str, Any]: + if tool_name not in self.tool_map: + # Fallback for unknown tools: return dummy outputs based on expected output types + # This should ideally not happen if all tools are implemented + return {} + + try: + return self.tool_map[tool_name](inputs) + except Exception as e: + print(f"Error executing {tool_name}: {e}") + # Return empty or error indication? For generation, we might want to fail hard or return dummy. + # For now, return dummy to keep flow going, but log error. + return {} + + # --- Implementations --- + + def calc_bigmul(self, inputs): + # Check if required parameters are present + if "a" not in inputs or "b" not in inputs: + raise ValueError("Missing required parameters 'a' and/or 'b'") + + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + return {"product": str(a * b)} + except (ValueError, TypeError) as e: + raise ValueError(f"Failed to convert parameters to integers: {str(e)}") + + def calc_modexp(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + try: + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if isinstance(base, str): + base = int(base) + elif not isinstance(base, int): + raise ValueError("Parameter 'base' must be a string or integer") + + if isinstance(exp, str): + exp = int(exp) + elif not isinstance(exp, int): + raise ValueError("Parameter 'exp' must be a string or integer") + + if isinstance(mod, str): + mod = int(mod) + elif not isinstance(mod, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": str(pow(base, exp, mod))} + + def calc_modexp_int(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["base"], int): + raise ValueError("Parameter 'base' must be an integer") + if not isinstance(inputs["exp"], int): + raise ValueError("Parameter 'exp' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": pow(base, exp, mod)} + + def calc_gcd(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + # 计算 GCD 并返回字符串格式(符合 Big_Int 输出类型) + result = math.gcd(a, b) + return {"gcd": str(result)} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def calc_gcd_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["b"], int): + raise ValueError("Parameter 'b' must be an integer") + + # 获取参数 + a = inputs["a"] + b = inputs["b"] + + return {"gcd": math.gcd(a, b)} + + def calc_inv_mod(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + m = inputs["mod"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(m, str): + m = int(m) + elif not isinstance(m, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": str(pow(a, -1, m))} + except ValueError as e: + # 模逆不存在时,返回一个特殊值(用于数据传递) + # 在 DAG 生成阶段,这允许数据流继续 + return {"inv": str(a)} + + def calc_inv_mod_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + a = inputs["a"] + m = inputs["mod"] + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": pow(a, -1, m)} + except ValueError as e: + raise ValueError(f"Modular inverse does not exist: {str(e)}") + + def hash_sha256(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.sha256(text.encode()).hexdigest()} + + def hash_md5(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.md5(text.encode()).hexdigest()} + + def hmac_sha256(self, inputs): + # 参数检查 + if "hex_key" not in inputs: + raise ValueError("Missing required parameter: hex_key") + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["hex_key"], str): + raise ValueError("Parameter 'hex_key' must be a string") + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + try: + key = bytes.fromhex(inputs["hex_key"]) + text = inputs["text"].encode() + return {"hex": hmac.new(key, text, hashlib.sha256).hexdigest()} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def base64_decode(self, inputs): + # 参数检查 + if "data" not in inputs: + raise ValueError("Missing required parameter: data") + + # 类型检查 + if not isinstance(inputs["data"], str): + raise ValueError("Parameter 'data' must be a string") + + data = inputs["data"] + try: + return {"bytes_hex": binascii.hexlify(base64.b64decode(data)).decode()} + except Exception as e: + raise ValueError(f"Base64 decode error: {str(e)}") + + def base64_encode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"b64": base64.b64encode(bytes.fromhex(hex_data)).decode()} + except Exception as e: + raise ValueError(f"Base64 encode error: {str(e)}") + + def hex_decode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"text": bytes.fromhex(hex_data).decode('utf-8', errors='ignore')} + except Exception as e: + raise ValueError(f"Hex decode error: {str(e)}") + + def hex_encode(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + try: + return {"hex": text.encode().hex()} + except Exception as e: + raise ValueError(f"Hex encode error: {str(e)}") + + + # 到此处实现已经更新 + + def zlib_inflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("Parameter 'hex' must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("Missing required parameter: hex") + + try: + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空字符串 + if not hex_data: + raise ValueError("Empty hex string provided") + + # 检查十六进制字符串的有效性 + if len(hex_data) % 2 != 0: + raise ValueError("Hex string must have even length") + + # 检查是否只包含有效的十六进制字符 + if not all(c in '0123456789abcdefABCDEF' for c in hex_data): + raise ValueError("Invalid hex string provided") + + # 尝试解压缩 + return {"text": zlib.decompress(bytes.fromhex(hex_data)).decode('utf-8')} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hex string provided") from e + raise ValueError(f"Invalid zlib data: {e}") from e + except Exception as e: + raise RuntimeError(f"Failed to inflate data: {e}") from e + + def zlib_deflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("Parameter 'text' must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("Missing required parameter: text") + + try: + # 压缩文本 + return {"hex": zlib.compress(text.encode('utf-8')).hex()} + except Exception as e: + raise RuntimeError(f"Failed to deflate data: {e}") from e + + # --- File Operations --- + + def zip_unzip(self, inputs): + """ZIP 解压工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"files": golden_outputs.get("files", "")} + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return {"files": golden_outputs.get("files", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "files" in golden_outputs: + # 验证必需参数 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 检查类型 + if has_zip_id and not isinstance(zip_id, str): + return {"error": "Parameter 'zip_id' must be a string type"} + if has_password and not isinstance(password, str): + return {"error": "Parameter 'password' must be a string type"} + + # 验证输入是否与预期匹配 + if golden_inputs: + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return {"files": golden_outputs["files"]} + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + # 没有golden_inputs但有golden_outputs,直接返回输出 + return {"files": golden_outputs["files"]} + + # 如果没有预期输出,返回空结果 + return {"files": ""} + + def regex_search(self, inputs): + """正则搜索工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"matches": golden_outputs.get("matches", "[]")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "matches" in golden_outputs: + # 提取实际参数 + pattern = inputs.get("pattern") + file_id = inputs.get("file_id") + text = inputs.get("text") + + # 1. 检查必需参数 + if pattern is None: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["pattern"], + "message": "Missing required parameter 'pattern'" + } + } + + # 类型检查 + if not isinstance(pattern, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "pattern", + "message": "Parameter 'pattern' must be a string type" + } + } + if file_id is not None and not isinstance(file_id, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if text is not None and not isinstance(text, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "text", + "message": "Parameter 'text' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合 + provided_params = {} + if pattern is not None: + provided_params["pattern"] = pattern + if file_id is not None: + provided_params["file_id"] = file_id + if text is not None: + provided_params["text"] = text + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数(关键改进) + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_pattern = golden_inputs.get("pattern") + expected_file_id = golden_inputs.get("file_id") + expected_text = golden_inputs.get("text") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_pattern is not None: + if str(pattern) != str(expected_pattern): + incorrect_params.append("pattern") + else: + correct_params.append("pattern") + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_text is not None: + if str(text) != str(expected_text): + incorrect_params.append("text") + else: + correct_params.append("text") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "matches": "[]", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "matches": golden_outputs["matches"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空列表 + return {"matches": "[]"} + + def json_get(self, inputs): + """JSON 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"values": golden_outputs.get("values", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "values" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + jsonpath = inputs.get("jsonpath", "") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if jsonpath is not None and not isinstance(jsonpath, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "jsonpath", + "message": "Parameter 'jsonpath' must be a string type" + } + } + + # 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:jsonpath有默认值"") + provided_params = {} + if file_id is not None: + provided_params["file_id"] = file_id + if jsonpath != "": + provided_params["jsonpath"] = jsonpath + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_jsonpath = golden_inputs.get("jsonpath") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_jsonpath is not None: + if str(jsonpath) != str(expected_jsonpath): + incorrect_params.append("jsonpath") + else: + correct_params.append("jsonpath") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "values": "", + "_validation": validation_info + } + + # 所有验证通过,返回正确输出 + return { + "values": golden_outputs["values"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"values": ""} + + def csv_query(self, inputs): + """CSV 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"rows": golden_outputs.get("rows", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "rows" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + select_columns = inputs.get("select", "") + where_clause = inputs.get("where", "") + + # 1. 检查必需参数 + if file_id is None: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["file_id"], + "message": "Missing required parameter 'file_id'" + } + } + + # 类型检查 + if not isinstance(file_id, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if not isinstance(select_columns, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "select", + "message": "Parameter 'select' must be a string type" + } + } + if not isinstance(where_clause, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "where", + "message": "Parameter 'where' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:select和where有默认值"") + provided_params = {"file_id": file_id} + if select_columns != "": + provided_params["select"] = select_columns + if where_clause != "": + provided_params["where"] = where_clause + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_select = golden_inputs.get("select") + expected_where = golden_inputs.get("where") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_select is not None: + if str(select_columns) != str(expected_select): + incorrect_params.append("select") + else: + correct_params.append("select") + + if expected_where is not None: + if str(where_clause) != str(expected_where): + incorrect_params.append("where") + else: + correct_params.append("where") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "rows": "", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "rows": golden_outputs["rows"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"rows": ""} + + def graph_shortest_path(self, inputs): + """图最短路径工具 + + 如果有 _golden_outputs 或 _init_outputs,验证输入并返回预设输出。 + 否则执行真实的 Dijkstra 算法。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 检查是否在预设模式中(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + if golden_outputs and "path" in golden_outputs: + # 评测阶段但没有 golden_inputs,直接返回 outputs + if not golden_inputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 评测模式:验证输入参数是否匹配 golden 值 + src = inputs.get("src") + dst = inputs.get("dst") + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + + has_src = src is not None and src != "" + has_dst = dst is not None and dst != "" + + # 验证必需参数 + if not has_src or not has_dst: + missing = [] + if not has_src: + missing.append("src") + if not has_dst: + missing.append("dst") + return {"error": "Missing required parameters: " + ", ".join(missing)} + + # 类型检查 + if not isinstance(src, str): + return {"error": "Parameter 'src' must be a string"} + if not isinstance(dst, str): + return {"error": "Parameter 'dst' must be a string"} + + # 验证输入是否匹配期望值 + if golden_inputs: + expected_src = golden_inputs.get("src") + expected_dst = golden_inputs.get("dst") + expected_file_id = golden_inputs.get("file_id") + expected_graph_data = golden_inputs.get("graph_data") + + # 收集验证结果 + incorrect_params = [] + correct_params = [] + + # 检查必需参数是否匹配 + if expected_src is not None: + if str(src) != str(expected_src): + incorrect_params.append("src") + else: + correct_params.append("src") + + if expected_dst is not None: + if str(dst) != str(expected_dst): + incorrect_params.append("dst") + else: + correct_params.append("dst") + + # 检查可选参数(如果在 expected_inputs 中定义了) + if expected_file_id is not None: + if file_id != expected_file_id: + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_graph_data is not None: + if graph_data != expected_graph_data: + incorrect_params.append("graph_data") + else: + correct_params.append("graph_data") + + # 如果有参数不正确,返回详细的反馈 + if incorrect_params: + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 验证通过,返回预设的输出 + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 获取参数(真实执行路径) + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + # Support both src/dst (interface definition) and start/end (original implementation) + start = inputs.get("src") + end = inputs.get("dst") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + raise TypeError("file_id must be a string") + + if graph_data is not None and not isinstance(graph_data, str): + raise TypeError("graph_data must be a string") + + if start is not None and not isinstance(start, str): + raise TypeError("src/start must be a string") + + if end is not None and not isinstance(end, str): + raise TypeError("dst/end must be a string") + + # 检查必需参数 + if file_id is None and graph_data is None: + raise ValueError("Either file_id or graph_data must be provided") + + if start is None: + raise ValueError("src/start parameter is required") + + if end is None: + raise ValueError("dst/end parameter is required") + + # Get graph content + content = None + if file_id is not None: + # 尝试从 VFS 获取(如果存在) + if hasattr(self, 'vfs') and file_id in self.vfs: + content = self.vfs[file_id] + else: + # VFS 不存在或文件不在 VFS 中 + # 返回一个默认的空图结果,或者抛出错误提示需要 init_outputs + raise ValueError( + f"File '{file_id}' not found. For tools that require files, " + f"please provide init_outputs in the initial_values." + ) + elif graph_data is not None: + content = graph_data + + if content is None: + content = "{}" + + try: + # Parse graph data + graph = json.loads(content) + + # 类型检查 + if not isinstance(graph, dict): + raise TypeError("Graph data must be a dictionary") + + # If graph is not in the expected format, try to extract adjacency list + if "nodes" in graph and "edges" in graph: + # 验证nodes和edges的类型 + if not isinstance(graph["nodes"], list): + raise TypeError("Nodes must be a list") + + if not isinstance(graph["edges"], list): + raise TypeError("Edges must be a list") + + # Convert from nodes/edges format to adjacency list + adjacency_list = {} + for node in graph["nodes"]: + # 验证node类型 + if not isinstance(node, dict): + raise TypeError("Each node must be a dictionary") + + # Use node ID as key, not the entire node dictionary + node_id = node.get("id", "") + if node_id: + adjacency_list[node_id] = {} + + for edge in graph["edges"]: + # 验证edge类型 + if not isinstance(edge, dict): + raise TypeError("Each edge must be a dictionary") + + u = edge["from"] + v = edge["to"] + weight = edge.get("weight", 1) # Default to unweighted + + # 类型检查 + if not isinstance(u, str): + raise TypeError("Edge 'from' must be a string") + + if not isinstance(v, str): + raise TypeError("Edge 'to' must be a string") + + if not isinstance(weight, (int, float)): + raise TypeError("Edge weight must be a number") + + if u not in adjacency_list: + adjacency_list[u] = {} + if v not in adjacency_list: + adjacency_list[v] = {} + + adjacency_list[u][v] = weight + # If undirected, add reverse edge + if not edge.get("directed", False): + adjacency_list[v][u] = weight + elif isinstance(graph, dict): + # Already in adjacency list format + adjacency_list = graph + + # 验证邻接表结构 + for node, neighbors in adjacency_list.items(): + if not isinstance(neighbors, dict): + raise TypeError("Adjacency list must be a dictionary of dictionaries") + + for neighbor, weight in neighbors.items(): + if not isinstance(weight, (int, float)): + raise TypeError("Edge weights must be numbers") + else: + raise TypeError("Graph data must be a dictionary") + + # 检查起点和终点是否为空 + if not start: + raise ValueError("Start node cannot be empty") + + if not end: + raise ValueError("End node cannot be empty") + + # 检查起点和终点是否在图中 + if start not in adjacency_list: + raise ValueError(f"Start node '{start}' not found in graph") + + if end not in adjacency_list: + raise ValueError(f"End node '{end}' not found in graph") + + # Dijkstra's algorithm implementation + import heapq + + # Initialize distances and previous nodes + distances = {node: float('infinity') for node in adjacency_list} + previous = {node: None for node in adjacency_list} + distances[start] = 0 + + # Priority queue + pq = [(0, start)] + heapq.heapify(pq) + + while pq: + current_dist, current_node = heapq.heappop(pq) + + # If we've reached the end node, we can break early + if current_node == end: + break + + # Nodes can be added multiple times to the priority queue, but we only process them once + if current_dist > distances[current_node]: + continue + + # Explore neighbors + for neighbor, weight in adjacency_list[current_node].items(): + distance = current_dist + weight + + # If a shorter path is found + if distance < distances[neighbor]: + distances[neighbor] = distance + previous[neighbor] = current_node + heapq.heappush(pq, (distance, neighbor)) + + # Reconstruct the shortest path + path = [] + current = end + while current is not None: + path.append(current) + current = previous[current] + path.reverse() # Reverse to get from start to end + + # Check if path exists + if not path or path[0] != start: + return {"path": "[]", "cost": 0} + + return { + "path": json.dumps(path), + "cost": distances[end] + } + except json.JSONDecodeError as e: + raise ValueError(f"Invalid JSON in graph data: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in graph_shortest_path: {str(e)}") + + # --- Crypto (Simplified) --- + def crypto_aes_cbc_decrypt(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 (使用模板中定义的参数名) + hex_cipher = inputs.get("hex_cipher") + hex_key = inputs.get("hex_key") + hex_iv = inputs.get("hex_iv") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + + if hex_key is not None and not isinstance(hex_key, str): + raise TypeError("hex_key must be a string") + + if hex_iv is not None and not isinstance(hex_iv, str): + raise TypeError("hex_iv must be a string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + + if hex_key is None: + raise ValueError("hex_key parameter is required") + + if hex_iv is None: + raise ValueError("hex_iv parameter is required") + + from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes + from cryptography.hazmat.backends import default_backend + from cryptography.hazmat.primitives import padding + + try: + # Convert hex strings to bytes + ciphertext = bytes.fromhex(hex_cipher) + key = bytes.fromhex(hex_key) + iv = bytes.fromhex(hex_iv) + + # Validate key length (AES-128, AES-192, AES-256) + if len(key) not in [16, 24, 32]: + raise ValueError("Invalid key length. Must be 16, 24, or 32 bytes.") + + if len(iv) != 16: + raise ValueError("Invalid IV length. Must be 16 bytes.") + + # Create cipher object + cipher = Cipher( + algorithms.AES(key), + modes.CBC(iv), + backend=default_backend() + ) + + decryptor = cipher.decryptor() + + # Decrypt the ciphertext + padded_plaintext = decryptor.update(ciphertext) + decryptor.finalize() + + # Remove PKCS7 padding + unpadder = padding.PKCS7(128).unpadder() + plaintext = unpadder.update(padded_plaintext) + unpadder.finalize() + + # Return decrypted text + return {"text": plaintext.decode('utf-8', errors='ignore')} + except ValueError as e: + if "non-hexadecimal number found in fromhex()" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher, hex_key, or hex_iv") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in crypto_aes_cbc_decrypt: {str(e)}") + + def crypto_rsa_decrypt_hex(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_cipher = inputs.get("hex_cipher") + n = inputs.get("n") + d = inputs.get("d") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + if n is not None and not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + if d is not None and not isinstance(d, (int, str)): + raise TypeError("d must be an integer or string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + if n is None: + raise ValueError("n parameter is required") + if d is None: + raise ValueError("d parameter is required") + + try: + # Convert parameters to appropriate types + cipher_int = int(hex_cipher, 16) + n_int = int(n) if isinstance(n, str) else n + d_int = int(d) if isinstance(d, str) else d + + # RSA decryption: plaintext = ciphertext^d mod n + plaintext_int = pow(cipher_int, d_int, n_int) + + # Convert result to hex and then to text + plaintext_hex = hex(plaintext_int)[2:] + + # Pad with leading zero if odd length + if len(plaintext_hex) % 2 != 0: + plaintext_hex = '0' + plaintext_hex + + # Convert hex to bytes and then to text + try: + plaintext_bytes = bytes.fromhex(plaintext_hex) + plaintext_text = plaintext_bytes.decode('utf-8', errors='ignore') + except: + # If decoding fails, return hex representation + plaintext_text = plaintext_hex + + return {"text": plaintext_text} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in crypto_rsa_decrypt_hex: {str(e)}") + + # --- Others --- + def num_base_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + s = inputs.get("s") + from_base = inputs.get("from_base") + to_base = inputs.get("to_base") + + # 类型检查 - 接受 str 或 int + if s is not None and not isinstance(s, (str, int)): + raise TypeError("s must be a string or integer") + + if from_base is not None and not isinstance(from_base, (int, str)): + raise TypeError("from_base must be an integer") + + if to_base is not None and not isinstance(to_base, (int, str)): + raise TypeError("to_base must be an integer") + + # 检查必需参数 + if s is None: + raise ValueError("s parameter is required") + + if from_base is None: + raise ValueError("from_base parameter is required") + + if to_base is None: + raise ValueError("to_base parameter is required") + + try: + # Convert to int if needed + from_base = int(from_base) if isinstance(from_base, str) else from_base + to_base = int(to_base) if isinstance(to_base, str) else to_base + s_str = str(s) + + # 验证基数范围 + if from_base < 2 or from_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + if to_base < 2 or to_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + # Convert from source base to decimal + val = int(s_str, from_base) + + # Convert from decimal to target base + if to_base == 10: + result = str(val) + elif to_base == 16: + result = hex(val)[2:] + elif to_base == 8: + result = oct(val)[2:] + elif to_base == 2: + result = bin(val)[2:] + else: + # Generic base conversion for other bases + if val == 0: + result = "0" + else: + digits = "0123456789abcdefghijklmnopqrstuvwxyz" + result = "" + n = abs(val) + while n: + result = digits[n % to_base] + result + n //= to_base + if val < 0: + result = "-" + result + + return {"str": result} + except ValueError as e: + raise ValueError(f"Invalid number format: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in num_base_convert: {str(e)}") + + def time_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iso = inputs.get("iso") + timestamp = inputs.get("timestamp") + datetime_str = inputs.get("datetime") + from_tz = inputs.get("from_tz") + to_tz = inputs.get("to_tz") + format_str = inputs.get("format") + + # 类型检查 + if iso is not None and not isinstance(iso, str): + raise TypeError("iso must be a string") + + if timestamp is not None and not isinstance(timestamp, (str, int, float)): + raise TypeError("timestamp must be a string, integer, or float") + + if datetime_str is not None and not isinstance(datetime_str, str): + raise TypeError("datetime must be a string") + + if from_tz is not None and not isinstance(from_tz, str): + raise TypeError("from_tz must be a string") + + if to_tz is not None and not isinstance(to_tz, str): + raise TypeError("to_tz must be a string") + + if format_str is not None and not isinstance(format_str, str): + raise TypeError("format must be a string") + + # 设置默认值 + if from_tz is None: + from_tz = "UTC" + + if to_tz is None: + to_tz = "UTC" + + import datetime + import pytz + + # 验证时区参数 + try: + if from_tz: + pytz.timezone(from_tz) + if to_tz: + pytz.timezone(to_tz) + except Exception: + raise ValueError("Invalid timezone provided") + + try: + # Parse input time + dt = None + + if iso is not None: + # Parse ISO 8601 format + dt = datetime.datetime.fromisoformat(iso.replace('Z', '+00:00')) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=pytz.UTC) + elif timestamp is not None: + # Parse Unix timestamp + timestamp = float(timestamp) + dt = datetime.datetime.fromtimestamp(timestamp, pytz.UTC) + elif datetime_str is not None: + # Parse datetime string + # Try common formats + formats_to_try = [ + "%Y-%m-%d %H:%M:%S", + "%Y-%m-%d %H:%M:%S.%f", + "%Y-%m-%d", + "%m/%d/%Y %H:%M:%S", + "%m/%d/%Y" + ] + + parse_success = False + for fmt in formats_to_try: + try: + dt = datetime.datetime.strptime(datetime_str, fmt) + dt = pytz.timezone(from_tz).localize(dt) + parse_success = True + break + except ValueError: + continue + + if not parse_success: + raise ValueError("Unable to parse datetime string with common formats") + else: + # 如果没有提供任何时间参数,则使用当前时间 + dt = datetime.datetime.now(pytz.UTC) + except ValueError as e: + raise ValueError(f"Error parsing time input: {str(e)}") + except Exception as e: + raise RuntimeError(f"Unexpected error parsing time input: {str(e)}") + + try: + # Convert timezone + if from_tz != to_tz: + dt = dt.astimezone(pytz.timezone(to_tz)) + + # Format outputs + result = { + "iso": dt.isoformat(), + "timestamp": str(dt.timestamp()), + "datetime": dt.strftime("%Y-%m-%d %H:%M:%S"), + "date": dt.strftime("%Y-%m-%d"), + "time": dt.strftime("%H:%M:%S"), + "timezone": to_tz + } + + # Add custom format if requested + if format_str: + try: + result["formatted"] = dt.strftime(format_str) + except ValueError as e: + raise ValueError(f"Invalid format string: {str(e)}") + + return result + except Exception as e: + raise RuntimeError(f"Error in time_convert: {str(e)}") + + def checksum_crc32(self, inputs): + import zlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("hex must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("hex parameter is required") + + try: + # 验证十六进制字符串 + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空 + if not hex_data: + raise ValueError("hex data cannot be empty") + + # 检查是否为有效的十六进制字符串 + if not all(c in "0123456789abcdefABCDEF" for c in hex_data): + raise ValueError("hex must be a valid hexadecimal string") + + # 检查长度是否为偶数 + if len(hex_data) % 2 != 0: + raise ValueError("hex must have even number of characters") + + val = zlib.crc32(bytes.fromhex(hex_data)) + # 确保 hex 输出是 8 位,前导补 0 + return {"hex": f"{val:08x}", "int": val} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in checksum_crc32: {str(e)}") + + def geo_haversine(self, inputs): + import math + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + lat1 = inputs.get("lat1") + lon1 = inputs.get("lon1") + lat2 = inputs.get("lat2") + lon2 = inputs.get("lon2") + + # 类型检查 + if lat1 is not None and not isinstance(lat1, (int, float, str)): + raise TypeError("lat1 must be a number or string") + if lon1 is not None and not isinstance(lon1, (int, float, str)): + raise TypeError("lon1 must be a number or string") + if lat2 is not None and not isinstance(lat2, (int, float, str)): + raise TypeError("lat2 must be a number or string") + if lon2 is not None and not isinstance(lon2, (int, float, str)): + raise TypeError("lon2 must be a number or string") + + # 检查必需参数 + if lat1 is None: + raise ValueError("lat1 parameter is required") + if lon1 is None: + raise ValueError("lon1 parameter is required") + if lat2 is None: + raise ValueError("lat2 parameter is required") + if lon2 is None: + raise ValueError("lon2 parameter is required") + + try: + # 转换为浮点数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(lat1, str): + lat1 = float(lat1) + elif not isinstance(lat1, (int, float)): + raise TypeError("lat1 must be a number or string") + else: + lat1 = float(lat1) + + if isinstance(lon1, str): + lon1 = float(lon1) + elif not isinstance(lon1, (int, float)): + raise TypeError("lon1 must be a number or string") + else: + lon1 = float(lon1) + + if isinstance(lat2, str): + lat2 = float(lat2) + elif not isinstance(lat2, (int, float)): + raise TypeError("lat2 must be a number or string") + else: + lat2 = float(lat2) + + if isinstance(lon2, str): + lon2 = float(lon2) + elif not isinstance(lon2, (int, float)): + raise TypeError("lon2 must be a number or string") + else: + lon2 = float(lon2) + + # Validate coordinates (approximate range check) + if not (-90 <= lat1 <= 90): + raise ValueError("lat1 must be between -90 and 90") + if not (-90 <= lat2 <= 90): + raise ValueError("lat2 must be between -90 and 90") + if not (-180 <= lon1 <= 180): + raise ValueError("lon1 must be between -180 and 180") + if not (-180 <= lon2 <= 180): + raise ValueError("lon2 must be between -180 and 180") + + # Earth radius in meters + R = 6371000 # Approximate radius of Earth + + # Convert degrees to radians + lat1_rad = math.radians(lat1) + lon1_rad = math.radians(lon1) + lat2_rad = math.radians(lat2) + lon2_rad = math.radians(lon2) + + # Calculate differences + delta_lat = lat2_rad - lat1_rad + delta_lon = lon2_rad - lon1_rad + + # Haversine formula + a = math.sin(delta_lat / 2) ** 2 + \ + math.cos(lat1_rad) * math.cos(lat2_rad) * \ + math.sin(delta_lon / 2) ** 2 + c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) + distance_m = R * c + + # Return distance in meters + return {"meters": round(distance_m, 2)} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in geo_haversine: {str(e)}") + + def otp_totp_generate(self, inputs): + import hmac + import hashlib + import base64 + import time + import struct + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + base32_secret = inputs.get("base32_secret") + step = inputs.get("step", 30) # Default to 30 seconds + digits = inputs.get("digits", 6) # Default to 6 digits + timestamp_iso = inputs.get("timestamp_iso", "") + algo = inputs.get("algo", "sha1") # Default to sha1 as current implementation only supports this + + # 类型检查 + if base32_secret is not None and not isinstance(base32_secret, str): + raise TypeError("base32_secret must be a string") + if not isinstance(step, (int, str)): + raise TypeError("step must be an integer or string") + if not isinstance(digits, (int, str)): + raise TypeError("digits must be an integer or string") + if not isinstance(timestamp_iso, str): + raise TypeError("timestamp_iso must be a string") + if not isinstance(algo, str): + raise TypeError("algo must be a string") + + # 检查必需参数 + if base32_secret is None: + raise ValueError("base32_secret parameter is required") + + try: + # Convert step and digits to appropriate types + step = int(step) + digits = int(digits) + if digits < 6 or digits > 8: + raise ValueError("Digits must be between 6 and 8") + + # Convert timestamp_iso to integer timestamp + if timestamp_iso: + import datetime + dt = datetime.datetime.fromisoformat(timestamp_iso.replace('Z', '+00:00')) + timestamp = int(dt.timestamp()) + else: + timestamp = int(time.time()) + + # Calculate counter value (T = floor(timestamp / step)) + counter = timestamp // step + + # Decode the base32 secret + # Add padding if necessary (base64 requires padding to be multiple of 8) + base32_secret = base32_secret.upper().replace(' ', '') + if len(base32_secret) % 8 != 0: + base32_secret += '=' * (8 - (len(base32_secret) % 8)) + key = base64.b32decode(base32_secret, casefold=True) + + # Calculate HMAC-SHA1 + counter_bytes = struct.pack('>Q', counter) # Big-endian 8-byte integer + hmac_hash = hmac.new(key, counter_bytes, hashlib.sha1).digest() + + # Dynamic truncation + offset = hmac_hash[-1] & 0xF + code = struct.unpack('>I', hmac_hash[offset:offset+4])[0] & 0x7FFFFFFF + + # Generate the OTP + otp = str(code % (10 ** digits)).zfill(digits) + + # Calculate remaining time until next OTP change + remaining_time = step - (timestamp % step) + + return {"totp": otp, "remaining_time": remaining_time, "time_step": step} + except ValueError as e: + if "invalid literal for int()" in str(e): + raise ValueError("step and digits must be valid integers") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in otp_totp_generate: {str(e)}") + + def unicode_norm(self, inputs): + import unicodedata + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + form = inputs.get("form", "NFC") # Default to NFC + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if form is not None and not isinstance(form, str): + raise TypeError("form must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Normalize form (NFC, NFD, NFKC, NFKD) + form = form.upper().strip() + + if form not in ['NFC', 'NFD', 'NFKC', 'NFKD']: + raise ValueError(f"Invalid normalization form: {form}. Must be one of: NFC, NFD, NFKC, NFKD") + + # Apply Unicode normalization + normalized_text = unicodedata.normalize(form, text) + + return {"text": normalized_text} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in unicode_norm: {str(e)}") + + def text_bidi_sanitize(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Bidi control characters to remove + bidi_controls = [ + '\u200E', # LEFT-TO-RIGHT MARK + '\u200F', # RIGHT-TO-LEFT MARK + '\u202A', # LEFT-TO-RIGHT EMBEDDING + '\u202B', # RIGHT-TO-LEFT EMBEDDING + '\u202C', # POP DIRECTIONAL FORMATTING + '\u202D', # LEFT-TO-RIGHT OVERRIDE + '\u202E', # RIGHT-TO-LEFT OVERRIDE + '\u2066', # LEFT-TO-RIGHT ISOLATE + '\u2067', # RIGHT-TO-LEFT ISOLATE + '\u2068', # FIRST STRONG ISOLATE + '\u2069', # POP DIRECTIONAL ISOLATE + ] + + # Remove all Bidi control characters + sanitized_text = text + for control_char in bidi_controls: + sanitized_text = sanitized_text.replace(control_char, '') + + return {"text": sanitized_text} + except Exception as e: + raise RuntimeError(f"Error in text_bidi_sanitize: {str(e)}") + + def text_xor_hex(self, inputs): + import binascii + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_a = inputs.get("hex_a") + hex_b = inputs.get("hex_b") + + # 类型检查 + if hex_a is not None and not isinstance(hex_a, str): + raise TypeError("hex_a must be a string") + if hex_b is not None and not isinstance(hex_b, str): + raise TypeError("hex_b must be a string") + + # 检查必需参数 + if hex_a is None: + raise ValueError("hex_a parameter is required") + if hex_b is None: + raise ValueError("hex_b parameter is required") + + try: + # Remove any whitespace + hex_a = hex_a.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + hex_b = hex_b.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + + # Validate hex strings + if not (all(c in "0123456789abcdefABCDEF" for c in hex_a) and len(hex_a) % 2 == 0): + raise ValueError("hex_a must be a valid hexadecimal string with even length") + if not (all(c in "0123456789abcdefABCDEF" for c in hex_b) and len(hex_b) % 2 == 0): + raise ValueError("hex_b must be a valid hexadecimal string with even length") + + # Convert hex strings to bytes + bytes_a = binascii.unhexlify(hex_a) + bytes_b = binascii.unhexlify(hex_b) + + # Make the byte arrays the same length by padding the shorter one with zeros + max_len = max(len(bytes_a), len(bytes_b)) + bytes_a = bytes_a.ljust(max_len, b'\x00') + bytes_b = bytes_b.ljust(max_len, b'\x00') + + # Perform XOR operation + result_bytes = bytes(a ^ b for a, b in zip(bytes_a, bytes_b)) + + # Convert result back to hex + result_hex = binascii.hexlify(result_bytes).decode('utf-8') + + return {"hex": result_hex} + except ValueError as e: + if "Non-hexadecimal digit found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in text_xor_hex: {str(e)}") + + def text_rotN(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + n = inputs.get("n", 0) + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + n = int(n) + except ValueError: + raise ValueError("n must be a valid integer") + + result = [] + for char in text: + if char.isupper(): + # Rotate uppercase letters + result_char = chr((ord(char) - ord('A') + n) % 26 + ord('A')) + result.append(result_char) + elif char.islower(): + # Rotate lowercase letters + result_char = chr((ord(char) - ord('a') + n) % 26 + ord('a')) + result.append(result_char) + else: + # Keep non-alphabetic characters unchanged + result.append(char) + + return {"text": ''.join(result)} + + def luhn_check(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数(支持 card_number 和 number 两个参数名) + card_number = inputs.get("number") or inputs.get("card_number") + + # 类型检查 + if card_number is not None and not isinstance(card_number, str): + raise TypeError("number must be a string") + + # 检查必需参数 + if card_number is None: + raise ValueError("number parameter is required") + + try: + # 如果输入是JSON数组或其他非数字字符串,返回该字符串本身(用于数据传递) + # 这种情况发生在DAG设计中类型不匹配时 + if card_number.startswith('[') or card_number.startswith('{'): + # 输入是JSON,直接返回原值(用于传递) + return {"valid": card_number} + + # Remove whitespace from card number + card_number = card_number.replace(" ", "").replace("-", "") + + # Check if card number is all digits + if not card_number.isdigit() or len(card_number) < 13: + return {"valid": "false"} + + # Implement Luhn algorithm + total = 0 + reverse_digits = card_number[::-1] # Reverse the number for easier processing + + for i, digit in enumerate(reverse_digits): + num = int(digit) + if i % 2 == 1: # Every second digit starting from the right (which is first in reversed string) + num *= 2 + if num > 9: + num -= 9 # Equivalent to sum of digits for 2-digit numbers + total += num + + # Check if total is divisible by 10 + is_valid = total % 10 == 0 + return {"valid": "true" if is_valid else "false"} + except Exception as e: + raise RuntimeError(f"Error in luhn_check: {str(e)}") + + def iban_validate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iban = inputs.get("iban") + + # 类型检查 + if iban is not None and not isinstance(iban, str): + raise TypeError("iban must be a string") + + # 检查必需参数 + if iban is None: + raise ValueError("iban parameter is required") + + try: + # Remove whitespace from IBAN + iban = iban.replace(" ", "") + + # Basic length and format check + if not (len(iban) >= 15 and len(iban) <= 34): + return {"valid": "False"} + + if not (iban[:2].isalpha() and iban[2:].isdigit()): + return {"valid": "False"} + + # Move first four characters to the end + rearranged = iban[4:] + iban[:4] + + # Replace letters with numbers (A=10, B=11, ..., Z=35) + numeric_iban = '' + for char in rearranged: + if char.isdigit(): + numeric_iban += char + else: + numeric_iban += str(ord(char.upper()) - ord('A') + 10) + + # Perform modulo 97 check + # Use step-by-step approach for very large numbers + remainder = 0 + for char in numeric_iban: + remainder = (remainder * 10 + int(char)) % 97 + + is_valid = remainder == 1 + return {"valid": "True" if is_valid else "False"} + except Exception as e: + raise RuntimeError(f"Error in iban_validate: {str(e)}") + + def matter_synthesizer(self, inputs): + import hashlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + blueprint = inputs.get("blueprint") + + # 类型检查 + if blueprint is not None and not isinstance(blueprint, str): + raise TypeError("blueprint must be a string") + + try: + # Get blueprint parameter as defined in interface + if blueprint is None: + blueprint = "" + + # Generate a unique item ID based on the blueprint + # This ensures the same blueprint always produces the same item + blueprint_hash = hashlib.sha256(blueprint.encode()).hexdigest()[:16] + + # Create a synthesized item with a deterministic ID based on blueprint + synthesized_item = f"synthesized_item_{blueprint_hash}" + + return {"output_slot": synthesized_item} + except Exception as e: + raise RuntimeError(f"Error in matter_synthesizer: {str(e)}") + + # --- Terminal Implementations --- + def terminal_1(self, inputs): + """ + terminal_1: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 只返回 text_output + - 只输入正确的 slot_b → 只返回 hex_output + - 同时输入正确的 slot_a 和 slot_b → 返回 item_dispenser(物品掉落) + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + # 检查哪些输入被提供了 + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值是否正确(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + expected_a = golden_inputs["slot_a"] + a_valid = str(slot_a) == str(expected_a) + + if has_b and "slot_b" in golden_inputs: + expected_b = golden_inputs["slot_b"] + b_valid = str(slot_b) == str(expected_b) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 item_dispenser + if has_a and has_b: + if a_valid and b_valid: + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 text_output + if has_a and not has_b: + if a_valid: + if "text_output" in golden_outputs: + result["text_output"] = golden_outputs["text_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 hex_output + if has_b and not has_a: + if b_valid: + if "hex_output" in golden_outputs: + result["hex_output"] = golden_outputs["hex_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def terminal_2(self, inputs): + """ + terminal_2: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 text_result + - 同时输入正确的 num1 和 num2 → 返回 hex_result 和 math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + # 检查哪些输入被提供了 + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值是否正确(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + expected_num1 = golden_inputs["num1"] + num1_valid = str(num1) == str(expected_num1) + + if has_num2 and "num2" in golden_inputs: + expected_num2 = golden_inputs["num2"] + num2_valid = str(num2) == str(expected_num2) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 hex_result 和 math_token + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 text_result + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "text_result" in golden_outputs: + result["text_result"] = golden_outputs["text_result"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def logic_terminal(self, inputs): + """ + Logic Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 返回 screen(部分输出) + - 只输入正确的 slot_b → 返回 screen 和 secondary_output + - 同时输入正确的 slot_a 和 slot_b → 返回 screen, secondary_output, item_dispenser + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + a_valid = str(slot_a) == str(golden_inputs["slot_a"]) + + if has_b and "slot_b" in golden_inputs: + b_valid = str(slot_b) == str(golden_inputs["slot_b"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出(包括 item_dispenser) + if has_a and has_b: + if a_valid and b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 screen(部分输出) + if has_a and not has_b: + if a_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 screen 和 secondary_output + if has_b and not has_a: + if b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def math_terminal(self, inputs): + """ + Math Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 result_display + - 同时输入正确的 num1 和 num2 → 返回 result_display, hex_result, math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + num1_valid = str(num1) == str(golden_inputs["num1"]) + + if has_num2 and "num2" in golden_inputs: + num2_valid = str(num2) == str(golden_inputs["num2"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 result_display + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def crypt_terminal(self, inputs): + """ + Encryption Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 plaintext → 返回 status(部分输出) + - 同时输入正确的 plaintext 和 key → 返回 status, encrypted_hex, encryption_chip + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + plaintext = inputs.get("plaintext") + key = inputs.get("key") + + has_plaintext = plaintext is not None and plaintext != "" + has_key = key is not None and key != "" + + # 验证输入值(与 golden values 比较) + plaintext_valid = False + key_valid = False + + if has_plaintext and "plaintext" in golden_inputs: + plaintext_valid = str(plaintext) == str(golden_inputs["plaintext"]) + + if has_key and "key" in golden_inputs: + key_valid = str(key) == str(golden_inputs["key"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_plaintext and has_key: + if plaintext_valid and key_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + if "encrypted_hex" in golden_outputs: + result["encrypted_hex"] = golden_outputs["encrypted_hex"] + if "encryption_chip" in golden_outputs: + result["encryption_chip"] = golden_outputs["encryption_chip"] + return result + else: + incorrect_params = [] + correct_params = [] + if not plaintext_valid: + incorrect_params.append("plaintext") + else: + correct_params.append("plaintext") + if not key_valid: + incorrect_params.append("key") + else: + correct_params.append("key") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 plaintext 且正确 → 返回 status(部分输出) + if has_plaintext and not has_key: + if plaintext_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: plaintext"} + + # 只提供 key 但没有 plaintext + if has_key and not has_plaintext: + return {"error": "plaintext required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + def sequence_terminal(self, inputs): + """ + Sequence Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 sequence → 返回 verification(部分输出) + - 同时输入正确的 sequence 和 checksum → 返回 verification, auth_code, access_card + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + sequence = inputs.get("sequence") + checksum = inputs.get("checksum") + + has_sequence = sequence is not None and sequence != "" + has_checksum = checksum is not None and checksum != "" + + # 验证输入值(与 golden values 比较) + sequence_valid = False + checksum_valid = False + + if has_sequence and "sequence" in golden_inputs: + sequence_valid = str(sequence) == str(golden_inputs["sequence"]) + + if has_checksum and "checksum" in golden_inputs: + checksum_valid = str(checksum) == str(golden_inputs["checksum"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_sequence and has_checksum: + if sequence_valid and checksum_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + if "auth_code" in golden_outputs: + result["auth_code"] = golden_outputs["auth_code"] + if "access_card" in golden_outputs: + result["access_card"] = golden_outputs["access_card"] + return result + else: + incorrect_params = [] + correct_params = [] + if not sequence_valid: + incorrect_params.append("sequence") + else: + correct_params.append("sequence") + if not checksum_valid: + incorrect_params.append("checksum") + else: + correct_params.append("checksum") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 sequence 且正确 → 返回 verification(部分输出) + if has_sequence and not has_checksum: + if sequence_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: sequence"} + + # 只提供 checksum 但没有 sequence + if has_checksum and not has_sequence: + return {"error": "sequence required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + # --- Additional File Tools --- + + def zip_unzip_file(self, inputs): + """ZIP 解压文件工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def zip_unzip_item(self, inputs): + """ZIP 解压道具工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def code_py_exec(self, inputs): + """Python 代码执行工具 + + 这是一个真实执行的工具,在 DAG 生成阶段和运行时评测阶段都会执行代码。 + 输入: code (Python 代码字符串) + 输出: stdout (标准输出,包含执行结果和错误信息) + + 特殊行为: + - 如果代码定义了 main() 函数,会自动调用它 + - 如果执行出错,错误信息会包含在 stdout 中 + """ + code = inputs.get("code", "") + + if not code: + return {"stdout": "Error: No code provided"} + + try: + # 创建一个受限的执行环境 + import io + import sys + + # 捕获标准输出和标准错误 + old_stdout = sys.stdout + old_stderr = sys.stderr + sys.stdout = io.StringIO() + sys.stderr = io.StringIO() + + # 执行代码 + exec_globals = {"__builtins__": __builtins__} + exec_locals = {} + exec(code, exec_globals, exec_locals) + + # 如果定义了 main() 函数,自动调用它 + if 'main' in exec_locals and callable(exec_locals['main']): + exec_locals['main']() + + # 获取输出 + stdout_value = sys.stdout.getvalue() + stderr_value = sys.stderr.getvalue() + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 合并 stdout 和 stderr + output = stdout_value + if stderr_value: + output += ("\n" if output else "") + f"[stderr] {stderr_value}" + + # 如果没有任何输出,尝试返回 result 变量的值 + if not output: + result = exec_locals.get("_result") or exec_locals.get("result") + if result is not None: + output = str(result) + + return {"stdout": output if output else "(no output)"} + + except Exception as e: + # 恢复标准输出和错误输出 + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 返回错误信息 + return {"stdout": f"Error: {type(e).__name__}: {str(e)}"} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-3cee13d8/environment/puzzle/worker.Dockerfile b/tasks/agentescape-25-skeleton-3cee13d8/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-25-skeleton-3cee13d8/environment/puzzle/worker.Dockerfile @@ -0,0 +1,8 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends libseccomp2 && rm -rf /var/lib/apt/lists/* +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY worker.py child.py /app/ +COPY upstream/simulator.py /app/simulator.py +CMD ["uvicorn", "worker:app", "--host", "0.0.0.0", "--port", "8001", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-25-skeleton-3cee13d8/environment/puzzle/worker.py b/tasks/agentescape-25-skeleton-3cee13d8/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3cee13d8/environment/puzzle/worker.py @@ -0,0 +1,73 @@ +"""Stateless Python tool worker. Never receives a scenario or reference values.""" + +import json +import os +import signal +import subprocess +import sys +import tempfile +import threading + +from fastapi import FastAPI +from pydantic import BaseModel, ConfigDict + +app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) +lock = threading.Lock() + + +class Execution(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + code: str + + +@app.get("/health") +def health(): + return {"ok": True} + + +@app.post("/execute") +def execute(request: Execution): + if len(request.code.encode()) > 65536: + return {"stdout": "Error: code exceeds 64 KiB limit"} + with lock, tempfile.TemporaryDirectory(prefix="escape-code-") as directory: + os.chown(directory, 65534, 65534) + with tempfile.TemporaryFile() as output: + process = subprocess.Popen( + [sys.executable, "-I", "/app/child.py"], + stdin=subprocess.PIPE, + stdout=output, + stderr=subprocess.DEVNULL, + cwd=directory, + user=65534, + group=65534, + extra_groups=[], + start_new_session=True, + env={"PATH": "/usr/local/bin:/usr/bin:/bin"}, + ) + try: + process.communicate( + json.dumps({"code": request.code}).encode(), timeout=5 + ) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + return {"stdout": "Error: Python execution timed out"} + finally: + # Also remove children still in the process group after normal exit. + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + output.seek(0) + value = output.read(65537) + if len(value) > 65536 or process.returncode != 0: + return { + "stdout": "Error: Python execution exceeded a resource limit or failed" + } + try: + result = json.loads(value) + if not isinstance(result.get("stdout"), str): + raise ValueError("Invalid worker response") + return result + except (ValueError, AttributeError): + return {"stdout": "Error: Python execution returned invalid output"} diff --git a/tasks/agentescape-25-skeleton-3cee13d8/instruction.md b/tasks/agentescape-25-skeleton-3cee13d8/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3cee13d8/instruction.md @@ -0,0 +1,18 @@ +# Escape the room + +Discover the victory string and submit it with `escape submit-answer`. +Start with `escape observe`. This returns the room, available information, visible entities, and victory node ID. + +Use these commands (JSON responses): + +```sh +escape investigate NODE_ID +escape tool-call NODE_ID --arguments-json '{"parameter": "value"}' +escape use-item NODE_ID --arguments-json '{"parameter": "value"}' +escape submit-answer 'exact victory string' +escape state +``` + +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. + +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. diff --git a/tasks/agentescape-25-skeleton-3cee13d8/solution/oracle.py b/tasks/agentescape-25-skeleton-3cee13d8/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3cee13d8/solution/oracle.py @@ -0,0 +1,133 @@ +"""Reference solver: use trusted inputs, but obtain the answer through public actions.""" + +import json +import urllib.request +from pathlib import Path + + +def http_action(base_url, payload): + request = urllib.request.Request( + base_url + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(request, timeout=30) as response: + return json.load(response) + + +def solve(scenario, act, observe): + nodes = {node["id"]: node for node in scenario["nodes"]} + visible = {entity["id"] for entity in observe["available_entities"]} + solved = set() + seen_outputs = {} + action_count = 0 + + def call(payload): + nonlocal action_count + action_count += 1 + response = act(payload) + visible.update(entity["id"] for entity in response.get("newly_revealed", [])) + if ( + response.get("episode", {}).get("termination_reason") + == "infrastructure_error" + ): + raise RuntimeError("Infrastructure failure") + return response + + for _round in range(len(nodes) + 2): + progress = False + for node_id, node in nodes.items(): + if node_id not in visible or node_id in solved: + continue + # Preserve graph order for data inputs; trigger/drop edges express visibility. + predecessors = [ + edge["source_id"] + for edge in scenario["edges"] + if edge["target_id"] == node_id + and edge["connection_type"] not in ("Item", "Hidden_Item") + ] + if any(pred not in solved for pred in predecessors): + continue + info = call({"action": "investigate", "node_id": node_id}) + if not info.get("ok"): + raise RuntimeError(f"Investigation failed: {node_id}: {info}") + inputs = { + port["name"]: port["value"] + for port in node.get("inputs", []) + if "value" in port + } + if node["type"] == "Tool": + result = call( + {"action": "tool_call", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok") or result.get("output_values", {}).get("error"): + raise RuntimeError(f"Tool failed: {node_id}: {result}") + output = result.get("output_values", {}) + if node.get("template_id") in ("terminal_1", "terminal_2"): + slots = { + port["name"]: inputs[port["name"]] + for port in node["inputs"] + if port["type"] not in ("Item", "Hidden_Item") + and port["name"] in inputs + } + triggers = { + key: value for key, value in inputs.items() if key not in slots + } + for key, value in slots.items(): + partial = call( + { + "action": "tool_call", + "node_id": node_id, + "arguments": {**triggers, key: value}, + } + ) + if partial.get("ok"): + output.update(partial.get("output_values", {})) + # HIDDEN_ITEM tool drops only occur on subsequent investigation. + call({"action": "investigate", "node_id": node_id}) + elif info.get("required_inputs"): + result = call( + {"action": "use_item", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok"): + raise RuntimeError(f"Item failed: {node_id}: {result}") + output = result.get("content") + else: + output = info.get("content") + seen_outputs[node_id] = output + solved.add(node_id) + progress = True + win_id = scenario["metadata"]["win_node_id"] + if win_id in solved and (len(solved) == len(nodes) or not progress): + outputs = seen_outputs[win_id] + if not outputs: + raise RuntimeError(f"Victory node returned no output: {win_id}") + # Upstream grades its first stored output port, independent of response order. + victory_port = next( + port["name"] for port in nodes[win_id]["outputs"] if "value" in port + ) + answer = outputs[victory_port] if isinstance(outputs, dict) else outputs + result = call({"action": "submit_answer", "answer": answer}) + if not result.get("is_win"): + raise RuntimeError(f"Victory submission failed: {result}") + return {"won": True, "actions": action_count, "visited_nodes": len(solved)} + if not progress: + raise RuntimeError(f"No progress: visible={visible}, solved={solved}") + raise RuntimeError("Reference solver exceeded graph traversal limit") + + +if __name__ == "__main__": + import os + + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000") + with urllib.request.urlopen(base + "/observation", timeout=20) as response: + observation = json.load(response) + print( + json.dumps( + solve( + json.loads(Path("/solution/scenario.json").read_text()), + lambda payload: http_action(base, payload), + observation, + ) + ) + ) diff --git a/tasks/agentescape-25-skeleton-3cee13d8/solution/scenario.json b/tasks/agentescape-25-skeleton-3cee13d8/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..bf8d93cf51930b20ced7f9deb0f27358d1a37e86 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3cee13d8/solution/scenario.json @@ -0,0 +1,1652 @@ +{ + "metadata": { + "total_nodes": 25, + "total_edges": 32, + "win_node_id": "calc_modexp", + "win_condition": { + "type": "tool_output", + "node_id": "calc_modexp", + "output_port": "value", + "output_type": "Big_Int", + "description": "Execute BigInt Modular Exponentiation and get the output from port 'value'" + }, + "source_init": { + "source_nodes": [ + "graph_shortest_path", + "zip_unzip_file", + "iban_validate", + "zip_unzip_file_a829", + "calc_bigmul", + "item_11", + "crypto_rsa_decrypt_hex", + "terminal_2", + "calc_inv_mod", + "graph_shortest_path_fb93", + "graph_shortest_path_991f", + "zip_unzip_file_8b4a", + "terminal_2_d217", + "terminal_1", + "text_rotN" + ], + "by_node": { + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": {}, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "iban_validate": { + "node_name": "IBAN Validator", + "node_type": "Tool", + "template_id": "iban_validate", + "init_inputs": { + "iban": { + "type": "Text_Generic", + "description": "IBAN string" + } + }, + "init_outputs": {} + }, + "zip_unzip_file_a829": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "calc_bigmul": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "b": { + "type": "Big_Int", + "description": "Second large integer" + } + }, + "init_outputs": {} + }, + "item_11": { + "node_name": "", + "node_type": "Item", + "template_id": "item_11", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Code_Python", + "description": "Python code" + } + } + }, + "crypto_rsa_decrypt_hex": { + "node_name": "RSA Decrypt", + "node_type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "init_inputs": { + "d": { + "type": "Big_Int", + "description": "Private exponent d" + } + }, + "init_outputs": {} + }, + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": { + "num2": { + "type": "Big_Int", + "description": "Second Number" + } + }, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + } + } + }, + "calc_inv_mod": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "Integer a" + }, + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "graph_shortest_path_fb93": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "Graph JSON file ID" + }, + "src": { + "type": "Text_Generic", + "description": "Source node" + }, + "dst": { + "type": "Text_Generic", + "description": "Destination node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "graph_shortest_path_991f": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "Graph JSON file ID" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "zip_unzip_file_8b4a": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "terminal_2_d217": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": { + "num1": { + "type": "Big_Int", + "description": "First Number" + }, + "num2": { + "type": "Big_Int", + "description": "Second Number" + } + }, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + }, + "math_token": { + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + } + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": { + "slot_a": { + "type": "Text_Generic", + "description": "Input Slot A" + }, + "slot_b": { + "type": "Big_Int", + "description": "Input Slot B" + } + }, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + }, + "item_dispenser": { + "type": "Item", + "description": "Item output when both slots are provided" + } + } + }, + "text_rotN": { + "node_name": "ROT-N Cipher", + "node_type": "Tool", + "template_id": "text_rotN", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text" + }, + "n": { + "type": "Big_Int", + "description": "Shift N" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "graph_shortest_path": { + "init_inputs": {}, + "init_outputs": { + "path": "[\"NodeA\", \"NodeB\", \"NodeC\", \"NodeD\", \"NodeE\"]", + "cost": "854123" + } + }, + "zip_unzip_file": { + "init_inputs": {}, + "init_outputs": { + "files": "extracted_data_749.txt" + } + }, + "iban_validate": { + "init_inputs": { + "iban": "FR7630006000011234567890189" + }, + "init_outputs": {} + }, + "zip_unzip_file_a829": { + "init_inputs": {}, + "init_outputs": { + "files": "config_archive_42.zip" + } + }, + "calc_bigmul": { + "init_inputs": { + "b": "83920194857291029384" + }, + "init_outputs": {} + }, + "item_11": { + "init_inputs": {}, + "init_outputs": { + "content": "def hello():\n print('Hello World')\n return True" + } + }, + "crypto_rsa_decrypt_hex": { + "init_inputs": { + "d": "59283740192837461029" + }, + "init_outputs": {} + }, + "terminal_2": { + "init_inputs": { + "num2": "10293847561029384756" + }, + "init_outputs": { + "text_result": "Calculation sequence finished successfully.", + "hex_result": "b83c2f9a1e0d" + } + }, + "calc_inv_mod": { + "init_inputs": { + "a": "29384710293847561029", + "mod": "104729" + }, + "init_outputs": {} + }, + "graph_shortest_path_fb93": { + "init_inputs": { + "file_id": "graph_network_data.json", + "src": "Node_Alpha", + "dst": "Node_Omega" + }, + "init_outputs": { + "path": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Omega\"]", + "cost": "129384" + } + }, + "graph_shortest_path_991f": { + "init_inputs": { + "file_id": "route_map_49.json" + }, + "init_outputs": { + "path": "[\"A1\", \"B2\", \"C3\", \"D4\", \"E5\"]", + "cost": "509123" + } + }, + "zip_unzip_file_8b4a": { + "init_inputs": { + "zip_id": "encrypted_payload_2.zip" + }, + "init_outputs": { + "files": "unzipped_docs.pdf" + } + }, + "terminal_2_d217": { + "init_inputs": { + "num1": "49283746102938475610", + "num2": "75849302184756291023" + }, + "init_outputs": { + "text_result": "System processed partial instructions.", + "hex_result": "11223344aabbccdd", + "math_token": "Math token useless here" + } + }, + "terminal_1": { + "init_inputs": { + "slot_a": "Insert instruction A", + "slot_b": "84930281928374651029" + }, + "init_outputs": { + "text_output": "Slot A execution completed without errors.", + "hex_output": "ffeeddccbbaa9988", + "item_dispenser": "A mysterious blank card" + } + }, + "text_rotN": { + "init_inputs": { + "text": "The quick brown fox jumps over the lazy dog.", + "n": "39485710293847561029" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You awaken in the sealed sanctum of the forgotten Archmage Thorne. The heavy oak doors have locked behind you, glowing with impenetrable protective wards. To escape this arcane prison, you must navigate a complex web of magical artifacts left behind by the Archmage. Your ultimate goal is to activate The Archmage's Astrolabe, a mythical device capable of shattering the warding spells. The magic in this room is deeply interconnected; you must uncover hidden relics, trace their energies through the sanctum's ancient devices, and carefully weave their powers together to find your way to freedom.", + "narrative_style": "fantasy" + }, + "nodes": [ + { + "id": "calc_modexp", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "854123" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "444603542" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "71678168592093985890550232" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "6717592836223463060460953" + } + ], + "narrative": "This is The Archmage's Astrolabe, the final key to your escape. It requires inputs from The Map of Realms, The Celestial Catalyst, and The Amplifier Crystal to unleash its ultimate power." + }, + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "extracted_data_749.txt" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Omega\"]" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "True" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"NodeA\", \"NodeB\", \"NodeC\", \"NodeD\", \"NodeE\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "854123" + } + ], + "init": { + "inputs": {}, + "outputs": { + "path": "[\"NodeA\", \"NodeB\", \"NodeC\", \"NodeD\", \"NodeE\"]", + "cost": "854123" + } + }, + "narrative": "This is The Map of Realms. It requires inputs from The Sealed Spirit Vault, The Truth Sayer's Mirror, and The Guild Treasury Seal to chart the magical paths." + }, + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "config_archive_42.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "-" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_data_749.txt" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "extracted_data_749.txt" + } + }, + "narrative": "This is The Sealed Spirit Vault. It requires inputs from both The Enchanted Reliquary and The Obsidian Decipherer to release what is trapped inside." + }, + { + "id": "calc_modexp_8c54", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "2" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "854123" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": 1901690262 + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "444603542" + } + ], + "narrative": "This is The Celestial Catalyst. It requires inputs from The Harmony Scale, The Rune Verifier, and The Map of Realms to align the astral energies." + }, + { + "id": "luhn_check", + "name": "Luhn Checker", + "description": "Luhn validity of number string.", + "type": "Tool", + "template_id": "luhn_check", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "number", + "type": "Text_Generic", + "description": "Number string", + "value": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Omega\"]" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Omega\"]" + } + ], + "narrative": "This is The Truth Sayer's Mirror. It requires input from The Leyline Chart to reflect the true path." + }, + { + "id": "iban_validate", + "name": "IBAN Validator", + "description": "IBAN checksum validation.", + "type": "Tool", + "template_id": "iban_validate", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "iban", + "type": "Text_Generic", + "description": "IBAN string", + "value": "FR7630006000011234567890189" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "True" + } + ], + "init": { + "inputs": { + "iban": "FR7630006000011234567890189" + }, + "outputs": {} + }, + "narrative": "The Guild Treasury Seal is an intricate wax stamp used by the ancient merchant guilds." + }, + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "71678168592093985890550232" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": 1901690262 + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "2" + } + ], + "narrative": "This is The Harmony Scale. It requires inputs from both The Rune Verifier and The Amplifier Crystal to balance the magical weights." + }, + { + "id": "checksum_crc32", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "81afa410" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "71597d96" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 1901690262 + } + ], + "narrative": "This is The Rune Verifier. It requires input from The Glyph Authenticator to confirm the ancient symbols." + }, + { + "id": "zip_unzip_item", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_item", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "config_archive_42.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "(no output)" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip" + } + ], + "narrative": "This is The Locked Pandora's Box. It requires inputs from both The Spellweaver's Loom and The Enchanted Reliquary to spring open." + }, + { + "id": "code_py_exec", + "name": "Python Executor", + "description": "Run limited Python: only safe builtins.", + "type": "Tool", + "template_id": "code_py_exec", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "code", + "type": "Code_Python", + "description": "Python code", + "value": "def hello():\n print('Hello World')\n return True" + } + ], + "outputs": [ + { + "name": "stdout", + "type": "Text_Generic", + "description": "Standard Output (includes errors if any)", + "value": "(no output)" + } + ], + "narrative": "This is The Spellweaver's Loom. It requires input from The Ancient Spell Scroll to weave its magical logic." + }, + { + "id": "zip_unzip_file_a829", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "unzipped_docs.pdf" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "(no output)" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "config_archive_42.zip" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "config_archive_42.zip" + } + }, + "narrative": "This is The Enchanted Reliquary. It requires inputs from both The Spellweaver's Loom and The Bound Casket to unveil its secrets." + }, + { + "id": "calc_bigmul", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "854123" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "83920194857291029384" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "71678168592093985890550232" + } + ], + "init": { + "inputs": { + "b": "83920194857291029384" + }, + "outputs": {} + }, + "narrative": "This is The Amplifier Crystal. It requires input from The Map of Realms to magnify its magical properties." + }, + { + "id": "item_11", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_11", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Code_Python", + "description": "Python code", + "value": "def hello():\n print('Hello World')\n return True" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "def hello():\n print('Hello World')\n return True" + } + }, + "narrative": "The Ancient Spell Scroll is a dusty parchment containing forgotten incantations." + }, + { + "id": "checksum_crc32_de91", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "b83c2f9a1e0d" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "81afa410" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 2175771664 + } + ], + "narrative": "This is The Glyph Authenticator. It requires input from The Crystal Ball to decipher the arcane marks." + }, + { + "id": "crypto_rsa_decrypt_hex", + "name": "RSA Decrypt", + "description": "RSA decrypt (hex cipher) with n,d (decimal).", + "type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex_cipher", + "type": "Hex_String", + "description": "Ciphertext (Hex)", + "value": "81afa410" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Modulus n", + "value": "26021" + }, + { + "name": "d", + "type": "Big_Int", + "description": "Private exponent d", + "value": "59283740192837461029" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decrypted text", + "value": "-" + } + ], + "init": { + "inputs": { + "d": "59283740192837461029" + }, + "outputs": {} + }, + "narrative": "This is The Obsidian Decipherer. It requires inputs from both The Glyph Authenticator and The Inversion Pendulum to break the protective curses." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "The Mystical Gem is a glowing stone pulsing with dormant energy." + }, + { + "id": "terminal_2", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this terminal" + }, + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "509123" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "10293847561029384756" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Calculation sequence finished successfully." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "b83c2f9a1e0d" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": { + "num2": "10293847561029384756" + }, + "outputs": { + "text_result": "Calculation sequence finished successfully.", + "hex_result": "b83c2f9a1e0d" + } + }, + "narrative": "This is The Crystal Ball. It requires input from The Pathfinder's Compass to reveal its visions." + }, + { + "id": "calc_inv_mod", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "29384710293847561029" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "104729" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "26021" + } + ], + "init": { + "inputs": { + "a": "29384710293847561029", + "mod": "104729" + }, + "outputs": {} + }, + "narrative": "The Inversion Pendulum is a magical artifact that swings backwards in time." + }, + { + "id": "graph_shortest_path_fb93", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "graph_network_data.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Node_Alpha" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Node_Omega" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Omega\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "129384" + } + ], + "init": { + "inputs": { + "file_id": "graph_network_data.json", + "src": "Node_Alpha", + "dst": "Node_Omega" + }, + "outputs": { + "path": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Omega\"]", + "cost": "129384" + } + }, + "narrative": "The Leyline Chart is an old parchment detailing magical leylines across the kingdom." + }, + { + "id": "graph_shortest_path_991f", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "route_map_49.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Gur dhvpx oebja sbk whzcf bire gur ynml qbt." + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Slot A execution completed without errors." + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"A1\", \"B2\", \"C3\", \"D4\", \"E5\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "509123" + } + ], + "init": { + "inputs": { + "file_id": "route_map_49.json" + }, + "outputs": { + "path": "[\"A1\", \"B2\", \"C3\", \"D4\", \"E5\"]", + "cost": "509123" + } + }, + "narrative": "This is The Pathfinder's Compass. It requires inputs from both The Oracle's Pedestal and The Shifting Cypher Wheel to point the way." + }, + { + "id": "zip_unzip_file_8b4a", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "encrypted_payload_2.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "System processed partial instructions." + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "unzipped_docs.pdf" + } + ], + "init": { + "inputs": { + "zip_id": "encrypted_payload_2.zip" + }, + "outputs": { + "files": "unzipped_docs.pdf" + } + }, + "narrative": "This is The Bound Casket. It requires input from The Seer's Basin to loosen its magical bindings." + }, + { + "id": "terminal_2_d217", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this terminal" + }, + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "49283746102938475610" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "75849302184756291023" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "System processed partial instructions." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "11223344aabbccdd" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "Math token useless here" + } + ], + "init": { + "inputs": { + "num1": "49283746102938475610", + "num2": "75849302184756291023" + }, + "outputs": { + "text_result": "System processed partial instructions.", + "hex_result": "11223344aabbccdd", + "math_token": "Math token useless here" + } + }, + "narrative": "The Seer's Basin is a silver bowl filled with shimmering water for scrying." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "Insert instruction A" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "84930281928374651029" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Slot A execution completed without errors." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "ffeeddccbbaa9988" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided", + "value": "A mysterious blank card" + } + ], + "init": { + "inputs": { + "slot_a": "Insert instruction A", + "slot_b": "84930281928374651029" + }, + "outputs": { + "text_output": "Slot A execution completed without errors.", + "hex_output": "ffeeddccbbaa9988", + "item_dispenser": "A mysterious blank card" + } + }, + "narrative": "The Oracle's Pedestal is a stone structure carved with ancient prophecy marks." + }, + { + "id": "text_rotN", + "name": "ROT-N Cipher", + "description": "Caesar shift by N.", + "type": "Tool", + "template_id": "text_rotN", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "The quick brown fox jumps over the lazy dog." + }, + { + "name": "n", + "type": "Big_Int", + "description": "Shift N", + "value": "39485710293847561029" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Rotated text", + "value": "Gur dhvpx oebja sbk whzcf bire gur ynml qbt." + } + ], + "init": { + "inputs": { + "text": "The quick brown fox jumps over the lazy dog.", + "n": "39485710293847561029" + }, + "outputs": {} + }, + "narrative": "The Shifting Cypher Wheel is a wooden contraption with shifting runic alphabets." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "The Pocket Sundial is a brass timepiece etched with temporal magic." + } + ], + "edges": [ + { + "source_id": "graph_shortest_path", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "base" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "calc_modexp_8c54", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "exp" + }, + { + "source_id": "luhn_check", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "src" + }, + { + "source_id": "iban_validate", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "dst" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_modexp_8c54", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "base" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "b" + }, + { + "source_id": "zip_unzip_item", + "target_id": "iban_validate", + "connection_type": "Item", + "source_port": "item", + "target_port": "trigger_item" + }, + { + "source_id": "code_py_exec", + "target_id": "zip_unzip_item", + "connection_type": "Text_Generic", + "source_port": "stdout", + "target_port": "password" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp_8c54", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "mod" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_modexp_8c54", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "exp" + }, + { + "source_id": "zip_unzip_file_a829", + "target_id": "zip_unzip_item", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "calc_bigmul", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "mod" + }, + { + "source_id": "calc_bigmul", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "a" + }, + { + "source_id": "item_11", + "target_id": "code_py_exec", + "connection_type": "Code_Python", + "source_port": "content", + "target_port": "code" + }, + { + "source_id": "code_py_exec", + "target_id": "zip_unzip_file_a829", + "connection_type": "Text_Generic", + "source_port": "stdout", + "target_port": "password" + }, + { + "source_id": "checksum_crc32_de91", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "zip_unzip_file_a829", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "a" + }, + { + "source_id": "crypto_rsa_decrypt_hex", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "password" + }, + { + "source_id": "checksum_crc32_de91", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_cipher" + }, + { + "source_id": "item_8", + "target_id": "luhn_check", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "terminal_2", + "target_id": "item_11", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "source_tool" + }, + { + "source_id": "calc_inv_mod", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "n" + }, + { + "source_id": "graph_shortest_path_fb93", + "target_id": "luhn_check", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "number" + }, + { + "source_id": "terminal_2", + "target_id": "checksum_crc32_de91", + "connection_type": "Hex_String", + "source_port": "hex_result", + "target_port": "hex" + }, + { + "source_id": "graph_shortest_path_991f", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "num1" + }, + { + "source_id": "zip_unzip_file_8b4a", + "target_id": "zip_unzip_file_a829", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "terminal_2_d217", + "target_id": "zip_unzip_file_8b4a", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "password" + }, + { + "source_id": "terminal_1", + "target_id": "graph_shortest_path_991f", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "dst" + }, + { + "source_id": "text_rotN", + "target_id": "graph_shortest_path_991f", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "src" + }, + { + "source_id": "item_16", + "target_id": "checksum_crc32_de91", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-3cee13d8/solution/solve.sh b/tasks/agentescape-25-skeleton-3cee13d8/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3cee13d8/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-25-skeleton-3cee13d8/task.toml b/tasks/agentescape-25-skeleton-3cee13d8/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5868befffccfedb42f56c56f943e03cda6dda8c7 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3cee13d8/task.toml @@ -0,0 +1,38 @@ +schema_version = "1.4" +source = "https://github.com/AGI-Eval-Official/Repo-of-AgentEscapeBench" + +[[artifacts]] +source = "/evidence/final.json" +service = "puzzle" + +[[artifacts]] +source = "/evidence/trace.jsonl" +service = "puzzle" + +[task] +name = "edbeeching/agentescape-25-skeleton-3cee13d8" +version = "0.1.0" + +[metadata] +difficulty = 25 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "fbd59462282c59805f1e7f61d6678b7aa2d71c92b494fd9b76b72eca49bb8cfa" +protocol = "harbor-cli-action-budget-v1" +max_actions = 500 + +[agent] +timeout_sec = 1200 + +[environment] +build_timeout_sec = 900 +cpus = 1 +memory_mb = 1024 + +[verifier] +environment_mode = "separate" +timeout_sec = 60 + +[[verifier.collect]] +service = "puzzle" +command = "python -I /app/export.py" +timeout_sec = 15 diff --git a/tasks/agentescape-25-skeleton-3cee13d8/tests/Dockerfile b/tasks/agentescape-25-skeleton-3cee13d8/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-25-skeleton-3cee13d8/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-25-skeleton-3cee13d8/tests/expected.json b/tasks/agentescape-25-skeleton-3cee13d8/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..bfe1385b8544c090ec35f5eca510980d9d309ab9 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3cee13d8/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "fbd59462282c59805f1e7f61d6678b7aa2d71c92b494fd9b76b72eca49bb8cfa", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-3cee13d8/tests/grade.py b/tasks/agentescape-25-skeleton-3cee13d8/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3cee13d8/tests/grade.py @@ -0,0 +1,21 @@ +"""Grade only Harbor-collected sidecar evidence in a fresh verifier container.""" + +import json +from pathlib import Path + +expected = json.loads(Path("/tests/expected.json").read_text()) +state = json.loads(Path("/evidence/final.json").read_text()) +assert state["collected_from_live_service"] is True, "Missing trusted service export" +assert state["scenario_sha256"] == expected["scenario_sha256"], ( + "Wrong scenario evidence" +) +assert state["max_actions"] == expected["max_actions"], "Wrong budget" +assert type(state["won"]) is bool +assert 0 <= state["action_count"] <= state["max_actions"] +assert state["termination_reason"] != "infrastructure_error", ( + "Infrastructure failure is not a puzzle failure" +) +assert not state["won"] or state["termination_reason"] == "success" +Path("/logs/verifier").mkdir(parents=True, exist_ok=True) +Path("/logs/verifier/state.json").write_text(json.dumps(state, indent=2)) +Path("/logs/verifier/reward.txt").write_text("1.0\n" if state["won"] else "0.0\n") diff --git a/tasks/agentescape-25-skeleton-3cee13d8/tests/test.sh b/tasks/agentescape-25-skeleton-3cee13d8/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-25-skeleton-3cee13d8/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-25-skeleton-4b3614c7/environment/Dockerfile b/tasks/agentescape-25-skeleton-4b3614c7/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-25-skeleton-4b3614c7/environment/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-25-skeleton-4b3614c7/environment/agent/Dockerfile b/tasks/agentescape-25-skeleton-4b3614c7/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-25-skeleton-4b3614c7/environment/agent/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-25-skeleton-4b3614c7/environment/agent/cli.py b/tasks/agentescape-25-skeleton-4b3614c7/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-25-skeleton-4b3614c7/environment/agent/cli.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Public agent client; depends only on the Python standard library.""" + +import argparse +import json +import os +import sys +import urllib.error +import urllib.request + + +def main(): + parser = argparse.ArgumentParser(description="Interact with the escape room") + parser.add_argument( + "action", + choices=[ + "observe", + "state", + "investigate", + "tool-call", + "use-item", + "submit-answer", + ], + ) + parser.add_argument("value", nargs="?") + parser.add_argument("--arguments-json", default="{}") + args = parser.parse_args() + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000").rstrip("/") + if args.action in ("observe", "state"): + request = urllib.request.Request( + base + ("/observation" if args.action == "observe" else "/state") + ) + else: + if args.value is None: + parser.error("node ID or answer is required") + payload = {"action": args.action.replace("-", "_")} + if args.action == "submit-answer": + payload["answer"] = args.value + else: + payload["node_id"] = args.value + if args.action in ("tool-call", "use-item"): + payload["arguments"] = json.loads(args.arguments_json) + request = urllib.request.Request( + base + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=30) as response: + print(json.dumps(json.load(response), ensure_ascii=False)) + except (urllib.error.URLError, ValueError) as exc: + print(json.dumps({"ok": False, "error": str(exc)})) + sys.exit(2) + + +if __name__ == "__main__": + main() diff --git a/tasks/agentescape-25-skeleton-4b3614c7/environment/docker-compose.yaml b/tasks/agentescape-25-skeleton-4b3614c7/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..821379288a75bfa1487c010092e2ac8ad9c2d32c --- /dev/null +++ b/tasks/agentescape-25-skeleton-4b3614c7/environment/docker-compose.yaml @@ -0,0 +1,50 @@ +services: + main: + image: agentescapebench-agent:aab05a0a9ddb + build: + context: ./agent + networks: [default, puzzle] + security_opt: [no-new-privileges:true] + depends_on: + puzzle: + condition: service_healthy + puzzle: + image: agentescapebench-puzzle:agentescape-25-skeleton-4b3614c7-aab05a0a9ddb + build: + context: ./puzzle + networks: [puzzle, execution] + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 512m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"] + interval: 1s + timeout: 3s + retries: 30 + depends_on: + worker: + condition: service_healthy + worker: + image: agentescapebench-worker:aab05a0a9ddb + build: + context: ./puzzle + dockerfile: worker.Dockerfile + networks: [execution] + read_only: true + tmpfs: ["/tmp:size=64m,mode=1777"] + cap_drop: [ALL] + cap_add: [SETUID, SETGID, KILL, CHOWN, DAC_OVERRIDE] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 384m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8001/health')"] + interval: 1s + timeout: 3s + retries: 30 +networks: + puzzle: + internal: true + execution: + internal: true diff --git a/tasks/agentescape-25-skeleton-4b3614c7/environment/puzzle/Dockerfile b/tasks/agentescape-25-skeleton-4b3614c7/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-25-skeleton-4b3614c7/environment/puzzle/Dockerfile @@ -0,0 +1,9 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY upstream /app/upstream +COPY service.py export.py /app/ +COPY scenario.json /private/scenario.json +ENV SCENARIO_PATH=/private/scenario.json EVIDENCE_DIR=/evidence WORKER_URL=http://worker:8001 MAX_ACTIONS=500 +CMD ["uvicorn", "service:create_app", "--factory", "--host", "0.0.0.0", "--port", "8000", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-25-skeleton-4b3614c7/environment/puzzle/child.py b/tasks/agentescape-25-skeleton-4b3614c7/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-25-skeleton-4b3614c7/environment/puzzle/child.py @@ -0,0 +1,59 @@ +"""Run the original Python tool after reducing privileges and blocking networking.""" + +import ctypes +import errno +import json +import resource +import sys + +resource.setrlimit(resource.RLIMIT_CPU, (3, 3)) +resource.setrlimit(resource.RLIMIT_AS, (256 * 1024 * 1024, 256 * 1024 * 1024)) +resource.setrlimit(resource.RLIMIT_FSIZE, (65536, 65536)) +resource.setrlimit(resource.RLIMIT_NOFILE, (32, 32)) +resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + +# Filters survive fork/exec. Fail closed if seccomp cannot be loaded. +lib = ctypes.CDLL("libseccomp.so.2", use_errno=True) +lib.seccomp_init.argtypes = [ctypes.c_uint32] +lib.seccomp_init.restype = ctypes.c_void_p +lib.seccomp_rule_add.argtypes = [ + ctypes.c_void_p, + ctypes.c_uint32, + ctypes.c_int, + ctypes.c_uint, +] +lib.seccomp_syscall_resolve_name.argtypes = [ctypes.c_char_p] +lib.seccomp_load.argtypes = [ctypes.c_void_p] +lib.seccomp_release.argtypes = [ctypes.c_void_p] +ctx = lib.seccomp_init(0x7FFF0000) # SCMP_ACT_ALLOW +if not ctx: + raise RuntimeError("Cannot initialize execution isolation") +try: + for name in ( + "socket", + "socketpair", + "connect", + "ptrace", + "process_vm_readv", + "process_vm_writev", + "mount", + "unshare", + "setns", + "bpf", + ): + number = lib.seccomp_syscall_resolve_name(name.encode()) + if ( + number >= 0 + and lib.seccomp_rule_add(ctx, 0x00050000 | errno.EPERM, number, 0) != 0 + ): + raise RuntimeError("Cannot install execution isolation rule") + if lib.seccomp_load(ctx) != 0: + raise RuntimeError("Cannot activate execution isolation") +finally: + lib.seccomp_release(ctx) + +sys.path.insert(0, "/app") +from simulator import ToolSimulator # noqa: E402 + +request = json.load(sys.stdin) +json.dump(ToolSimulator().code_py_exec(request), sys.stdout) diff --git a/tasks/agentescape-25-skeleton-4b3614c7/environment/puzzle/export.py b/tasks/agentescape-25-skeleton-4b3614c7/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-25-skeleton-4b3614c7/environment/puzzle/export.py @@ -0,0 +1,13 @@ +"""Harbor invokes this inside the puzzle service after stopping the agent.""" + +import json +import pathlib +import urllib.request + +with urllib.request.urlopen("http://127.0.0.1:8000/state", timeout=10) as response: + state = json.load(response) +state["collected_from_live_service"] = True +target = pathlib.Path("/evidence/final.json") +temp = target.with_suffix(".tmp") +temp.write_text(json.dumps(state)) +temp.replace(target) diff --git a/tasks/agentescape-25-skeleton-4b3614c7/environment/puzzle/requirements.txt b/tasks/agentescape-25-skeleton-4b3614c7/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-25-skeleton-4b3614c7/environment/puzzle/requirements.txt @@ -0,0 +1,57 @@ +annotated-doc==0.0.5 + # via fastapi +annotated-types==0.8.0 + # via pydantic +anyio==4.16.0 + # via starlette +certifi==2026.10.23 + # via requests +cffi==2.1.1 ; platform_python_implementation != 'PyPy' + # via cryptography +charset-normalizer==3.5.2 + # via requests +click==8.5.0 + # via uvicorn +cryptography==50.0.2 + # via agentescapebench-harbor +fastapi==0.162.0 + # via agentescapebench-harbor +h11==0.16.0 + # via uvicorn +idna==3.20 + # via + # anyio + # requests +opentelemetry-api==1.45.2 + # via fastapi +pycparser==3.12 ; implementation_name != 'PyPy' and platform_python_implementation != 'PyPy' + # via cffi +pydantic==2.14.2 + # via + # agentescapebench-harbor + # fastapi +pydantic-core==2.50.2 + # via pydantic +pytz==2025.2 + # via agentescapebench-harbor +requests==2.34.2 + # via agentescapebench-harbor +starlette==1.10.0 + # via fastapi +typing-extensions==4.16.0 + # via + # anyio + # fastapi + # opentelemetry-api + # pydantic + # pydantic-core + # starlette + # typing-inspection +typing-inspection==0.4.4 + # via + # fastapi + # pydantic +urllib3==2.8.0 + # via requests +uvicorn==0.54.0 + # via agentescapebench-harbor diff --git a/tasks/agentescape-25-skeleton-4b3614c7/environment/puzzle/scenario.json b/tasks/agentescape-25-skeleton-4b3614c7/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..917583fa6002729fa0865b96796790ab2bc534ca --- /dev/null +++ b/tasks/agentescape-25-skeleton-4b3614c7/environment/puzzle/scenario.json @@ -0,0 +1,1592 @@ +{ + "metadata": { + "total_nodes": 25, + "total_edges": 35, + "win_node_id": "item_2", + "win_condition": { + "type": "item_content", + "node_id": "item_2", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_2", + "terminal_1", + "calc_modexp_be8b", + "terminal_1_bd51", + "graph_shortest_path", + "zip_unzip_file", + "time_convert", + "calc_gcd_13c6", + "terminal_1_3e9d", + "base64_encode", + "zip_unzip_file_6880", + "container_1", + "hash_sha256", + "calc_modexp_7f52", + "calc_bigmul_362a" + ], + "by_node": { + "item_2": { + "node_name": "", + "node_type": "Item", + "template_id": "item_2", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Text_Generic", + "description": "The text" + } + } + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": {}, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + }, + "item_dispenser": { + "type": "Item", + "description": "Item output when both slots are provided" + } + } + }, + "calc_modexp_be8b": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "exp": { + "type": "Big_Int", + "description": "Exponent" + } + }, + "init_outputs": {} + }, + "terminal_1_bd51": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": { + "slot_a": { + "type": "Text_Generic", + "description": "Input Slot A" + } + }, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + } + } + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": {}, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "time_convert": { + "node_name": "Timezone Converter", + "node_type": "Tool", + "template_id": "time_convert", + "init_inputs": { + "iso": { + "type": "Text_Generic", + "description": "ISO Timestamp" + } + }, + "init_outputs": {} + }, + "calc_gcd_13c6": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First integer" + } + }, + "init_outputs": {} + }, + "terminal_1_3e9d": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": { + "slot_a": { + "type": "Text_Generic", + "description": "Input Slot A" + } + }, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + }, + "item_dispenser": { + "type": "Item", + "description": "Item output when both slots are provided" + } + } + }, + "base64_encode": { + "node_name": "Base64 Encoder", + "node_type": "Tool", + "template_id": "base64_encode", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex bytes" + } + }, + "init_outputs": {} + }, + "zip_unzip_file_6880": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + }, + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "container_1": { + "node_name": "", + "node_type": "Item", + "template_id": "container_1", + "init_inputs": { + "fingerprint_input": { + "type": "Hex_String", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + }, + "hash_sha256": { + "node_name": "SHA-256 Hasher", + "node_type": "Tool", + "template_id": "hash_sha256", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text to hash" + } + }, + "init_outputs": {} + }, + "calc_modexp_7f52": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "base": { + "type": "Big_Int", + "description": "Base" + }, + "exp": { + "type": "Big_Int", + "description": "Exponent" + }, + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "calc_bigmul_362a": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First large integer" + }, + "b": { + "type": "Big_Int", + "description": "Second large integer" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "item_2": { + "init_inputs": {}, + "init_outputs": { + "content": "Mega Millions: 07, 14, 23, 38, 49 MB 11" + } + }, + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "Terminal 1 system initialized successfully.", + "hex_output": "1a2b3c4d5e6f7a8b", + "item_dispenser": "Dispensed matter synthesizer blueprint" + } + }, + "calc_modexp_be8b": { + "init_inputs": { + "exp": "384759283746501928374" + }, + "init_outputs": {} + }, + "terminal_1_bd51": { + "init_inputs": { + "slot_a": "Input text sequence for terminal bd51." + }, + "init_outputs": { + "text_output": "America/New_York", + "hex_output": "aabbccddeeff0011" + } + }, + "graph_shortest_path": { + "init_inputs": {}, + "init_outputs": { + "path": "[\"America/New_York\", \"node_beta\", \"node_gamma\", \"node_delta\", \"Europe/Paris\"]", + "cost": "450210" + } + }, + "zip_unzip_file": { + "init_inputs": {}, + "init_outputs": { + "files": "extracted_data_from_zip.zip" + } + }, + "time_convert": { + "init_inputs": { + "iso": "2023-11-20T08:30:00Z" + }, + "init_outputs": {} + }, + "calc_gcd_13c6": { + "init_inputs": { + "a": "73849501827364519283" + }, + "init_outputs": {} + }, + "terminal_1_3e9d": { + "init_inputs": { + "slot_a": "Terminal 3e9d configuration input data." + }, + "init_outputs": { + "text_output": "Europe/Paris", + "hex_output": "2233445566778899", + "item_dispenser": "Timezone configuration module item" + } + }, + "base64_encode": { + "init_inputs": { + "hex": "48656c6c6f576f726c64" + }, + "init_outputs": {} + }, + "zip_unzip_file_6880": { + "init_inputs": { + "zip_id": "secure_archive_6880.zip", + "password": "SuperStrongPassword2023!" + }, + "init_outputs": { + "files": "decrypted_files_6880_out.zip" + } + }, + "container_1": { + "init_inputs": { + "fingerprint_input": "deadbeef1234567890abcdef" + }, + "init_outputs": {} + }, + "hash_sha256": { + "init_inputs": { + "text": "Text payload to be hashed by SHA-256." + }, + "init_outputs": {} + }, + "calc_modexp_7f52": { + "init_inputs": { + "base": "32", + "exp": "56473829104758693021", + "mod": "999983" + }, + "init_outputs": {} + }, + "calc_bigmul_362a": { + "init_inputs": { + "a": "12938475610293847561", + "b": "98761234509876123450" + }, + "init_outputs": {} + } + }, + "intro_narrative": "The world ended not with a bang, but with a sudden, silent digital collapse. You are a Scavenger exploring the ruins of Outpost 31, a legendary pre-collapse bunker rumored to hold the 'Genesis Code'—humanity's last chance to restore the biosphere. The bunker is a tangled mess of interconnected mainframes, biometric locks, and archaic processors. The air is thick with dust, and the only light comes from the faint amber glow of surviving command terminals. Your objective is clear: navigate this labyrinth of forgotten technology, restore the power flow between the core systems, and ultimately unlock the final cache containing the Genesis Code. The systems here are heavily interdependent. You'll need to trace the physical and digital paths, bringing offline systems back to life one by one. Time is running out as the bunker's backup generators begin to fail. Connect the right modules, synthesize the necessary tools, and unravel the post-apocalyptic web to secure the future.", + "narrative_style": "post_apocalyptic" + }, + "nodes": [ + { + "id": "item_2", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_2", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "Text_Generic", + "description": "The text", + "value": "Mega Millions: 07, 14, 23, 38, 49 MB 11" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "Mega Millions: 07, 14, 23, 38, 49 MB 11" + } + }, + "narrative": "The final cache, a secure container meant to hold humanity's last hope." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by", + "value": "synthesized_item_0adc51cecfb6d99d" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A sealed time capsule, surprisingly intact despite the devastation." + }, + { + "id": "matter_synthesizer", + "name": "Matter Synthesizer", + "description": "Synthesizes physical objects from data blueprints.", + "type": "Tool", + "template_id": "matter_synthesizer", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "blueprint", + "type": "Text_Generic", + "description": "Object Blueprint", + "value": "Terminal 1 system initialized successfully." + } + ], + "outputs": [ + { + "name": "output_slot", + "type": "Item", + "description": "Synthesized Object", + "value": "synthesized_item_0adc51cecfb6d99d" + } + ], + "narrative": "This is the automated fabricator. It requires input from the main command terminal to start printing." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "2023-11-20T09:30:00+01:00" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "0" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Terminal 1 system initialized successfully." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "1a2b3c4d5e6f7a8b" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided", + "value": "Dispensed matter synthesizer blueprint" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "Terminal 1 system initialized successfully.", + "hex_output": "1a2b3c4d5e6f7a8b", + "item_dispenser": "Dispensed matter synthesizer blueprint" + } + }, + "narrative": "This is the main command terminal. It requires inputs from both the primary core processor and the temporal synchronizer to grant access." + }, + { + "id": "calc_modexp", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "0" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": 699284493 + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "1" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "0" + } + ], + "narrative": "This is the primary core processor. It requires inputs from the secondary core processor, the auxiliary core processor, and the primary data validator to fully initialize." + }, + { + "id": "calc_modexp_be8b", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": 584731264 + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "384759283746501928374" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "3" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "1" + } + ], + "init": { + "inputs": { + "exp": "384759283746501928374" + }, + "outputs": {} + }, + "narrative": "This is the secondary core processor. It requires inputs from both the signal multiplier and the secondary data validator." + }, + { + "id": "terminal_1_bd51", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "Input text sequence for terminal bd51." + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "3" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "America/New_York" + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "aabbccddeeff0011" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": { + "slot_a": "Input text sequence for terminal bd51." + }, + "outputs": { + "text_output": "America/New_York", + "hex_output": "aabbccddeeff0011" + } + }, + "narrative": "This is the navigation terminal. It requires input from the frequency harmonizer to lock onto safe coordinates." + }, + { + "id": "calc_bigmul", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "3" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "1" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "3" + } + ], + "narrative": "This is the signal multiplier. It requires inputs from both the secondary frequency harmonizer and the frequency harmonizer to boost the transmission." + }, + { + "id": "calc_modexp_c5c9", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "450210" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": 699284493 + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "3" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "0" + } + ], + "narrative": "This is the auxiliary core processor. It requires inputs from the route mapping system, the frequency harmonizer, and the primary data validator." + }, + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "extracted_data_from_zip.zip" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "America/New_York" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "2023-11-20T09:30:00+01:00" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"America/New_York\", \"node_beta\", \"node_gamma\", \"node_delta\", \"Europe/Paris\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "450210" + } + ], + "init": { + "inputs": {}, + "outputs": { + "path": "[\"America/New_York\", \"node_beta\", \"node_gamma\", \"node_delta\", \"Europe/Paris\"]", + "cost": "450210" + } + }, + "narrative": "This is the route mapping system. It requires inputs from the navigation terminal, the archive extractor, and the temporal synchronizer to chart a safe path." + }, + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": 699284493 + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "287040" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "3" + } + ], + "narrative": "This is the frequency harmonizer. It requires inputs from both the primary data validator and the environmental processor to calibrate the signals." + }, + { + "id": "checksum_crc32", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "bdb572feafdc3dc740bc8675ec4e351b1ec0225b70941912a1119270346ba06b" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "29ae3c0d" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 699284493 + } + ], + "narrative": "This is the primary data validator. It requires input from the cryptographic hasher to ensure data integrity." + }, + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "decrypted_files_6880_out.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "SGVsbG9Xb3JsZA==" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_data_from_zip.zip" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "extracted_data_from_zip.zip" + } + }, + "narrative": "This is the archive extractor. It requires inputs from both the format converter and the initial archive extractor to decompress the data." + }, + { + "id": "time_convert", + "name": "Timezone Converter", + "description": "Convert ISO time between timezones.", + "type": "Tool", + "template_id": "time_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "iso", + "type": "Text_Generic", + "description": "ISO Timestamp", + "value": "2023-11-20T08:30:00Z" + }, + { + "name": "from_tz", + "type": "Text_Generic", + "description": "From Timezone", + "value": "America/New_York" + }, + { + "name": "to_tz", + "type": "Text_Generic", + "description": "To Timezone", + "value": "Europe/Paris" + } + ], + "outputs": [ + { + "name": "iso", + "type": "Text_Generic", + "description": "Converted ISO Timestamp", + "value": "2023-11-20T09:30:00+01:00" + } + ], + "init": { + "inputs": { + "iso": "2023-11-20T08:30:00Z" + }, + "outputs": {} + }, + "narrative": "This is the temporal synchronizer. It requires inputs from both the backup terminal and the navigation terminal to align system clocks." + }, + { + "id": "zip_unzip_item", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_item", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "extracted_data_from_zip.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "SGVsbG9Xb3JsZA==" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip" + } + ], + "narrative": "This is the payload extractor. It requires inputs from both the archive extractor and the format converter to retrieve digital stasis objects." + }, + { + "id": "calc_gcd_13c6", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "73849501827364519283" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": 699284493 + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "init": { + "inputs": { + "a": "73849501827364519283" + }, + "outputs": {} + }, + "narrative": "This is the secondary frequency harmonizer. It requires input from the primary data validator to stabilize its resonance." + }, + { + "id": "checksum_crc32_a581", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "29ae3c0d" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "22da4a80" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 584731264 + } + ], + "narrative": "This is the secondary data validator. It requires input from the primary data validator to double-check the diagnostics." + }, + { + "id": "terminal_1_3e9d", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "Terminal 3e9d configuration input data." + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "1277819823948543275261250183787917405450" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Europe/Paris" + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "2233445566778899" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided", + "value": "Timezone configuration module item" + } + ], + "init": { + "inputs": { + "slot_a": "Terminal 3e9d configuration input data." + }, + "outputs": { + "text_output": "Europe/Paris", + "hex_output": "2233445566778899", + "item_dispenser": "Timezone configuration module item" + } + }, + "narrative": "This is the backup terminal. It requires input from the power multiplier to boot up its systems." + }, + { + "id": "base64_encode", + "name": "Base64 Encoder", + "description": "Encode hex bytes to base64.", + "type": "Tool", + "template_id": "base64_encode", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "hex", + "type": "Hex_String", + "description": "Hex bytes", + "value": "48656c6c6f576f726c64" + } + ], + "outputs": [ + { + "name": "b64", + "type": "Text_Generic", + "description": "Base64 string", + "value": "SGVsbG9Xb3JsZA==" + } + ], + "init": { + "inputs": { + "hex": "48656c6c6f576f726c64" + }, + "outputs": {} + }, + "narrative": "A robust format converter designed to translate corrupted civilian data." + }, + { + "id": "item_16_c6b7", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "An encrypted drive found buried in the rubble." + }, + { + "id": "zip_unzip_file_6880", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "secure_archive_6880.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "SuperStrongPassword2023!" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "decrypted_files_6880_out.zip" + } + ], + "init": { + "inputs": { + "zip_id": "secure_archive_6880.zip", + "password": "SuperStrongPassword2023!" + }, + "outputs": { + "files": "decrypted_files_6880_out.zip" + } + }, + "narrative": "An initial archive extractor, used for parsing old compressed records." + }, + { + "id": "container_1", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + }, + { + "name": "fingerprint_input", + "type": "Hex_String", + "description": "Fingerprint Hash", + "value": "deadbeef1234567890abcdef" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "deadbeef1234567890abcdef" + }, + "outputs": {} + }, + "narrative": "A biometric lockbox with a faded military insignia." + }, + { + "id": "hash_sha256", + "name": "SHA-256 Hasher", + "description": "SHA-256 over UTF-8 text; returns hex.", + "type": "Tool", + "template_id": "hash_sha256", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text to hash", + "value": "Text payload to be hashed by SHA-256." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "SHA-256 Hex digest", + "value": "bdb572feafdc3dc740bc8675ec4e351b1ec0225b70941912a1119270346ba06b" + } + ], + "init": { + "inputs": { + "text": "Text payload to be hashed by SHA-256." + }, + "outputs": {} + }, + "narrative": "A rusty cryptographic hasher salvaged from the old world." + }, + { + "id": "calc_modexp_7f52", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "32" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "56473829104758693021" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "999983" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "287040" + } + ], + "init": { + "inputs": { + "base": "32", + "exp": "56473829104758693021", + "mod": "999983" + }, + "outputs": {} + }, + "narrative": "An offline environmental processor covered in dust." + }, + { + "id": "calc_bigmul_362a", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "12938475610293847561" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "98761234509876123450" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "1277819823948543275261250183787917405450" + } + ], + "init": { + "inputs": { + "a": "12938475610293847561", + "b": "98761234509876123450" + }, + "outputs": {} + }, + "narrative": "A heavy-duty power multiplier once used to run city grids." + } + ], + "edges": [ + { + "source_id": "item_16", + "target_id": "item_2", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "matter_synthesizer", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "output_slot", + "target_port": "source_tool" + }, + { + "source_id": "terminal_1", + "target_id": "matter_synthesizer", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "blueprint" + }, + { + "source_id": "calc_modexp", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "slot_b" + }, + { + "source_id": "calc_modexp_be8b", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "mod" + }, + { + "source_id": "terminal_1_bd51", + "target_id": "calc_modexp", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "trigger_item" + }, + { + "source_id": "calc_bigmul", + "target_id": "calc_modexp_be8b", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "mod" + }, + { + "source_id": "calc_modexp_c5c9", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "base" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_modexp_c5c9", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "base" + }, + { + "source_id": "terminal_1_bd51", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "src" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_modexp_c5c9", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "mod" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "a" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp_c5c9", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "exp" + }, + { + "source_id": "calc_gcd", + "target_id": "terminal_1_bd51", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "slot_b" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "exp" + }, + { + "source_id": "time_convert", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "iso", + "target_port": "dst" + }, + { + "source_id": "zip_unzip_item", + "target_id": "calc_gcd", + "connection_type": "Item", + "source_port": "item", + "target_port": "trigger_item" + }, + { + "source_id": "time_convert", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "iso", + "target_port": "slot_a" + }, + { + "source_id": "zip_unzip_file", + "target_id": "zip_unzip_item", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "calc_gcd_13c6", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "b" + }, + { + "source_id": "checksum_crc32_a581", + "target_id": "calc_modexp_be8b", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "base" + }, + { + "source_id": "checksum_crc32", + "target_id": "checksum_crc32_a581", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "a" + }, + { + "source_id": "terminal_1_3e9d", + "target_id": "time_convert", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "to_tz" + }, + { + "source_id": "base64_encode", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "password" + }, + { + "source_id": "item_16_c6b7", + "target_id": "base64_encode", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "zip_unzip_file_6880", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "container_1", + "target_id": "zip_unzip_file_6880", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "hash_sha256", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "terminal_1_bd51", + "target_id": "time_convert", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "from_tz" + }, + { + "source_id": "calc_modexp_7f52", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "b" + }, + { + "source_id": "base64_encode", + "target_id": "zip_unzip_item", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "password" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_gcd_13c6", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "b" + }, + { + "source_id": "calc_bigmul_362a", + "target_id": "terminal_1_3e9d", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "slot_b" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-4b3614c7/environment/puzzle/service.py b/tasks/agentescape-25-skeleton-4b3614c7/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-25-skeleton-4b3614c7/environment/puzzle/service.py @@ -0,0 +1,212 @@ +"""Restricted facade over the unchanged, pinned upstream puzzle handlers.""" + +import hashlib +import json +import logging +import os +import sys +import threading +import urllib.request +import uuid +from pathlib import Path + +from fastapi import FastAPI, HTTPException +from fastapi.responses import JSONResponse +from pydantic import BaseModel, ConfigDict + +sys.path.insert(0, str(Path(__file__).parent / "upstream")) +import server as upstream # noqa: E402 + +log = logging.getLogger(__name__) + + +def public(value): + """Keep upstream agent-internal template hints out of the public response.""" + if isinstance(value, dict): + return {k: public(v) for k, v in value.items() if not k.startswith("_")} + if isinstance(value, list): + return [public(v) for v in value] + return value + + +class Action(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + action: str + node_id: str | None = None + arguments: dict | None = None + answer: str | None = None + + +class Episode: + def __init__( + self, scenario_path, max_actions=500, evidence_dir=None, worker_url=None + ): + if max_actions < 1: + raise ValueError("max_actions must be positive") + self.lock = threading.Lock() + self.max_actions = max_actions + self.count = 0 + self.won = False + self.reason = None + self.evidence_dir = Path(evidence_dir) if evidence_dir else None + self.scenario_hash = hashlib.sha256( + Path(scenario_path).read_bytes() + ).hexdigest() + self.initial = upstream.reset_case( + case_file_path=str(scenario_path), session_id=uuid.uuid4().hex + ) + self.case_id = self.initial["case_id"] + # Hide source file paths; no upstream reset/stats/routes are mounted. + self.initial.pop("message", None) + simulator = upstream.SIMULATORS[self.case_id] + if worker_url is None: + + def no_worker(_inputs): + self.reason = "infrastructure_error" + raise RuntimeError("isolated Python worker is not configured") + + simulator.tool_map["code_py_exec"] = no_worker + else: + + def execute_python(inputs): + request = urllib.request.Request( + worker_url + "/execute", + data=json.dumps({"code": inputs.get("code", "")}).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=12) as response: + result = json.load(response) + if not isinstance(result.get("stdout"), str): + raise RuntimeError("Invalid Python worker response") + return result + except Exception: + self.reason = "infrastructure_error" + raise + + simulator.tool_map["code_py_exec"] = execute_python + self.save() + if self.evidence_dir is not None: + (self.evidence_dir / "trace.jsonl").touch() + + def state(self): + return { + "scenario_sha256": self.scenario_hash, + "action_count": self.count, + "max_actions": self.max_actions, + "won": self.won, + "termination_reason": self.reason, + } + + def save(self, action=None, result=None): + if self.evidence_dir is None: + return + self.evidence_dir.mkdir(parents=True, exist_ok=True) + target = self.evidence_dir / "outcome.json" + temp = target.with_suffix(".tmp") + temp.write_text(json.dumps(self.state())) + temp.replace(target) + if action is not None: + with (self.evidence_dir / "trace.jsonl").open("a") as handle: + handle.write( + json.dumps( + {"index": self.count, "action": action, "result": result} + ) + + "\n" + ) + + def dispatch(self, payload): + with self.lock: + if self.reason is not None: + return { + "ok": False, + "error": "Episode has ended", + "episode": self.state(), + } + self.count += 1 + try: + action = Action.model_validate(payload) + if action.action == "submit_answer" and action.answer is not None: + result = upstream.submit_answer( + self.case_id, upstream.SubmitAnswerRequest(answer=action.answer) + ) + if result.get("is_win"): + self.won = True + self.reason = "success" + elif action.action == "investigate" and action.node_id is not None: + result = upstream.investigate( + self.case_id, + upstream.InvestigateRequest(node_id=action.node_id), + ) + elif ( + action.action in ("tool_call", "use_item") + and action.node_id is not None + ): + request_type, handler = ( + (upstream.ToolCallRequest, upstream.tool_call) + if action.action == "tool_call" + else (upstream.UseItemRequest, upstream.use_item) + ) + result = handler( + self.case_id, + request_type( + node_id=action.node_id, arguments=action.arguments or {} + ), + ) + else: + result = { + "ok": False, + "error": "Unknown action or missing action parameter", + } + except HTTPException as exc: + result = {"ok": False, "error": exc.detail} + except ValueError: + result = {"ok": False, "error": "Malformed action"} + except Exception: + log.exception("Puzzle service failure") + self.reason = "infrastructure_error" + self.save() + raise + if self.reason is None and self.count >= self.max_actions: + self.reason = "action_budget_exhausted" + result = public(result) + result["episode"] = self.state() + self.save(payload, result) + return result + + +def create_app( + scenario_path=None, max_actions=None, evidence_dir=None, worker_url=None +): + episode = Episode( + scenario_path or os.environ["SCENARIO_PATH"], + max_actions or int(os.environ.get("MAX_ACTIONS", "500")), + evidence_dir if evidence_dir is not None else os.environ.get("EVIDENCE_DIR"), + worker_url if worker_url is not None else os.environ.get("WORKER_URL"), + ) + app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) + app.state.episode = episode + + @app.get("/health") + def health(): + return {"ok": True} + + @app.get("/observation") + def observation(): + return {**public(episode.initial), "episode": episode.state()} + + @app.get("/state") + def state(): + return episode.state() + + @app.post("/action") + def action(payload: dict): + try: + return episode.dispatch(payload) + except Exception: + return JSONResponse( + status_code=503, + content={"ok": False, "error": "Puzzle infrastructure failure"}, + ) + + return app diff --git a/tasks/agentescape-25-skeleton-4b3614c7/environment/puzzle/upstream/models.py b/tasks/agentescape-25-skeleton-4b3614c7/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-25-skeleton-4b3614c7/environment/puzzle/upstream/models.py @@ -0,0 +1,108 @@ +from enum import Enum +from typing import List, Dict, Any, Optional +from pydantic import BaseModel, Field + +# 1. 细粒度接口类型定义 +class InterfaceType(str, Enum): + ''' + BIG_INT + TEXT_GENERIC + HEX_STRING + FILE_ID + HEX_STRING_KEY_AES + HEX_STRING_IV_AES + CODE_PYTHON + HIDDEN_ITEM + ITEM + ''' + # --- 基础类型 --- + TEXT_GENERIC = "Text_Generic" + BIG_INT = "Big_Int" + + # --- 编码/格式化字符串 --- + HEX_STRING = "Hex_String" # 通用 Hex + + # --- 特定用途的 Hex 字符串 (用于精确匹配) --- + HEX_STRING_KEY_AES = "Hex_String_Key_AES" + HEX_STRING_IV_AES = "Hex_String_IV_AES" + + # --- 文件类型 --- + FILE_ID = "File_Id" + + # --- 代码/脚本 --- + CODE_PYTHON = "Code_Python" + + # --- 实体交互类型 (严格命名) --- + ITEM = "Item" # 主动掉落接口 (Tool -> Item) + HIDDEN_ITEM = "Hidden_Item" # 被动掉落接口 (Item -> Item) + +# 3. 端口定义 +class Port(BaseModel): + name: str + type: InterfaceType + description: str + +# 4. 统一节点定义 (融合工具和物品) +class Node(BaseModel): + id: str + name: str + description: str + type: str # "Tool" or "Item" + + # 接口定义 + inputs: List[Port] = [] + outputs: List[Port] = [] + + # 状态字段 + content: Optional[Any] = None # 物品有内容,工具为None + if_success: Optional[bool] = None # 工具初始为False,物品为None + initial_visible: bool = False + + # 运行时状态 (Server维护) + is_revealed: bool = False + + # 标记该 Tool 节点是否有待触发的 HIDDEN_ITEM 掉落 + # 当 Tool 按照 golden_input 正确执行且有 HIDDEN_ITEM 输出边时设为 True + # 在 investigate 该 Tool 时触发掉落并重置为 False + has_hidden_item_ready: bool = False + + # 初始输入值 (metadata.initial_values.init_inputs,用于渐进式暴露判断) + init_input_values: Dict[str, Any] = {} + + # Golden 输入值 (nodes[].inputs[].value,用于评测验证) + golden_input_values: Dict[str, Any] = {} + + # Golden 输出值 (nodes[].outputs[].value,用于评测验证和 Item 节点的 content) + golden_output_values: Dict[str, Any] = {} + + # 实际获得的输出值历史 (工具每次执行后实际返回的输出列表,用于渐进式暴露判断) + # 格式: List[Dict[str, Any]],每个元素是一次执行的输出字典 + actual_outputs_history: List[Dict[str, Any]] = [] + + # 逻辑规则 (用于终端机等复杂物品) + logic_rules: Optional[Dict[str, Any]] = None + + def copy(self, **kwargs): + """Helper to create a copy with updated fields.""" + data = self.dict() + data.update(kwargs) + return Node(**data) + +# 5. 边定义 (拓扑结构) +class Edge(BaseModel): + source_id: str + target_id: str + connection_type: InterfaceType # 直接使用 InterfaceType + # 如果是 Data_Flow,指定端口对应关系 + source_port: Optional[str] = None + target_port: Optional[str] = None + +# 6. 完整图定义 +class GraphScenario(BaseModel): + case_id: str + title: str + intro_narrative: str + nodes: Dict[str, Node] + edges: List[Edge] + difficulty: int + win_node_id: str # 标记哪个节点是最终目标(通常是一个提交工具或最终物品) diff --git a/tasks/agentescape-25-skeleton-4b3614c7/environment/puzzle/upstream/server.py b/tasks/agentescape-25-skeleton-4b3614c7/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-25-skeleton-4b3614c7/environment/puzzle/upstream/server.py @@ -0,0 +1,1490 @@ +import json +import os +import time +import logging +import random +from pathlib import Path +from typing import Dict, Any, List, Optional +from datetime import datetime +from collections import defaultdict +from fastapi import FastAPI, HTTPException, Request +from fastapi.responses import JSONResponse +from fastapi.middleware.cors import CORSMiddleware +from pydantic import BaseModel, Field + +from models import GraphScenario, Node, InterfaceType +# from generator import ScenarioGenerator +from simulator import ToolSimulator +import uvicorn + +# 配置日志 +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler('server.log'), + logging.StreamHandler() + ] +) +logger = logging.getLogger(__name__) + +app = FastAPI( + title="AgentEscapeBench Universal Server", + version="1.0.0", + description="Industrial-grade evaluation server for escape room AI agents" +) + +# 添加 CORS 支持 +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# In-memory State +SCENARIOS: Dict[str, GraphScenario] = {} +SIMULATORS: Dict[str, ToolSimulator] = {} # case_id -> ToolSimulator +RAW_NODES_DATA: Dict[str, Dict[str, Any]] = {} # case_id -> node_id -> raw node data (for template_id) +FILE_METADATA: Dict[str, Dict[str, Any]] = {} # case_id -> metadata (for initial_values access) + +# Performance monitoring +STATS: Dict[str, Any] = { + "total_requests": 0, + "successful_requests": 0, + "failed_requests": 0, + "tool_calls": defaultdict(int), + "investigates": defaultdict(int), + "use_items": defaultdict(int), + "case_loads": 0, + "start_time": datetime.now() +} + +# Request timing middleware +@app.middleware("http") +async def add_process_time_header(request: Request, call_next): + start_time = time.time() + STATS["total_requests"] += 1 + + try: + response = await call_next(request) + STATS["successful_requests"] += 1 + process_time = time.time() - start_time + response.headers["X-Process-Time"] = str(process_time) + logger.info(f"{request.method} {request.url.path} - {response.status_code} - {process_time:.3f}s") + return response + except Exception as e: + STATS["failed_requests"] += 1 + logger.error(f"{request.method} {request.url.path} - Error: {str(e)}") + raise + +# Exception handler +@app.exception_handler(Exception) +async def global_exception_handler(request: Request, exc: Exception): + logger.error(f"Unhandled exception: {exc}", exc_info=True) + return JSONResponse( + status_code=500, + content={ + "ok": False, + "error": "Internal server error", + "detail": str(exc) if os.getenv("DEBUG") else "An error occurred" + } + ) + +# Health check endpoint +@app.get("/health") +def health_check(): + """健康检查端点""" + uptime = (datetime.now() - STATS["start_time"]).total_seconds() + return { + "status": "healthy", + "version": "1.0.0", + "uptime_seconds": uptime, + "loaded_cases": len(SCENARIOS), + "stats": { + "total_requests": STATS["total_requests"], + "successful_requests": STATS["successful_requests"], + "failed_requests": STATS["failed_requests"], + "success_rate": STATS["successful_requests"] / max(STATS["total_requests"], 1) + } + } + +# Statistics endpoint +@app.get("/stats") +def get_stats(): + """获取详细统计信息""" + return { + "stats": STATS, + "loaded_cases": list(SCENARIOS.keys()), + "uptime": str(datetime.now() - STATS["start_time"]) + } + +def _apply_progressive_reveal_at_init(scenario: GraphScenario): + """ + 在初始化时应用渐进式暴露机制(基于ITEM/HIDDEN_ITEM边) + + 新逻辑: + - 如果一个节点没有 ITEM/HIDDEN_ITEM 类型的入边,它就是初始可见的 + - 如果一个节点有 ITEM/HIDDEN_ITEM 类型的入边,它初始不可见,需要等待上游触发 + + Args: + scenario: 场景对象 + """ + # 收集所有有 ITEM/HIDDEN_ITEM 入边的节点 + nodes_with_item_edges = set() + for edge in scenario.edges: + if edge.connection_type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + nodes_with_item_edges.add(edge.target_id) + + logger.info(f"Nodes with ITEM/HIDDEN_ITEM incoming edges: {nodes_with_item_edges}") + + # 设置初始可见性:没有 ITEM/HIDDEN_ITEM 入边的节点初始可见 + initially_visible_count = 0 + for node_id, node in scenario.nodes.items(): + if node_id not in nodes_with_item_edges: + node.is_revealed = True + initially_visible_count += 1 + logger.info(f"Initial visible (no ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + else: + node.is_revealed = False + logger.debug(f"Initial hidden (has ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + + logger.info(f"Progressive reveal initialized: {initially_visible_count}/{len(scenario.nodes)} nodes initially visible") + + +def _check_inputs_match_golden(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> bool: + """ + 检查实际输入参数是否与 golden inputs 完全匹配 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + True 表示所有 golden inputs 都存在且值匹配 + """ + if not golden_inputs: + return True # 如果没有 golden inputs,认为匹配 + + for key, expected_value in golden_inputs.items(): + actual_value = arguments.get(key) + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) != str(expected_value): + logger.debug(f"Input mismatch for '{key}': expected '{expected_value}', got '{actual_value}'") + return False + + return True + + +def _get_parameter_validation_feedback(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> Dict[str, Any]: + """ + 对源头节点的参数进行详细验证,返回验证反馈 + + 注意:不返回期望值(expected),避免泄漏答案 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + 包含验证结果的字典: + - all_correct: bool - 所有参数是否正确 + - correct_params: List[str] - 正确的参数名列表 + - incorrect_params: List[str] - 错误的参数名列表(不包含期望值) + """ + if not golden_inputs: + return { + "all_correct": True, + "correct_params": [], + "incorrect_params": [] + } + + correct_params = [] + incorrect_params = [] + + for key, actual_value in arguments.items(): + # 只对用户实际提交的参数给反馈,未提交的参数不评价 + if key not in golden_inputs: + continue # 该参数不在 golden 中,跳过(如 _golden_inputs 等内部参数) + expected_value = golden_inputs[key] + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) == str(expected_value): + correct_params.append(key) + else: + # 只记录参数名,不包含期望值,避免泄漏答案 + incorrect_params.append(key) + + # all_correct:用户提交的所有参数都正确,且覆盖了全部 golden 参数 + all_provided_correct = len(incorrect_params) == 0 + all_golden_covered = all(k in arguments for k in golden_inputs) + return { + "all_correct": all_provided_correct and all_golden_covered, + "correct_params": correct_params, + "incorrect_params": incorrect_params + } + + +def _is_source_node(node_id: str, scenario: GraphScenario) -> bool: + """ + 判断节点是否是源头节点(完全没有任何入边的节点) + + 源头节点定义: + - 没有任何类型的入边(包括 DATA、ITEM、HIDDEN_ITEM) + - 即没有任何上游节点 + + Args: + node_id: 节点ID + scenario: 场景对象 + + Returns: + True 表示是源头节点 + """ + for edge in scenario.edges: + if edge.target_id == node_id: + # 只要有任何入边,就不是源头节点 + return False + + return True + + +def _check_and_reveal_ready_nodes(scenario: GraphScenario, recent_outputs: Dict[str, Any], source_node_id: str) -> List[Dict[str, Any]]: + """ + 检查并释放参数齐全的隐藏节点(渐进式暴露机制) + + 核心逻辑: + 1. 维护"可见值集合":包含所有被测模型当前可以看到的值 + - init_inputs 的值(初始可见) + - 工具执行后的实际输出值(运行时获得) + - 可见 Item 的输出值 + 2. 检查隐藏节点:该节点的所有 golden_input 值是否都在可见值集合中 + 3. 如果是,则释放该节点 + + Args: + scenario: 场景对象 + recent_outputs: 最近执行的工具的输出 + source_node_id: 刚执行的工具节点ID + + Returns: + 新释放的节点列表 + """ + newly_revealed = [] + + # 构建"可见值集合"(Set of visible values) + # 存储格式:set of values (转为字符串) + visible_values = set() + + # 1. 添加有意义的 init_inputs 值到可见值集合 + # Item 的 init_inputs 不应该加入,因为它们在密室中完全用不到 + for node_id, node in scenario.nodes.items(): + # 跳过源头 Item 节点(没有入边的 Item) + if node.type == "Item": + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,跳过其 init_inputs + continue + + # 添加其他节点的 init_inputs + for port_name, init_value in node.init_input_values.items(): + if init_value: + visible_values.add(str(init_value)) + + # 2. 添加已执行工具的所有历史输出值 + for node_id, node in scenario.nodes.items(): + if node.type == "Tool" and node.if_success and node.actual_outputs_history: + # 遍历所有历史执行记录 + for output_dict in node.actual_outputs_history: + for output_port_name, output_value in output_dict.items(): + if output_value: + visible_values.add(str(output_value)) + + # 3. 添加已被 investigate 的 Item 的 golden 输出值 + # 注意:Item 可见不等于其输出值可见,需要 investigate 后才能获得 + # 这里我们使用 actual_outputs_history 来标记 Item 是否已被 investigate + for node_id, node in scenario.nodes.items(): + if node.type == "Item" and node.is_revealed and node.actual_outputs_history: + # Item 通常只会被 investigate 一次,但为了一致性也使用历史列表 + for output_dict in node.actual_outputs_history: + for port_name, port_value in output_dict.items(): + if port_value: + visible_values.add(str(port_value)) + + # 遍历所有隐藏的节点,检查其 golden_input 是否都在可见值集合中 + for node_id, node in scenario.nodes.items(): + # 跳过已可见的节点 + if node.is_revealed: + continue + + # 只检查工具节点(物品节点由 ITEM 输出触发) + if node.type != "Tool": + continue + + # 检查该节点的所有 golden_input 值是否都在可见值集合中 + all_inputs_ready = True + missing_values = [] + + for input_port_name, golden_input_value in node.golden_input_values.items(): + # 检查这个 golden 值是否在可见值集合中 + if str(golden_input_value) not in visible_values: + all_inputs_ready = False + missing_values.append(f"{input_port_name}={golden_input_value}") + + # 如果所有 golden_input 值都在可见值集合中,释放该节点 + if all_inputs_ready and len(node.golden_input_values) > 0: + logger.info(f"All golden inputs ready for {node_id}: {list(node.golden_input_values.values())}") + + # 如果所有输入都齐全,释放该节点 + if all_inputs_ready: + node.is_revealed = True + + # 构建节点信息返回给模型 + node_info = { + "id": node.id, + "type": node.type, + "can_investigate": True, + "hint": "This tool's input parameters are now complete, you can use investigate to view detailed information" + } + + # if node.name: + # node_info["name"] = node.name + if node.description: + node_info["description"] = node.description + + newly_revealed.append(node_info) + logger.info(f"Progressive reveal: {node_id} is now ready (all inputs satisfied)") + + return newly_revealed + + +def _initialize_node_values(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]): + """ + Initialize node state and load values from port value fields. + 应用渐进式暴露机制:初始时只显示参数齐全的节点(源头节点) + + 重要区分: + 1. input_values: 只加载 metadata.initial_values 中的 init_inputs(真正的初始值) + 2. output_values: 加载 nodes[].outputs[].value(golden 输出,用于验证) + """ + # 第一步:加载所有节点的值,并将所有节点初始设为隐藏 + initial_values = metadata.get('initial_values', {}) + + for node_id, node in scenario.nodes.items(): + # 忽略 initial_visible 字段,初始全部隐藏 + # 由渐进式暴露机制根据参数齐全情况决定是否显示 + node.is_revealed = False + + if node.type == "Tool": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + elif node.type == "Item": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + + # 从 JSON 加载值 + if node_id in raw_nodes_data: + node_data = raw_nodes_data[node_id] # node_data是json文件中nodes中的字典 + + # 【重要】只加载 metadata.initial_values 中的初始输入值 + if node_id in initial_values: + init_data = initial_values[node_id] + # 加载初始输入值(用于渐进式暴露判断) + for port_name, port_value in init_data.get('init_inputs', {}).items(): + node.init_input_values[port_name] = port_value + + # 【评测用】加载 golden 输入值(用于验证模型传入的参数是否正确) + for input_port_data in node_data.get('inputs', []): + if 'value' in input_port_data: + node.golden_input_values[input_port_data['name']] = input_port_data['value'] + + # 【评测用】加载 golden 输出值(用于验证工具调用是否正确,以及 Item 节点的 content) + for output_port_data in node_data.get('outputs', []): + if 'value' in output_port_data: + node.golden_output_values[output_port_data['name']] = output_port_data['value'] + + # For Items, set content from golden_output_values + if node.type == "Item" and node.golden_output_values: + # Item 的 content 是其第一个 golden 输出值 + node.content = list(node.golden_output_values.values())[0] + + # 第二步:应用渐进式暴露机制 + # 检查所有节点,根据参数齐全情况释放源头节点(工具 + Item) + _apply_progressive_reveal_at_init(scenario) + +def _build_node_info(node: Node, raw_nodes_data: Dict[str, Any]) -> Dict[str, Any]: + """ + 构建节点信息(工具或物品) + + Args: + node: 节点对象 + raw_nodes_data: 原始节点数据(用于获取 template_id 等) + + Returns: + 节点信息字典 + """ + if node.type == "Tool": + # 过滤掉输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口) + # 这些端口仅用于控制掉落机制,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + tool_info = { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Tool", + "inputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.inputs if p.type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]], + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id(工具的标准名称) + if node.id in raw_nodes_data: + node_data = raw_nodes_data[node.id] + template_id = node_data.get('template_id') + if template_id: + tool_info['template_id'] = template_id + + return tool_info + + elif node.type == "Item": + return { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Item" + } + + else: + return { + "id": node.id, + # "name": node.name, + "type": node.type + } + +def _get_initial_observation(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]) -> Dict[str, Any]: + """ + Generate initial observation for the agent (what they see when entering the room). + + 策略: + - Tools: 只显示名称和描述,不显示接口定义。需要 investigate 才能获得详细接口信息。 + - Items: 只显示存在,不显示内容。需要 investigate 才能获得内容值。 + - init_inputs: 作为"可用信息"告诉模型,这些是可以用作工具参数的初始值。 + - init_outputs: 不告诉模型(这些是答案,需要模型通过调用工具获得)。 + """ + available_entities = [] # 统一的实体列表(Tools 和 Items) + available_information = [] # 可用的初始信息(来自 init_inputs) + + # 从 metadata.initial_values 提取 init_inputs 作为可用信息 + # 只提供值本身,不透露这些值对应哪个节点的哪个参数,让模型自己推理 + # 注意:跳过源头 Item(没有入边的 Item)的 init_inputs,因为它们在密室中完全用不到 + initial_values = metadata.get('initial_values', {}) + # initial_values字段的格式 + # "initial_values": { + # "terminal_1": { + # "init_inputs": {}, + # "init_outputs": { + # "text_output": "System initialization complete.", + # "hex_output": "48656c6c6f20576f726c64", + # "item_dispenser": "掉落了一张纸条,上面写着“请勿随意触摸终端”" + # } + # } + # } + for node_id, init_data in initial_values.items(): + # 获取节点信息,判断是否为源头 Item + node = scenario.nodes.get(node_id) + if node and node.type == "Item": + # 检查是否为源头 Item(没有入边) + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,检查是否有 init_inputs + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 有 init_inputs,需要暴露这些参数 + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + # 处理完后跳过后续的通用逻辑 + continue + + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 为每个 init_input 值创建一个信息条目(不包含 source_node 和 parameter 信息) + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + + for node in scenario.nodes.values(): + if node.is_revealed: + # Tools: 只显示基本信息,提示可以 investigate 查看详细接口 + if node.type == "Tool": + tool_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Tool", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the tool's detailed interface information for calling" + } + # 只在 name 非空时添加 + # if node.name: + # tool_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_info["description"] = node.description + + available_entities.append(tool_info) + + # Items: 只显示基本信息,提示可以 investigate 查看内容 + elif node.type == "Item": + item_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Item", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the item's content" + } + # 只在 name 非空时添加 + # if node.name: + # item_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + item_info["description"] = node.description + + available_entities.append(item_info) + + return { + "narrative": scenario.intro_narrative, + "available_entities": available_entities, # 使用统一的实体列表 + "available_information": available_information, # 可用的初始信息(只包含 init_inputs) + "win_node_id": scenario.win_node_id # 胜利节点ID,让模型知道需要关注哪个节点 + } + +@app.post("/env/reset") +def reset_case(case_id: str = None, case_file_path: str = None, session_id: str = None): + """Loads a specific case from file and resets it. + + Args: + case_id: Optional case ID for resetting an existing case + case_file_path: Path to case file for loading a new case + session_id: Optional session ID to ensure isolation between concurrent evaluations + """ + logger.info(f"Reset request - case_id: {case_id}, case_file_path: {case_file_path}, session_id: {session_id}") + STATS["case_loads"] += 1 + + if case_file_path: + if not os.path.exists(case_file_path): + logger.error(f"Case file not found: {case_file_path}") + raise HTTPException(status_code=404, detail=f"File not found: {case_file_path}") + try: + with open(case_file_path, "r", encoding="utf-8") as f: + file_data = json.load(f) + + # 转换格式:从 DAG executor 生成的格式转换为 GraphScenario 格式 + # 1. 提取 metadata + metadata = file_data.get('metadata', {}) + + # 2. 生成 case_id, title, intro_narrative + # 【修复】为每个评测会话生成唯一的 case_id,防止并发评测时状态污染 + base_name = os.path.basename(case_file_path).replace('.json', '').replace('_full', '').replace('_full2', '') + + if session_id: + # 如果提供了 session_id,使用它来确保唯一性 + case_id = f"{base_name}_{session_id}" + else: + # 否则使用时间戳和随机数确保唯一性 + unique_suffix = f"{int(time.time() * 1000)}_{random.randint(1000, 9999)}" + case_id = f"{base_name}_{unique_suffix}" + + file_data['case_id'] = case_id + logger.info(f"Generated unique case_id: {case_id} (base: {base_name}, session: {session_id})") + + if 'title' not in file_data: + file_data['title'] = f"Escape Room: {file_data['case_id']}" + + if 'intro_narrative' not in file_data: # 目前的json文件中已经有了intro_narrative字段,不会使用下面一行的内容,而是使用每个评测问题的json文件中的对应字段 + 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]".' + + # 3. 转换 nodes 列表为字典(DAG executor 生成的文件中 nodes 是列表格式) + nodes_dict = {} + for node_data in file_data['nodes']: + nodes_dict[node_data['id']] = node_data # 这里的id是template_id之后可能添加一个后缀 + file_data['nodes'] = nodes_dict # 把列表转成一个字典 + + # 4. 添加缺失的字段 + if 'difficulty' not in file_data: + file_data['difficulty'] = metadata.get('total_nodes', 5) + + if 'win_node_id' not in file_data: + file_data['win_node_id'] = metadata.get('win_node_id', '') + + scenario = GraphScenario(**file_data) + + # Extract raw nodes data for template_id access + # nodes 已经在上面转换为字典格式 + raw_nodes_data = file_data.get('nodes', {}) + RAW_NODES_DATA[scenario.case_id] = raw_nodes_data + + # Store metadata for initial values access + FILE_METADATA[scenario.case_id] = metadata + + logger.info(f"Successfully parsed case file: {scenario.case_id}, nodes: {len(scenario.nodes)}, edges: {len(scenario.edges)}") + except Exception as e: + logger.error(f"Failed to load case file: {str(e)}", exc_info=True) + raise HTTPException(status_code=500, detail=f"Failed to load case file: {str(e)}") + + # Initialize node state and load values + _initialize_node_values(scenario, raw_nodes_data, metadata) + + SCENARIOS[scenario.case_id] = scenario + simulator = ToolSimulator() + SIMULATORS[scenario.case_id] = simulator + + 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'])}") + + # 生成初始观察信息(进入密室后看到的环境) + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + ''' + initial_observation的格式: + { + "narrative": scenario.intro_narrative, + "available_entities": available_entities # 使用统一的实体列表 + "available_information": available_information # 可用的初始信息(只包含 init_inputs) + } + ''' + + return { + "ok": True, + "message": f"Case loaded from {case_file_path}", + "case_id": scenario.case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果没有提供 case_file_path,但提供了 case_id,则尝试从内存重置 + if case_id and case_id in SCENARIOS: + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + metadata = FILE_METADATA.get(case_id, {}) + + # Reset dynamic fields and re-apply progressive reveal + # 重新初始化节点状态(包括渐进式暴露) + _initialize_node_values(scenario, raw_nodes_data, metadata) + + 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'])}") + + # 生成初始观察信息 + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + + return { + "ok": True, + "message": f"Case {case_id} reset.", + "case_id": case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果既没有 case_file_path,也没有在内存中找到,返回错误 + raise HTTPException( + status_code=400, + detail="Must provide case_file_path to load a new case, or use case_id to reset an existing case." + ) + +class InvestigateRequest(BaseModel): + node_id: str + +@app.post("/env/{case_id}/investigate") +def investigate(case_id: str, req: InvestigateRequest): + """ + Investigates a Tool or Item to reveal detailed information. + + - For Tools: Returns detailed interface information (inputs/outputs) needed to call the tool + - For Items: Returns content value and triggers hidden item drops + """ + logger.info(f"Investigate request - case_id: {case_id}, node_id: {req.node_id}") + STATS["investigates"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + node = scenario.nodes[req.node_id] + + if not node.is_revealed: + logger.warning(f"Attempt to investigate hidden node: {req.node_id}") + return {"ok": False, "error": "Node is not visible yet."} + + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + newly_revealed = [] + + # 处理 Tool 的 investigate + if node.type == "Tool": + logger.info(f"Investigating tool: {req.node_id}") + + # 返回工具的详细接口信息 + # id 字段使用 node.id(节点唯一标识),agent 用这个字段识别和调用具体的节点 + # template_id 是工具类型标识符,Agent 内部用于判断工具特性(如 terminal 类工具参数可选) + # 注意:只过滤输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口),这些端口仅用于控制掉落,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + # 【端口上游依赖提示 & 初始值直接给出】 + # 针对参数语义模糊(全为数字类型)的工具,在 investigate 返回信息中标注 + # 哪个输入端口来自哪个上游节点(upstream_from)。 + # 对于所有工具:若该节点不是纯源头节点(有任意数据流入边), + # 且某个端口没有上游入边(值来自初始可见参数),则直接给出该端口的 golden input 值。 + AMBIGUOUS_TOOLS = { + "num_base_convert", "calc_modexp", "calc_modexp_int", + "calc_inv_mod", "calc_inv_mod_int", "crypto_rsa_decrypt_hex", "geo_haversine" + } + # Terminal 类工具自带参数对错反馈机制,玩家/模型可自行试错, + # 无需在 investigate 时直接暴露 init_value + SELF_FEEDBACK_TOOLS = { + "terminal_1", "terminal_2", + "Logic Terminal", "Math Terminal", "Encryption Terminal", "Sequence Terminal" + } + _template_id_for_hint = raw_nodes_data.get(node.id, {}).get("template_id", "") + # 构建数据流入边映射(对所有工具):{target_port -> (source_node_id, source_port)} + _upstream_map = {} + for _edge in scenario.edges: + if (_edge.target_id == node.id + and _edge.connection_type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM] + and _edge.target_port is not None): + _upstream_map[_edge.target_port] = (_edge.source_id, _edge.source_port) + # 判断该节点是否有任意数据流入边(即不是纯源头节点) + _has_any_upstream = len(_upstream_map) > 0 + # 判断该节点是否有任意入边(包括 ITEM/HIDDEN_ITEM 掉落边) + # 有任意入边(含掉落边)但无数据流入边的节点,其输入来自初始可见参数,应直接给出 + _has_any_edge = any(_edge.target_id == node.id for _edge in scenario.edges) + # 构建 inputs 列表 + _inputs_list = [] + for p in node.inputs: + if p.type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + continue + port_dict = {"name": p.name, "type": p.type, "description": p.description} + if p.name in _upstream_map: + # 该端口有上游数据流依赖,且属于语义模糊工具 → 标注来源 + if _template_id_for_hint in AMBIGUOUS_TOOLS: + src_node_id, src_port = _upstream_map[p.name] + port_dict["upstream_from"] = f"{src_node_id}.{src_port}" if src_port else src_node_id + elif _has_any_edge and _template_id_for_hint not in SELF_FEEDBACK_TOOLS: + # 该节点有任意入边,但此端口没有数据流入边 → 值来自初始可见参数,直接给出 + # 排除自带反馈机制的 terminal 类工具(它们通过执行结果反馈对错,无需提前暴露参数值) + golden_val = node.golden_input_values.get(p.name) + if golden_val is not None: + port_dict["init_value"] = golden_val + _inputs_list.append(port_dict) + + tool_details = { + "id": node.id, # 节点 ID,用于唯一标识和调用这个具体节点 + "type": "Tool", + "inputs": _inputs_list, + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id 用于 Agent 内部判断工具类型(不会展示给被测模型) + if node.id in raw_nodes_data: + template_id = raw_nodes_data[node.id].get('template_id') + if template_id: + tool_details["_template_id"] = template_id # 使用下划线前缀标记为内部字段 + + # 只在 name 非空时添加 + # if node.name: + # tool_details["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_details["description"] = node.description + + # 添加 narrative 字段(如果存在) + if node.id in raw_nodes_data: + narrative = raw_nodes_data[node.id].get('narrative') + if narrative: + tool_details['narrative'] = narrative + + # 不再返回 init_values,避免泄漏答案 + # investigate 只应该返回工具的接口定义,不应该暴露初始值 + + # 【新增】检查该 Tool 是否有待触发的 HIDDEN_ITEM 掉落 + # 如果该工具已按照 golden_input 正确执行,且有 HIDDEN_ITEM 输出边,则触发掉落 + if node.has_hidden_item_ready: + logger.info(f"Tool has HIDDEN_ITEM ready - triggering passive drop for: {req.node_id}") + + # 遍历该工具的所有 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + # 重置标志,已经触发过了,避免重复 + node.has_hidden_item_ready = False + + logger.info(f"Tool investigation successful - node: {req.node_id}, revealed: {len(newly_revealed)}") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Tool", + "details": tool_details + } + + # 如果有新掉落的节点,添加到响应中 + if newly_revealed: + result["newly_revealed"] = newly_revealed + + return result + + # 处理 Item 的 investigate + elif node.type == "Item": + logger.info(f"Investigating item: {req.node_id}") + + # 【第一步】检查该 Item 是否有需要参数的输入端口 + # 如果有,且尚未通过 use_item 验证,则不返回内容,只返回参数要求 + required_inputs = [] + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + inputs_info = raw_node.get('inputs', []) + required_inputs = [ + { + "name": inp.get("name"), + "type": inp.get("type"), + "description": inp.get("description", "") + } + for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + # 如果有 required_inputs 且尚未通过 use_item 验证(if_success == False) + # 则不返回内容,只返回参数要求提示 + if required_inputs and not node.if_success: + logger.info(f"Item has required inputs and not yet unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "required_inputs": required_inputs + } + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + param_names = ', '.join([inp['name'] for inp in required_inputs]) + 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}" + + return result + + # 【新增】如果有 required_inputs 且已经通过 use_item 验证(if_success == True) + # 则返回提示:该节点已经被成功解决 + if required_inputs and node.if_success: + logger.info(f"Item has required inputs and already unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "message": "This item has already been successfully unlocked by you." + } + return result + + # 【第二步】该 Item 没有 required_inputs 或已通过验证,返回内容 + # 1. 返回 Item 的 golden_output_values(即 Item 的内容) + # 注意:某些 Item 仅用于触发 HIDDEN_ITEM 掉落,没有实际内容 + has_actual_content = bool(node.golden_output_values) or node.content is not None + content = node.golden_output_values if node.golden_output_values else node.content + + # 【关键】将 golden_output_values 追加到 actual_outputs_history,标记该 Item 已被 investigate + # 这样在渐进式暴露时,这些值才会被加入可见值集合 + # 即使是空字典(仅触发 HIDDEN_ITEM 的 Item),也要记录,以便渐进式暴露逻辑知道该 Item 已被调查 + if node.golden_output_values is not None: + node.actual_outputs_history.append(dict(node.golden_output_values)) + + # 2. Trigger Hidden Item Drops (Passive Drop) + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + logger.info(f"Item investigation successful - node: {req.node_id}, has_content: {has_actual_content}, revealed: {len(newly_revealed)}") + + # 【渐进式暴露】旧机制(基于 golden_input)已禁用 + # 现在完全由 ITEM/HIDDEN_ITEM 边触发控制节点可见性 + # 上面的 HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, node.golden_output_values or {}, node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # logger.info(f"Progressive reveal after Item investigate: {len(progressive_revealed)} nodes now ready") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Item" + } + + # 只在有实际内容时才添加 content 字段 + # 对于仅触发 HIDDEN_ITEM 掉落的 Item,不返回 content 字段,避免返回 None 或空字典让模型困惑 + if has_actual_content: + result["content"] = content + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型通过 investigate 获得内容后,需要自己识别这是否是胜利字符串 + + return result + + else: + logger.warning(f"Attempt to investigate unknown node type: {req.node_id} (type: {node.type})") + return {"ok": False, "error": f"Cannot investigate node type: {node.type}"} + +class ToolCallRequest(BaseModel): + node_id: str # 使用 node_id 精确指定要调用的节点 + arguments: Dict[str, Any] + +@app.post("/env/{case_id}/tool_call") +def tool_call(case_id: str, req: ToolCallRequest): + """Executes a tool and triggers item drops.""" + logger.info(f"Tool call request - case_id: {case_id}, node_id: {req.node_id}, args: {list(req.arguments.keys())}") + STATS["tool_calls"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + + # 通过 node_id 精确查找节点 + node_id = req.node_id + if node_id not in scenario.nodes: + logger.error(f"Node not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + tool_node = scenario.nodes[node_id] + + if not tool_node: + logger.error(f"Tool not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Tool not found") + + if not tool_node.is_revealed: + logger.warning(f"Attempt to call hidden tool: {node_id}") + return {"ok": False, "error": "Tool is not visible yet."} + + if tool_node.type != "Tool": + logger.warning(f"Attempt to call non-tool node: {node_id} (type: {tool_node.type})") + return {"ok": False, "error": "Only tools can be called."} + + # 1. Execute Tool (Real Execution via Simulator) + simulator = SIMULATORS[case_id] + + # Get tool name from template_id if available, otherwise use node name + tool_name = tool_node.name + if case_id in RAW_NODES_DATA and node_id in RAW_NODES_DATA[case_id]: + template_id = RAW_NODES_DATA[case_id][node_id].get('template_id') + if template_id: + tool_name = template_id + + # 文件处理工具和 Terminal 需要验证输入并返回预先计算的输出 + # 传递节点的实际输入输出值(从 DAG 执行后填充的数据) + tool_arguments = dict(req.arguments) # Make a copy + + # 传递节点的 golden values(从 JSON 的 inputs[].value 和 outputs[].value 加载) + # 用于在评测阶段验证被测模型传入的参数是否正确 + if tool_node.golden_input_values: + tool_arguments['_golden_inputs'] = tool_node.golden_input_values + if tool_node.golden_output_values: + tool_arguments['_golden_outputs'] = tool_node.golden_output_values + + logger.debug(f"Executing tool {tool_name} (node: {tool_node.name}) with args {tool_arguments}") + + try: + output_values = simulator.execute(tool_name, tool_arguments) + logger.info(f"Tool invoked - {tool_name}: {list(output_values.keys())}") + except Exception as e: + logger.error(f"Tool execution failed - {tool_name}: {str(e)}", exc_info=True) + return {"ok": False, "error": f"Tool execution failed: {str(e)}"} + + # 检查验证结果(精细化错误反馈) + validation = output_values.pop("_validation", {"valid": True}) + + if not validation["valid"]: + # 根据错误类型构造友好的错误消息 + error_type = validation.get("error_type") + + if error_type == "missing_required": + missing = validation.get("missing_params", []) + error_msg = f"Error: Missing required parameters {', '.join(missing)}" + + elif error_type == "type_error": + param = validation.get("param_name") + message = validation.get("message", "Parameter type error") + error_msg = f"Error: {message}" + + elif error_type == "incomplete_optional": + provided = validation.get("provided_params", []) + missing = validation.get("missing_params", []) + error_msg = ( + f"Hint: You provided some parameters ({', '.join(provided)}), " + f"but may also need: {', '.join(missing)}.\n" + f"Trying to provide these parameters together might yield better results." + ) + + elif error_type == "value_mismatch": + param = validation.get("param_name") + hint = validation.get("hint", "Parameter value may be incorrect") + error_msg = f"Hint: {hint}.\nPlease check if this parameter value meets the requirements." + + else: + error_msg = validation.get("hint") or validation.get("message", "Parameter validation failed") + + logger.info(f"Tool validation failed - {tool_name}: {error_type}") + return { + "ok": False, + "error": error_msg, + "error_type": error_type + } + + # Simulate success + tool_node.if_success = True + + # 【关键】将本次执行的输出值追加到历史列表(用于渐进式暴露判断) + # 每次调用都会记录,不会覆盖之前的执行结果 + tool_node.actual_outputs_history.append(dict(output_values)) + + # 2. 检查是否应该触发掉落(只有输入参数正确时才掉落) + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, tool_node.golden_input_values) + + newly_revealed = [] + investigate_hints = [] # 提示模型哪些节点可以 investigate 来发现隐藏内容 + + if inputs_match_golden: + logger.info(f"✓ Tool inputs match golden - node: {node_id}, triggering drops") + + # 检查该工具是否有 ITEM 或 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == tool_node.id: + target_node = scenario.nodes[edge.target_id] + + # ITEM 边:立即掉落(主动掉落) + if edge.connection_type == InterfaceType.ITEM: + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from {node_id})") + + # HIDDEN_ITEM 边:不立即掉落,标记并提示(被动掉落) + elif edge.connection_type == InterfaceType.HIDDEN_ITEM: + # 标记该工具有待触发的 HIDDEN_ITEM 掉落 + tool_node.has_hidden_item_ready = True + + # 提示模型可以 investigate 这个工具来发现隐藏内容 + hint_info = { + "tool_id": tool_node.id, + "hint": f"Tool '{tool_node.id}' seems to hide something, try investigating it to discover more information" + } + # if tool_node.name: + # hint_info["tool_name"] = tool_node.name + + investigate_hints.append(hint_info) + logger.info(f"HIDDEN_ITEM ready: {tool_node.id} -> {target_node.id} (will drop on investigate)") + else: + logger.info(f"✗ Tool inputs do NOT match golden - node: {node_id}, no drops triggered") + + response = { + "ok": True, + "message": "Tool invoked", + "output_values": output_values # Return raw outputs to Agent + } + + # 【新增】对源头节点进行参数验证反馈 + # 源头节点:没有数据流入边的节点,这些节点的参数需要模型自己推理 + # 验证模型使用的参数是否正确,并提供明确的反馈 + if _is_source_node(node_id, scenario) and tool_node.golden_input_values: + validation_feedback = _get_parameter_validation_feedback(req.arguments, tool_node.golden_input_values) + + if validation_feedback["all_correct"]: + # 用户提交了全部 golden 参数且全部正确 + response["parameter_feedback"] = { + "status": "correct", + "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." + } + logger.info(f"✓ Source node parameters all correct - node: {node_id}") + elif validation_feedback["incorrect_params"]: + # 有提交了但值错误的参数,只对这些参数给出反馈 + incorrect_list = [] + for param_name in validation_feedback["incorrect_params"]: + incorrect_list.append(f" - Parameter '{param_name}' is incorrect") + + correct_info = "" + if validation_feedback["correct_params"]: + correct_info = f"\n✓ Correct parameters: {', '.join(validation_feedback['correct_params'])}" + + response["parameter_feedback"] = { + "status": "incorrect", + "message": ( + f"⚠️ Some parameters are incorrect:\n" + + "\n".join(incorrect_list) + + correct_info + + 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." + ), + "incorrect_params": validation_feedback["incorrect_params"], + "correct_params": validation_feedback["correct_params"] + } + logger.info(f"✗ Source node parameters incorrect - node: {node_id}, incorrect: {validation_feedback['incorrect_params']}") + # else: 部分提交且全部正确 → 不给任何 parameter_feedback,避免对未提交的参数发表意见 + + # 检查工具调用是否完全正确(输出与 golden outputs 匹配) + # 用于给模型正向反馈,让它知道这个工具已经正确调用过,避免重复调用 + # 注意:只有当输出完全匹配时才标记为 correct,不会在错误时提供具体错误信息 + # if tool_node.golden_output_values and output_values: + # is_correct = True + # for port_name, expected_value in tool_node.golden_output_values.items(): + # actual_value = output_values.get(port_name) + # if str(actual_value) != str(expected_value): + # is_correct = False + # break + + # if is_correct: + # response["tool_call_correct"] = True + # logger.info(f"✓ Tool called with correct result - node: {node_id}") + + # 只在有新内容掉落时才返回 newly_revealed + if newly_revealed: + response["newly_revealed"] = newly_revealed + + # 添加 investigate 提示(对于有待触发 HIDDEN_ITEM 掉落的工具) + if investigate_hints: + response["investigate_hints"] = investigate_hints + + # 3. 渐进式暴露机制 - 现在完全由 ITEM/HIDDEN_ITEM 边控制 + # 旧机制(基于 golden_input 检查)已被禁用 + # 新机制中,节点的可见性只由 ITEM/HIDDEN_ITEM 边触发决定 + # 上面的 ITEM/HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, output_values, tool_node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # response["newly_revealed"] = newly_revealed + # logger.info(f"Progressive reveal: {len(progressive_revealed)} nodes now ready") + + # Check if this is the win node + if node_id == scenario.win_node_id: + # 验证输出值是否等于预期的胜利值 + # 从节点的 golden_output_values 中获取预期值(在 _initialize_node_values 时从 JSON 加载) + expected_outputs = tool_node.golden_output_values + + # 检查实际输出是否与预期输出匹配 + is_correct = False + victory_string = None + mismatch_info = [] + + if expected_outputs and output_values: + # 检查每个预期输出端口的值是否匹配 + is_correct = True + for port_name, expected_value in expected_outputs.items(): + actual_value = output_values.get(port_name) + if actual_value != expected_value: + is_correct = False + mismatch_info.append(f"Port '{port_name}': expected '{expected_value}', actual '{actual_value}'") + logger.warning(f"Win node output mismatch - port: {port_name}, expected: {expected_value}, actual: {actual_value}") + + # 如果所有输出都匹配,使用第一个输出作为胜利字符串 + if is_correct and output_values: + victory_string = list(output_values.values())[0] + else: + logger.warning(f"Win node called but missing output values - expected: {expected_outputs}, actual: {output_values}") + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型调用工具获得输出后,需要自己识别这是否是胜利字符串并提交 + if is_correct: + logger.info(f"🎯 Win node called with correct output - case: {case_id}, node: {node_id}, victory: {victory_string}") + else: + logger.info(f"❌ Win node called with incorrect output - case: {case_id}, node: {node_id}") + + return response + +class UseItemRequest(BaseModel): + node_id: str = Field(..., description="The ID of the Item node to use (must be Item type)") + arguments: Dict[str, Any] = Field(default_factory=dict, description="Input arguments to provide to the item") + +@app.post("/env/{case_id}/use_item") +def use_item(case_id: str, req: UseItemRequest): + """ + Use an Item node by providing input arguments. + + This is specifically for Item nodes that require parameters to be "unlocked" or "activated", + such as containers that need a password/fingerprint. + + - Validates that the node is of type Item + - Checks if provided arguments match the item's golden_input_values + - If match: triggers ITEM-type edge drops and returns the item's content + - If not match: returns error message + """ + logger.info(f"Use item request - case_id: {case_id}, node_id: {req.node_id}, args: {req.arguments}") + STATS["use_items"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + item_node = scenario.nodes[req.node_id] + + if not item_node.is_revealed: + logger.warning(f"Attempt to use hidden item: {req.node_id}") + return {"ok": False, "error": "Item is not visible yet."} + + if item_node.type != "Item": + logger.warning(f"Attempt to use non-item node: {req.node_id} (type: {item_node.type})") + return {"ok": False, "error": "Only Item nodes can be used with use_item. Tools should be called with tool_call."} + + # 【新增】检查该 Item 是否已经被成功解锁 + # 如果已经被正确使用过,直接返回成功提示 + if item_node.if_success: + logger.info(f"Item already unlocked, returning success message: {req.node_id}") + return { + "ok": True, + "message": "This item has already been successfully unlocked by you." + } + + # 检查该 Item 是否真的需要通过 use_item 提供参数 + # 只有当 Item 有非 Item/Hidden_Item 类型的输入时,才应该使用 use_item + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + non_hidden_inputs = [ + inp for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + if not non_hidden_inputs: + # 该 Item 不需要参数,应该只使用 investigate + logger.warning(f"Attempt to use_item on a node that doesn't require parameters: {req.node_id}") + return { + "ok": False, + "error": "This item does not require parameters. Please use investigate to examine the item directly." + } + + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, item_node.golden_input_values) + + if not inputs_match_golden: + logger.info(f"✗ Item inputs do NOT match golden - node: {req.node_id}") + # 提供更详细的错误信息,帮助 Agent 理解问题 + # 只显示非 Item/Hidden_Item 类型的参数(Hidden_Item 由系统自动处理) + expected_params = [] + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + expected_params = [ + inp.get("name") for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + provided_params = list(req.arguments.keys()) if req.arguments else [] + + # 检查参数名是否匹配 + if set(expected_params) == set(provided_params): + # 参数名正确但值不匹配 - 不泄漏正确的值 + error_msg = f"Parameter names are correct, but the parameter values are incorrect. Please try using different parameter values." + else: + error_msg = f"Parameter names do not match. Expected parameter names: {expected_params}, you provided: {provided_params}." + + return { + "ok": False, + "error": error_msg + } + + logger.info(f"✓ Item inputs match golden - node: {req.node_id}, activating item") + + # 标记该 Item 已被正确使用 + item_node.if_success = True + + # 将 golden_output_values 追加到 actual_outputs_history + if item_node.golden_output_values: + item_node.actual_outputs_history.append(dict(item_node.golden_output_values)) + + # 触发 ITEM 类型边的掉落 + newly_revealed = [] + for edge in scenario.edges: + if edge.source_id == item_node.id and edge.connection_type == InterfaceType.ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from use_item on {req.node_id})") + + # 检查是否为 Win Node + win_node_id = scenario.win_node_id + is_win_node = (req.node_id == win_node_id) + + # 构建返回结果 + result = { + "ok": True, + "message": "Item used successfully.", + "content": item_node.golden_output_values if item_node.golden_output_values else None + } + + # 获取 narrative(如果存在) + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + narrative = raw_nodes_data[req.node_id].get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 如果是 Win Node,只记录日志 + if is_win_node: + logger.info(f"Win node (Item) unlocked via use_item - case: {case_id}, node: {req.node_id}") + + return result + + +class SubmitAnswerRequest(BaseModel): + answer: str = Field(..., description="The victory string to submit") + +@app.post("/env/{case_id}/submit_answer") +def submit_answer(case_id: str, req: SubmitAnswerRequest): + """ + 提交答案接口 + 被测模型在获得胜利字符串提示后,需要调用此接口提交答案 + """ + logger.info(f"Submit answer request - case_id: {case_id}, answer: {req.answer}") + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + + # 获取 win_node 的 golden_output_values + if not scenario.win_node_id: + logger.error(f"No win node defined for case: {case_id}") + return { + "ok": False, + "error": "This case has no victory node defined" + } + + win_node = scenario.nodes.get(scenario.win_node_id) + if not win_node: + logger.error(f"Win node not found: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node does not exist" + } + + # 获取正确的胜利字符串(取第一个 golden_output_value) + if win_node.golden_output_values: + correct_answer = list(win_node.golden_output_values.values())[0] + else: + logger.error(f"Win node has no golden_output_values: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node has no correct answer" + } + + # 验证提交的答案 + if req.answer == correct_answer: + logger.info(f"🎉 CORRECT ANSWER SUBMITTED - case: {case_id}, answer: {req.answer}") + return { + "ok": True, + "is_win": True, + "victory_message": f"🎉 Congratulations on successfully escaping the room! Your answer is correct: {req.answer}" + } + else: + logger.info(f"❌ INCORRECT ANSWER SUBMITTED - case: {case_id}, submitted: {req.answer}, correct: {correct_answer}") + return { + "ok": True, + "is_win": False, + "error": f"The submitted answer is incorrect. You submitted: {req.answer}" + } + +if __name__ == "__main__": + + uvicorn.run(app, host="0.0.0.0", port=8000) \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-4b3614c7/environment/puzzle/upstream/simulator.py b/tasks/agentescape-25-skeleton-4b3614c7/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-25-skeleton-4b3614c7/environment/puzzle/upstream/simulator.py @@ -0,0 +1,2911 @@ +import hashlib +import hmac +import base64 +import binascii +import zlib +import json +import uuid +import math +import re +from typing import Dict, Any, List + +class ToolSimulator: + def __init__(self): + """工具模拟器 + + 文件处理工具(zip_unzip, zip_unzip_file, zip_unzip_item, json_get, csv_query, + regex_search, graph_shortest_path)不需要真实文件系统。 + 这些工具只验证输入参数,然后返回预先初始化好的 golden_outputs。 + """ + self.tool_map = { + # 数论 + "calc_bigmul": self.calc_bigmul, + "calc_modexp": self.calc_modexp, + "calc_modexp_int": self.calc_modexp_int, + "calc_gcd": self.calc_gcd, + "calc_gcd_int": self.calc_gcd_int, + "calc_inv_mod": self.calc_inv_mod, + "calc_inv_mod_int": self.calc_inv_mod_int, + + # 哈希 + "hash_sha256": self.hash_sha256, + "hash_md5": self.hash_md5, + "hmac_sha256": self.hmac_sha256, + + # 编码 + "base64_decode": self.base64_decode, + "base64_encode": self.base64_encode, + "hex_decode": self.hex_decode, + "hex_encode": self.hex_encode, + "zlib_inflate": self.zlib_inflate, + "zlib_deflate": self.zlib_deflate, + + # 文件 + "zip_unzip": self.zip_unzip, + "zip_unzip_file": self.zip_unzip_file, + "zip_unzip_item": self.zip_unzip_item, + "regex_search": self.regex_search, + "json_get": self.json_get, + "csv_query": self.csv_query, + "code_py_exec": self.code_py_exec, + + # 图 + "graph_shortest_path": self.graph_shortest_path, + + # 加解密 (简化模拟) + "crypto_aes_cbc_decrypt": self.crypto_aes_cbc_decrypt, + "crypto_rsa_decrypt_hex": self.crypto_rsa_decrypt_hex, + + # 其他 + "num_base_convert": self.num_base_convert, + "time_convert": self.time_convert, + "checksum_crc32": self.checksum_crc32, + "geo_haversine": self.geo_haversine, + "otp_totp_generate": self.otp_totp_generate, + "unicode_norm": self.unicode_norm, + "text_bidi_sanitize": self.text_bidi_sanitize, + "text_xor_hex": self.text_xor_hex, + "text_rotN": self.text_rotN, + "luhn_check": self.luhn_check, + "iban_validate": self.iban_validate, + + # 物理 + "matter_synthesizer": self.matter_synthesizer, + + # 终端机 + "terminal_1": self.terminal_1, + "terminal_2": self.terminal_2, + "Logic Terminal": self.logic_terminal, + "Math Terminal": self.math_terminal, + "Encryption Terminal": self.crypt_terminal, + "Sequence Terminal": self.sequence_terminal + } + + def execute(self, tool_name: str, inputs: Dict[str, Any]) -> Dict[str, Any]: + if tool_name not in self.tool_map: + # Fallback for unknown tools: return dummy outputs based on expected output types + # This should ideally not happen if all tools are implemented + return {} + + try: + return self.tool_map[tool_name](inputs) + except Exception as e: + print(f"Error executing {tool_name}: {e}") + # Return empty or error indication? For generation, we might want to fail hard or return dummy. + # For now, return dummy to keep flow going, but log error. + return {} + + # --- Implementations --- + + def calc_bigmul(self, inputs): + # Check if required parameters are present + if "a" not in inputs or "b" not in inputs: + raise ValueError("Missing required parameters 'a' and/or 'b'") + + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + return {"product": str(a * b)} + except (ValueError, TypeError) as e: + raise ValueError(f"Failed to convert parameters to integers: {str(e)}") + + def calc_modexp(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + try: + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if isinstance(base, str): + base = int(base) + elif not isinstance(base, int): + raise ValueError("Parameter 'base' must be a string or integer") + + if isinstance(exp, str): + exp = int(exp) + elif not isinstance(exp, int): + raise ValueError("Parameter 'exp' must be a string or integer") + + if isinstance(mod, str): + mod = int(mod) + elif not isinstance(mod, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": str(pow(base, exp, mod))} + + def calc_modexp_int(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["base"], int): + raise ValueError("Parameter 'base' must be an integer") + if not isinstance(inputs["exp"], int): + raise ValueError("Parameter 'exp' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": pow(base, exp, mod)} + + def calc_gcd(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + # 计算 GCD 并返回字符串格式(符合 Big_Int 输出类型) + result = math.gcd(a, b) + return {"gcd": str(result)} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def calc_gcd_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["b"], int): + raise ValueError("Parameter 'b' must be an integer") + + # 获取参数 + a = inputs["a"] + b = inputs["b"] + + return {"gcd": math.gcd(a, b)} + + def calc_inv_mod(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + m = inputs["mod"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(m, str): + m = int(m) + elif not isinstance(m, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": str(pow(a, -1, m))} + except ValueError as e: + # 模逆不存在时,返回一个特殊值(用于数据传递) + # 在 DAG 生成阶段,这允许数据流继续 + return {"inv": str(a)} + + def calc_inv_mod_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + a = inputs["a"] + m = inputs["mod"] + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": pow(a, -1, m)} + except ValueError as e: + raise ValueError(f"Modular inverse does not exist: {str(e)}") + + def hash_sha256(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.sha256(text.encode()).hexdigest()} + + def hash_md5(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.md5(text.encode()).hexdigest()} + + def hmac_sha256(self, inputs): + # 参数检查 + if "hex_key" not in inputs: + raise ValueError("Missing required parameter: hex_key") + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["hex_key"], str): + raise ValueError("Parameter 'hex_key' must be a string") + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + try: + key = bytes.fromhex(inputs["hex_key"]) + text = inputs["text"].encode() + return {"hex": hmac.new(key, text, hashlib.sha256).hexdigest()} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def base64_decode(self, inputs): + # 参数检查 + if "data" not in inputs: + raise ValueError("Missing required parameter: data") + + # 类型检查 + if not isinstance(inputs["data"], str): + raise ValueError("Parameter 'data' must be a string") + + data = inputs["data"] + try: + return {"bytes_hex": binascii.hexlify(base64.b64decode(data)).decode()} + except Exception as e: + raise ValueError(f"Base64 decode error: {str(e)}") + + def base64_encode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"b64": base64.b64encode(bytes.fromhex(hex_data)).decode()} + except Exception as e: + raise ValueError(f"Base64 encode error: {str(e)}") + + def hex_decode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"text": bytes.fromhex(hex_data).decode('utf-8', errors='ignore')} + except Exception as e: + raise ValueError(f"Hex decode error: {str(e)}") + + def hex_encode(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + try: + return {"hex": text.encode().hex()} + except Exception as e: + raise ValueError(f"Hex encode error: {str(e)}") + + + # 到此处实现已经更新 + + def zlib_inflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("Parameter 'hex' must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("Missing required parameter: hex") + + try: + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空字符串 + if not hex_data: + raise ValueError("Empty hex string provided") + + # 检查十六进制字符串的有效性 + if len(hex_data) % 2 != 0: + raise ValueError("Hex string must have even length") + + # 检查是否只包含有效的十六进制字符 + if not all(c in '0123456789abcdefABCDEF' for c in hex_data): + raise ValueError("Invalid hex string provided") + + # 尝试解压缩 + return {"text": zlib.decompress(bytes.fromhex(hex_data)).decode('utf-8')} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hex string provided") from e + raise ValueError(f"Invalid zlib data: {e}") from e + except Exception as e: + raise RuntimeError(f"Failed to inflate data: {e}") from e + + def zlib_deflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("Parameter 'text' must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("Missing required parameter: text") + + try: + # 压缩文本 + return {"hex": zlib.compress(text.encode('utf-8')).hex()} + except Exception as e: + raise RuntimeError(f"Failed to deflate data: {e}") from e + + # --- File Operations --- + + def zip_unzip(self, inputs): + """ZIP 解压工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"files": golden_outputs.get("files", "")} + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return {"files": golden_outputs.get("files", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "files" in golden_outputs: + # 验证必需参数 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 检查类型 + if has_zip_id and not isinstance(zip_id, str): + return {"error": "Parameter 'zip_id' must be a string type"} + if has_password and not isinstance(password, str): + return {"error": "Parameter 'password' must be a string type"} + + # 验证输入是否与预期匹配 + if golden_inputs: + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return {"files": golden_outputs["files"]} + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + # 没有golden_inputs但有golden_outputs,直接返回输出 + return {"files": golden_outputs["files"]} + + # 如果没有预期输出,返回空结果 + return {"files": ""} + + def regex_search(self, inputs): + """正则搜索工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"matches": golden_outputs.get("matches", "[]")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "matches" in golden_outputs: + # 提取实际参数 + pattern = inputs.get("pattern") + file_id = inputs.get("file_id") + text = inputs.get("text") + + # 1. 检查必需参数 + if pattern is None: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["pattern"], + "message": "Missing required parameter 'pattern'" + } + } + + # 类型检查 + if not isinstance(pattern, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "pattern", + "message": "Parameter 'pattern' must be a string type" + } + } + if file_id is not None and not isinstance(file_id, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if text is not None and not isinstance(text, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "text", + "message": "Parameter 'text' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合 + provided_params = {} + if pattern is not None: + provided_params["pattern"] = pattern + if file_id is not None: + provided_params["file_id"] = file_id + if text is not None: + provided_params["text"] = text + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数(关键改进) + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_pattern = golden_inputs.get("pattern") + expected_file_id = golden_inputs.get("file_id") + expected_text = golden_inputs.get("text") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_pattern is not None: + if str(pattern) != str(expected_pattern): + incorrect_params.append("pattern") + else: + correct_params.append("pattern") + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_text is not None: + if str(text) != str(expected_text): + incorrect_params.append("text") + else: + correct_params.append("text") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "matches": "[]", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "matches": golden_outputs["matches"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空列表 + return {"matches": "[]"} + + def json_get(self, inputs): + """JSON 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"values": golden_outputs.get("values", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "values" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + jsonpath = inputs.get("jsonpath", "") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if jsonpath is not None and not isinstance(jsonpath, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "jsonpath", + "message": "Parameter 'jsonpath' must be a string type" + } + } + + # 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:jsonpath有默认值"") + provided_params = {} + if file_id is not None: + provided_params["file_id"] = file_id + if jsonpath != "": + provided_params["jsonpath"] = jsonpath + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_jsonpath = golden_inputs.get("jsonpath") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_jsonpath is not None: + if str(jsonpath) != str(expected_jsonpath): + incorrect_params.append("jsonpath") + else: + correct_params.append("jsonpath") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "values": "", + "_validation": validation_info + } + + # 所有验证通过,返回正确输出 + return { + "values": golden_outputs["values"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"values": ""} + + def csv_query(self, inputs): + """CSV 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"rows": golden_outputs.get("rows", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "rows" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + select_columns = inputs.get("select", "") + where_clause = inputs.get("where", "") + + # 1. 检查必需参数 + if file_id is None: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["file_id"], + "message": "Missing required parameter 'file_id'" + } + } + + # 类型检查 + if not isinstance(file_id, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if not isinstance(select_columns, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "select", + "message": "Parameter 'select' must be a string type" + } + } + if not isinstance(where_clause, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "where", + "message": "Parameter 'where' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:select和where有默认值"") + provided_params = {"file_id": file_id} + if select_columns != "": + provided_params["select"] = select_columns + if where_clause != "": + provided_params["where"] = where_clause + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_select = golden_inputs.get("select") + expected_where = golden_inputs.get("where") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_select is not None: + if str(select_columns) != str(expected_select): + incorrect_params.append("select") + else: + correct_params.append("select") + + if expected_where is not None: + if str(where_clause) != str(expected_where): + incorrect_params.append("where") + else: + correct_params.append("where") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "rows": "", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "rows": golden_outputs["rows"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"rows": ""} + + def graph_shortest_path(self, inputs): + """图最短路径工具 + + 如果有 _golden_outputs 或 _init_outputs,验证输入并返回预设输出。 + 否则执行真实的 Dijkstra 算法。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 检查是否在预设模式中(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + if golden_outputs and "path" in golden_outputs: + # 评测阶段但没有 golden_inputs,直接返回 outputs + if not golden_inputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 评测模式:验证输入参数是否匹配 golden 值 + src = inputs.get("src") + dst = inputs.get("dst") + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + + has_src = src is not None and src != "" + has_dst = dst is not None and dst != "" + + # 验证必需参数 + if not has_src or not has_dst: + missing = [] + if not has_src: + missing.append("src") + if not has_dst: + missing.append("dst") + return {"error": "Missing required parameters: " + ", ".join(missing)} + + # 类型检查 + if not isinstance(src, str): + return {"error": "Parameter 'src' must be a string"} + if not isinstance(dst, str): + return {"error": "Parameter 'dst' must be a string"} + + # 验证输入是否匹配期望值 + if golden_inputs: + expected_src = golden_inputs.get("src") + expected_dst = golden_inputs.get("dst") + expected_file_id = golden_inputs.get("file_id") + expected_graph_data = golden_inputs.get("graph_data") + + # 收集验证结果 + incorrect_params = [] + correct_params = [] + + # 检查必需参数是否匹配 + if expected_src is not None: + if str(src) != str(expected_src): + incorrect_params.append("src") + else: + correct_params.append("src") + + if expected_dst is not None: + if str(dst) != str(expected_dst): + incorrect_params.append("dst") + else: + correct_params.append("dst") + + # 检查可选参数(如果在 expected_inputs 中定义了) + if expected_file_id is not None: + if file_id != expected_file_id: + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_graph_data is not None: + if graph_data != expected_graph_data: + incorrect_params.append("graph_data") + else: + correct_params.append("graph_data") + + # 如果有参数不正确,返回详细的反馈 + if incorrect_params: + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 验证通过,返回预设的输出 + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 获取参数(真实执行路径) + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + # Support both src/dst (interface definition) and start/end (original implementation) + start = inputs.get("src") + end = inputs.get("dst") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + raise TypeError("file_id must be a string") + + if graph_data is not None and not isinstance(graph_data, str): + raise TypeError("graph_data must be a string") + + if start is not None and not isinstance(start, str): + raise TypeError("src/start must be a string") + + if end is not None and not isinstance(end, str): + raise TypeError("dst/end must be a string") + + # 检查必需参数 + if file_id is None and graph_data is None: + raise ValueError("Either file_id or graph_data must be provided") + + if start is None: + raise ValueError("src/start parameter is required") + + if end is None: + raise ValueError("dst/end parameter is required") + + # Get graph content + content = None + if file_id is not None: + # 尝试从 VFS 获取(如果存在) + if hasattr(self, 'vfs') and file_id in self.vfs: + content = self.vfs[file_id] + else: + # VFS 不存在或文件不在 VFS 中 + # 返回一个默认的空图结果,或者抛出错误提示需要 init_outputs + raise ValueError( + f"File '{file_id}' not found. For tools that require files, " + f"please provide init_outputs in the initial_values." + ) + elif graph_data is not None: + content = graph_data + + if content is None: + content = "{}" + + try: + # Parse graph data + graph = json.loads(content) + + # 类型检查 + if not isinstance(graph, dict): + raise TypeError("Graph data must be a dictionary") + + # If graph is not in the expected format, try to extract adjacency list + if "nodes" in graph and "edges" in graph: + # 验证nodes和edges的类型 + if not isinstance(graph["nodes"], list): + raise TypeError("Nodes must be a list") + + if not isinstance(graph["edges"], list): + raise TypeError("Edges must be a list") + + # Convert from nodes/edges format to adjacency list + adjacency_list = {} + for node in graph["nodes"]: + # 验证node类型 + if not isinstance(node, dict): + raise TypeError("Each node must be a dictionary") + + # Use node ID as key, not the entire node dictionary + node_id = node.get("id", "") + if node_id: + adjacency_list[node_id] = {} + + for edge in graph["edges"]: + # 验证edge类型 + if not isinstance(edge, dict): + raise TypeError("Each edge must be a dictionary") + + u = edge["from"] + v = edge["to"] + weight = edge.get("weight", 1) # Default to unweighted + + # 类型检查 + if not isinstance(u, str): + raise TypeError("Edge 'from' must be a string") + + if not isinstance(v, str): + raise TypeError("Edge 'to' must be a string") + + if not isinstance(weight, (int, float)): + raise TypeError("Edge weight must be a number") + + if u not in adjacency_list: + adjacency_list[u] = {} + if v not in adjacency_list: + adjacency_list[v] = {} + + adjacency_list[u][v] = weight + # If undirected, add reverse edge + if not edge.get("directed", False): + adjacency_list[v][u] = weight + elif isinstance(graph, dict): + # Already in adjacency list format + adjacency_list = graph + + # 验证邻接表结构 + for node, neighbors in adjacency_list.items(): + if not isinstance(neighbors, dict): + raise TypeError("Adjacency list must be a dictionary of dictionaries") + + for neighbor, weight in neighbors.items(): + if not isinstance(weight, (int, float)): + raise TypeError("Edge weights must be numbers") + else: + raise TypeError("Graph data must be a dictionary") + + # 检查起点和终点是否为空 + if not start: + raise ValueError("Start node cannot be empty") + + if not end: + raise ValueError("End node cannot be empty") + + # 检查起点和终点是否在图中 + if start not in adjacency_list: + raise ValueError(f"Start node '{start}' not found in graph") + + if end not in adjacency_list: + raise ValueError(f"End node '{end}' not found in graph") + + # Dijkstra's algorithm implementation + import heapq + + # Initialize distances and previous nodes + distances = {node: float('infinity') for node in adjacency_list} + previous = {node: None for node in adjacency_list} + distances[start] = 0 + + # Priority queue + pq = [(0, start)] + heapq.heapify(pq) + + while pq: + current_dist, current_node = heapq.heappop(pq) + + # If we've reached the end node, we can break early + if current_node == end: + break + + # Nodes can be added multiple times to the priority queue, but we only process them once + if current_dist > distances[current_node]: + continue + + # Explore neighbors + for neighbor, weight in adjacency_list[current_node].items(): + distance = current_dist + weight + + # If a shorter path is found + if distance < distances[neighbor]: + distances[neighbor] = distance + previous[neighbor] = current_node + heapq.heappush(pq, (distance, neighbor)) + + # Reconstruct the shortest path + path = [] + current = end + while current is not None: + path.append(current) + current = previous[current] + path.reverse() # Reverse to get from start to end + + # Check if path exists + if not path or path[0] != start: + return {"path": "[]", "cost": 0} + + return { + "path": json.dumps(path), + "cost": distances[end] + } + except json.JSONDecodeError as e: + raise ValueError(f"Invalid JSON in graph data: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in graph_shortest_path: {str(e)}") + + # --- Crypto (Simplified) --- + def crypto_aes_cbc_decrypt(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 (使用模板中定义的参数名) + hex_cipher = inputs.get("hex_cipher") + hex_key = inputs.get("hex_key") + hex_iv = inputs.get("hex_iv") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + + if hex_key is not None and not isinstance(hex_key, str): + raise TypeError("hex_key must be a string") + + if hex_iv is not None and not isinstance(hex_iv, str): + raise TypeError("hex_iv must be a string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + + if hex_key is None: + raise ValueError("hex_key parameter is required") + + if hex_iv is None: + raise ValueError("hex_iv parameter is required") + + from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes + from cryptography.hazmat.backends import default_backend + from cryptography.hazmat.primitives import padding + + try: + # Convert hex strings to bytes + ciphertext = bytes.fromhex(hex_cipher) + key = bytes.fromhex(hex_key) + iv = bytes.fromhex(hex_iv) + + # Validate key length (AES-128, AES-192, AES-256) + if len(key) not in [16, 24, 32]: + raise ValueError("Invalid key length. Must be 16, 24, or 32 bytes.") + + if len(iv) != 16: + raise ValueError("Invalid IV length. Must be 16 bytes.") + + # Create cipher object + cipher = Cipher( + algorithms.AES(key), + modes.CBC(iv), + backend=default_backend() + ) + + decryptor = cipher.decryptor() + + # Decrypt the ciphertext + padded_plaintext = decryptor.update(ciphertext) + decryptor.finalize() + + # Remove PKCS7 padding + unpadder = padding.PKCS7(128).unpadder() + plaintext = unpadder.update(padded_plaintext) + unpadder.finalize() + + # Return decrypted text + return {"text": plaintext.decode('utf-8', errors='ignore')} + except ValueError as e: + if "non-hexadecimal number found in fromhex()" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher, hex_key, or hex_iv") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in crypto_aes_cbc_decrypt: {str(e)}") + + def crypto_rsa_decrypt_hex(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_cipher = inputs.get("hex_cipher") + n = inputs.get("n") + d = inputs.get("d") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + if n is not None and not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + if d is not None and not isinstance(d, (int, str)): + raise TypeError("d must be an integer or string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + if n is None: + raise ValueError("n parameter is required") + if d is None: + raise ValueError("d parameter is required") + + try: + # Convert parameters to appropriate types + cipher_int = int(hex_cipher, 16) + n_int = int(n) if isinstance(n, str) else n + d_int = int(d) if isinstance(d, str) else d + + # RSA decryption: plaintext = ciphertext^d mod n + plaintext_int = pow(cipher_int, d_int, n_int) + + # Convert result to hex and then to text + plaintext_hex = hex(plaintext_int)[2:] + + # Pad with leading zero if odd length + if len(plaintext_hex) % 2 != 0: + plaintext_hex = '0' + plaintext_hex + + # Convert hex to bytes and then to text + try: + plaintext_bytes = bytes.fromhex(plaintext_hex) + plaintext_text = plaintext_bytes.decode('utf-8', errors='ignore') + except: + # If decoding fails, return hex representation + plaintext_text = plaintext_hex + + return {"text": plaintext_text} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in crypto_rsa_decrypt_hex: {str(e)}") + + # --- Others --- + def num_base_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + s = inputs.get("s") + from_base = inputs.get("from_base") + to_base = inputs.get("to_base") + + # 类型检查 - 接受 str 或 int + if s is not None and not isinstance(s, (str, int)): + raise TypeError("s must be a string or integer") + + if from_base is not None and not isinstance(from_base, (int, str)): + raise TypeError("from_base must be an integer") + + if to_base is not None and not isinstance(to_base, (int, str)): + raise TypeError("to_base must be an integer") + + # 检查必需参数 + if s is None: + raise ValueError("s parameter is required") + + if from_base is None: + raise ValueError("from_base parameter is required") + + if to_base is None: + raise ValueError("to_base parameter is required") + + try: + # Convert to int if needed + from_base = int(from_base) if isinstance(from_base, str) else from_base + to_base = int(to_base) if isinstance(to_base, str) else to_base + s_str = str(s) + + # 验证基数范围 + if from_base < 2 or from_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + if to_base < 2 or to_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + # Convert from source base to decimal + val = int(s_str, from_base) + + # Convert from decimal to target base + if to_base == 10: + result = str(val) + elif to_base == 16: + result = hex(val)[2:] + elif to_base == 8: + result = oct(val)[2:] + elif to_base == 2: + result = bin(val)[2:] + else: + # Generic base conversion for other bases + if val == 0: + result = "0" + else: + digits = "0123456789abcdefghijklmnopqrstuvwxyz" + result = "" + n = abs(val) + while n: + result = digits[n % to_base] + result + n //= to_base + if val < 0: + result = "-" + result + + return {"str": result} + except ValueError as e: + raise ValueError(f"Invalid number format: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in num_base_convert: {str(e)}") + + def time_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iso = inputs.get("iso") + timestamp = inputs.get("timestamp") + datetime_str = inputs.get("datetime") + from_tz = inputs.get("from_tz") + to_tz = inputs.get("to_tz") + format_str = inputs.get("format") + + # 类型检查 + if iso is not None and not isinstance(iso, str): + raise TypeError("iso must be a string") + + if timestamp is not None and not isinstance(timestamp, (str, int, float)): + raise TypeError("timestamp must be a string, integer, or float") + + if datetime_str is not None and not isinstance(datetime_str, str): + raise TypeError("datetime must be a string") + + if from_tz is not None and not isinstance(from_tz, str): + raise TypeError("from_tz must be a string") + + if to_tz is not None and not isinstance(to_tz, str): + raise TypeError("to_tz must be a string") + + if format_str is not None and not isinstance(format_str, str): + raise TypeError("format must be a string") + + # 设置默认值 + if from_tz is None: + from_tz = "UTC" + + if to_tz is None: + to_tz = "UTC" + + import datetime + import pytz + + # 验证时区参数 + try: + if from_tz: + pytz.timezone(from_tz) + if to_tz: + pytz.timezone(to_tz) + except Exception: + raise ValueError("Invalid timezone provided") + + try: + # Parse input time + dt = None + + if iso is not None: + # Parse ISO 8601 format + dt = datetime.datetime.fromisoformat(iso.replace('Z', '+00:00')) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=pytz.UTC) + elif timestamp is not None: + # Parse Unix timestamp + timestamp = float(timestamp) + dt = datetime.datetime.fromtimestamp(timestamp, pytz.UTC) + elif datetime_str is not None: + # Parse datetime string + # Try common formats + formats_to_try = [ + "%Y-%m-%d %H:%M:%S", + "%Y-%m-%d %H:%M:%S.%f", + "%Y-%m-%d", + "%m/%d/%Y %H:%M:%S", + "%m/%d/%Y" + ] + + parse_success = False + for fmt in formats_to_try: + try: + dt = datetime.datetime.strptime(datetime_str, fmt) + dt = pytz.timezone(from_tz).localize(dt) + parse_success = True + break + except ValueError: + continue + + if not parse_success: + raise ValueError("Unable to parse datetime string with common formats") + else: + # 如果没有提供任何时间参数,则使用当前时间 + dt = datetime.datetime.now(pytz.UTC) + except ValueError as e: + raise ValueError(f"Error parsing time input: {str(e)}") + except Exception as e: + raise RuntimeError(f"Unexpected error parsing time input: {str(e)}") + + try: + # Convert timezone + if from_tz != to_tz: + dt = dt.astimezone(pytz.timezone(to_tz)) + + # Format outputs + result = { + "iso": dt.isoformat(), + "timestamp": str(dt.timestamp()), + "datetime": dt.strftime("%Y-%m-%d %H:%M:%S"), + "date": dt.strftime("%Y-%m-%d"), + "time": dt.strftime("%H:%M:%S"), + "timezone": to_tz + } + + # Add custom format if requested + if format_str: + try: + result["formatted"] = dt.strftime(format_str) + except ValueError as e: + raise ValueError(f"Invalid format string: {str(e)}") + + return result + except Exception as e: + raise RuntimeError(f"Error in time_convert: {str(e)}") + + def checksum_crc32(self, inputs): + import zlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("hex must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("hex parameter is required") + + try: + # 验证十六进制字符串 + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空 + if not hex_data: + raise ValueError("hex data cannot be empty") + + # 检查是否为有效的十六进制字符串 + if not all(c in "0123456789abcdefABCDEF" for c in hex_data): + raise ValueError("hex must be a valid hexadecimal string") + + # 检查长度是否为偶数 + if len(hex_data) % 2 != 0: + raise ValueError("hex must have even number of characters") + + val = zlib.crc32(bytes.fromhex(hex_data)) + # 确保 hex 输出是 8 位,前导补 0 + return {"hex": f"{val:08x}", "int": val} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in checksum_crc32: {str(e)}") + + def geo_haversine(self, inputs): + import math + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + lat1 = inputs.get("lat1") + lon1 = inputs.get("lon1") + lat2 = inputs.get("lat2") + lon2 = inputs.get("lon2") + + # 类型检查 + if lat1 is not None and not isinstance(lat1, (int, float, str)): + raise TypeError("lat1 must be a number or string") + if lon1 is not None and not isinstance(lon1, (int, float, str)): + raise TypeError("lon1 must be a number or string") + if lat2 is not None and not isinstance(lat2, (int, float, str)): + raise TypeError("lat2 must be a number or string") + if lon2 is not None and not isinstance(lon2, (int, float, str)): + raise TypeError("lon2 must be a number or string") + + # 检查必需参数 + if lat1 is None: + raise ValueError("lat1 parameter is required") + if lon1 is None: + raise ValueError("lon1 parameter is required") + if lat2 is None: + raise ValueError("lat2 parameter is required") + if lon2 is None: + raise ValueError("lon2 parameter is required") + + try: + # 转换为浮点数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(lat1, str): + lat1 = float(lat1) + elif not isinstance(lat1, (int, float)): + raise TypeError("lat1 must be a number or string") + else: + lat1 = float(lat1) + + if isinstance(lon1, str): + lon1 = float(lon1) + elif not isinstance(lon1, (int, float)): + raise TypeError("lon1 must be a number or string") + else: + lon1 = float(lon1) + + if isinstance(lat2, str): + lat2 = float(lat2) + elif not isinstance(lat2, (int, float)): + raise TypeError("lat2 must be a number or string") + else: + lat2 = float(lat2) + + if isinstance(lon2, str): + lon2 = float(lon2) + elif not isinstance(lon2, (int, float)): + raise TypeError("lon2 must be a number or string") + else: + lon2 = float(lon2) + + # Validate coordinates (approximate range check) + if not (-90 <= lat1 <= 90): + raise ValueError("lat1 must be between -90 and 90") + if not (-90 <= lat2 <= 90): + raise ValueError("lat2 must be between -90 and 90") + if not (-180 <= lon1 <= 180): + raise ValueError("lon1 must be between -180 and 180") + if not (-180 <= lon2 <= 180): + raise ValueError("lon2 must be between -180 and 180") + + # Earth radius in meters + R = 6371000 # Approximate radius of Earth + + # Convert degrees to radians + lat1_rad = math.radians(lat1) + lon1_rad = math.radians(lon1) + lat2_rad = math.radians(lat2) + lon2_rad = math.radians(lon2) + + # Calculate differences + delta_lat = lat2_rad - lat1_rad + delta_lon = lon2_rad - lon1_rad + + # Haversine formula + a = math.sin(delta_lat / 2) ** 2 + \ + math.cos(lat1_rad) * math.cos(lat2_rad) * \ + math.sin(delta_lon / 2) ** 2 + c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) + distance_m = R * c + + # Return distance in meters + return {"meters": round(distance_m, 2)} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in geo_haversine: {str(e)}") + + def otp_totp_generate(self, inputs): + import hmac + import hashlib + import base64 + import time + import struct + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + base32_secret = inputs.get("base32_secret") + step = inputs.get("step", 30) # Default to 30 seconds + digits = inputs.get("digits", 6) # Default to 6 digits + timestamp_iso = inputs.get("timestamp_iso", "") + algo = inputs.get("algo", "sha1") # Default to sha1 as current implementation only supports this + + # 类型检查 + if base32_secret is not None and not isinstance(base32_secret, str): + raise TypeError("base32_secret must be a string") + if not isinstance(step, (int, str)): + raise TypeError("step must be an integer or string") + if not isinstance(digits, (int, str)): + raise TypeError("digits must be an integer or string") + if not isinstance(timestamp_iso, str): + raise TypeError("timestamp_iso must be a string") + if not isinstance(algo, str): + raise TypeError("algo must be a string") + + # 检查必需参数 + if base32_secret is None: + raise ValueError("base32_secret parameter is required") + + try: + # Convert step and digits to appropriate types + step = int(step) + digits = int(digits) + if digits < 6 or digits > 8: + raise ValueError("Digits must be between 6 and 8") + + # Convert timestamp_iso to integer timestamp + if timestamp_iso: + import datetime + dt = datetime.datetime.fromisoformat(timestamp_iso.replace('Z', '+00:00')) + timestamp = int(dt.timestamp()) + else: + timestamp = int(time.time()) + + # Calculate counter value (T = floor(timestamp / step)) + counter = timestamp // step + + # Decode the base32 secret + # Add padding if necessary (base64 requires padding to be multiple of 8) + base32_secret = base32_secret.upper().replace(' ', '') + if len(base32_secret) % 8 != 0: + base32_secret += '=' * (8 - (len(base32_secret) % 8)) + key = base64.b32decode(base32_secret, casefold=True) + + # Calculate HMAC-SHA1 + counter_bytes = struct.pack('>Q', counter) # Big-endian 8-byte integer + hmac_hash = hmac.new(key, counter_bytes, hashlib.sha1).digest() + + # Dynamic truncation + offset = hmac_hash[-1] & 0xF + code = struct.unpack('>I', hmac_hash[offset:offset+4])[0] & 0x7FFFFFFF + + # Generate the OTP + otp = str(code % (10 ** digits)).zfill(digits) + + # Calculate remaining time until next OTP change + remaining_time = step - (timestamp % step) + + return {"totp": otp, "remaining_time": remaining_time, "time_step": step} + except ValueError as e: + if "invalid literal for int()" in str(e): + raise ValueError("step and digits must be valid integers") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in otp_totp_generate: {str(e)}") + + def unicode_norm(self, inputs): + import unicodedata + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + form = inputs.get("form", "NFC") # Default to NFC + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if form is not None and not isinstance(form, str): + raise TypeError("form must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Normalize form (NFC, NFD, NFKC, NFKD) + form = form.upper().strip() + + if form not in ['NFC', 'NFD', 'NFKC', 'NFKD']: + raise ValueError(f"Invalid normalization form: {form}. Must be one of: NFC, NFD, NFKC, NFKD") + + # Apply Unicode normalization + normalized_text = unicodedata.normalize(form, text) + + return {"text": normalized_text} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in unicode_norm: {str(e)}") + + def text_bidi_sanitize(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Bidi control characters to remove + bidi_controls = [ + '\u200E', # LEFT-TO-RIGHT MARK + '\u200F', # RIGHT-TO-LEFT MARK + '\u202A', # LEFT-TO-RIGHT EMBEDDING + '\u202B', # RIGHT-TO-LEFT EMBEDDING + '\u202C', # POP DIRECTIONAL FORMATTING + '\u202D', # LEFT-TO-RIGHT OVERRIDE + '\u202E', # RIGHT-TO-LEFT OVERRIDE + '\u2066', # LEFT-TO-RIGHT ISOLATE + '\u2067', # RIGHT-TO-LEFT ISOLATE + '\u2068', # FIRST STRONG ISOLATE + '\u2069', # POP DIRECTIONAL ISOLATE + ] + + # Remove all Bidi control characters + sanitized_text = text + for control_char in bidi_controls: + sanitized_text = sanitized_text.replace(control_char, '') + + return {"text": sanitized_text} + except Exception as e: + raise RuntimeError(f"Error in text_bidi_sanitize: {str(e)}") + + def text_xor_hex(self, inputs): + import binascii + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_a = inputs.get("hex_a") + hex_b = inputs.get("hex_b") + + # 类型检查 + if hex_a is not None and not isinstance(hex_a, str): + raise TypeError("hex_a must be a string") + if hex_b is not None and not isinstance(hex_b, str): + raise TypeError("hex_b must be a string") + + # 检查必需参数 + if hex_a is None: + raise ValueError("hex_a parameter is required") + if hex_b is None: + raise ValueError("hex_b parameter is required") + + try: + # Remove any whitespace + hex_a = hex_a.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + hex_b = hex_b.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + + # Validate hex strings + if not (all(c in "0123456789abcdefABCDEF" for c in hex_a) and len(hex_a) % 2 == 0): + raise ValueError("hex_a must be a valid hexadecimal string with even length") + if not (all(c in "0123456789abcdefABCDEF" for c in hex_b) and len(hex_b) % 2 == 0): + raise ValueError("hex_b must be a valid hexadecimal string with even length") + + # Convert hex strings to bytes + bytes_a = binascii.unhexlify(hex_a) + bytes_b = binascii.unhexlify(hex_b) + + # Make the byte arrays the same length by padding the shorter one with zeros + max_len = max(len(bytes_a), len(bytes_b)) + bytes_a = bytes_a.ljust(max_len, b'\x00') + bytes_b = bytes_b.ljust(max_len, b'\x00') + + # Perform XOR operation + result_bytes = bytes(a ^ b for a, b in zip(bytes_a, bytes_b)) + + # Convert result back to hex + result_hex = binascii.hexlify(result_bytes).decode('utf-8') + + return {"hex": result_hex} + except ValueError as e: + if "Non-hexadecimal digit found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in text_xor_hex: {str(e)}") + + def text_rotN(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + n = inputs.get("n", 0) + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + n = int(n) + except ValueError: + raise ValueError("n must be a valid integer") + + result = [] + for char in text: + if char.isupper(): + # Rotate uppercase letters + result_char = chr((ord(char) - ord('A') + n) % 26 + ord('A')) + result.append(result_char) + elif char.islower(): + # Rotate lowercase letters + result_char = chr((ord(char) - ord('a') + n) % 26 + ord('a')) + result.append(result_char) + else: + # Keep non-alphabetic characters unchanged + result.append(char) + + return {"text": ''.join(result)} + + def luhn_check(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数(支持 card_number 和 number 两个参数名) + card_number = inputs.get("number") or inputs.get("card_number") + + # 类型检查 + if card_number is not None and not isinstance(card_number, str): + raise TypeError("number must be a string") + + # 检查必需参数 + if card_number is None: + raise ValueError("number parameter is required") + + try: + # 如果输入是JSON数组或其他非数字字符串,返回该字符串本身(用于数据传递) + # 这种情况发生在DAG设计中类型不匹配时 + if card_number.startswith('[') or card_number.startswith('{'): + # 输入是JSON,直接返回原值(用于传递) + return {"valid": card_number} + + # Remove whitespace from card number + card_number = card_number.replace(" ", "").replace("-", "") + + # Check if card number is all digits + if not card_number.isdigit() or len(card_number) < 13: + return {"valid": "false"} + + # Implement Luhn algorithm + total = 0 + reverse_digits = card_number[::-1] # Reverse the number for easier processing + + for i, digit in enumerate(reverse_digits): + num = int(digit) + if i % 2 == 1: # Every second digit starting from the right (which is first in reversed string) + num *= 2 + if num > 9: + num -= 9 # Equivalent to sum of digits for 2-digit numbers + total += num + + # Check if total is divisible by 10 + is_valid = total % 10 == 0 + return {"valid": "true" if is_valid else "false"} + except Exception as e: + raise RuntimeError(f"Error in luhn_check: {str(e)}") + + def iban_validate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iban = inputs.get("iban") + + # 类型检查 + if iban is not None and not isinstance(iban, str): + raise TypeError("iban must be a string") + + # 检查必需参数 + if iban is None: + raise ValueError("iban parameter is required") + + try: + # Remove whitespace from IBAN + iban = iban.replace(" ", "") + + # Basic length and format check + if not (len(iban) >= 15 and len(iban) <= 34): + return {"valid": "False"} + + if not (iban[:2].isalpha() and iban[2:].isdigit()): + return {"valid": "False"} + + # Move first four characters to the end + rearranged = iban[4:] + iban[:4] + + # Replace letters with numbers (A=10, B=11, ..., Z=35) + numeric_iban = '' + for char in rearranged: + if char.isdigit(): + numeric_iban += char + else: + numeric_iban += str(ord(char.upper()) - ord('A') + 10) + + # Perform modulo 97 check + # Use step-by-step approach for very large numbers + remainder = 0 + for char in numeric_iban: + remainder = (remainder * 10 + int(char)) % 97 + + is_valid = remainder == 1 + return {"valid": "True" if is_valid else "False"} + except Exception as e: + raise RuntimeError(f"Error in iban_validate: {str(e)}") + + def matter_synthesizer(self, inputs): + import hashlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + blueprint = inputs.get("blueprint") + + # 类型检查 + if blueprint is not None and not isinstance(blueprint, str): + raise TypeError("blueprint must be a string") + + try: + # Get blueprint parameter as defined in interface + if blueprint is None: + blueprint = "" + + # Generate a unique item ID based on the blueprint + # This ensures the same blueprint always produces the same item + blueprint_hash = hashlib.sha256(blueprint.encode()).hexdigest()[:16] + + # Create a synthesized item with a deterministic ID based on blueprint + synthesized_item = f"synthesized_item_{blueprint_hash}" + + return {"output_slot": synthesized_item} + except Exception as e: + raise RuntimeError(f"Error in matter_synthesizer: {str(e)}") + + # --- Terminal Implementations --- + def terminal_1(self, inputs): + """ + terminal_1: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 只返回 text_output + - 只输入正确的 slot_b → 只返回 hex_output + - 同时输入正确的 slot_a 和 slot_b → 返回 item_dispenser(物品掉落) + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + # 检查哪些输入被提供了 + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值是否正确(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + expected_a = golden_inputs["slot_a"] + a_valid = str(slot_a) == str(expected_a) + + if has_b and "slot_b" in golden_inputs: + expected_b = golden_inputs["slot_b"] + b_valid = str(slot_b) == str(expected_b) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 item_dispenser + if has_a and has_b: + if a_valid and b_valid: + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 text_output + if has_a and not has_b: + if a_valid: + if "text_output" in golden_outputs: + result["text_output"] = golden_outputs["text_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 hex_output + if has_b and not has_a: + if b_valid: + if "hex_output" in golden_outputs: + result["hex_output"] = golden_outputs["hex_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def terminal_2(self, inputs): + """ + terminal_2: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 text_result + - 同时输入正确的 num1 和 num2 → 返回 hex_result 和 math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + # 检查哪些输入被提供了 + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值是否正确(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + expected_num1 = golden_inputs["num1"] + num1_valid = str(num1) == str(expected_num1) + + if has_num2 and "num2" in golden_inputs: + expected_num2 = golden_inputs["num2"] + num2_valid = str(num2) == str(expected_num2) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 hex_result 和 math_token + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 text_result + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "text_result" in golden_outputs: + result["text_result"] = golden_outputs["text_result"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def logic_terminal(self, inputs): + """ + Logic Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 返回 screen(部分输出) + - 只输入正确的 slot_b → 返回 screen 和 secondary_output + - 同时输入正确的 slot_a 和 slot_b → 返回 screen, secondary_output, item_dispenser + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + a_valid = str(slot_a) == str(golden_inputs["slot_a"]) + + if has_b and "slot_b" in golden_inputs: + b_valid = str(slot_b) == str(golden_inputs["slot_b"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出(包括 item_dispenser) + if has_a and has_b: + if a_valid and b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 screen(部分输出) + if has_a and not has_b: + if a_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 screen 和 secondary_output + if has_b and not has_a: + if b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def math_terminal(self, inputs): + """ + Math Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 result_display + - 同时输入正确的 num1 和 num2 → 返回 result_display, hex_result, math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + num1_valid = str(num1) == str(golden_inputs["num1"]) + + if has_num2 and "num2" in golden_inputs: + num2_valid = str(num2) == str(golden_inputs["num2"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 result_display + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def crypt_terminal(self, inputs): + """ + Encryption Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 plaintext → 返回 status(部分输出) + - 同时输入正确的 plaintext 和 key → 返回 status, encrypted_hex, encryption_chip + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + plaintext = inputs.get("plaintext") + key = inputs.get("key") + + has_plaintext = plaintext is not None and plaintext != "" + has_key = key is not None and key != "" + + # 验证输入值(与 golden values 比较) + plaintext_valid = False + key_valid = False + + if has_plaintext and "plaintext" in golden_inputs: + plaintext_valid = str(plaintext) == str(golden_inputs["plaintext"]) + + if has_key and "key" in golden_inputs: + key_valid = str(key) == str(golden_inputs["key"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_plaintext and has_key: + if plaintext_valid and key_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + if "encrypted_hex" in golden_outputs: + result["encrypted_hex"] = golden_outputs["encrypted_hex"] + if "encryption_chip" in golden_outputs: + result["encryption_chip"] = golden_outputs["encryption_chip"] + return result + else: + incorrect_params = [] + correct_params = [] + if not plaintext_valid: + incorrect_params.append("plaintext") + else: + correct_params.append("plaintext") + if not key_valid: + incorrect_params.append("key") + else: + correct_params.append("key") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 plaintext 且正确 → 返回 status(部分输出) + if has_plaintext and not has_key: + if plaintext_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: plaintext"} + + # 只提供 key 但没有 plaintext + if has_key and not has_plaintext: + return {"error": "plaintext required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + def sequence_terminal(self, inputs): + """ + Sequence Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 sequence → 返回 verification(部分输出) + - 同时输入正确的 sequence 和 checksum → 返回 verification, auth_code, access_card + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + sequence = inputs.get("sequence") + checksum = inputs.get("checksum") + + has_sequence = sequence is not None and sequence != "" + has_checksum = checksum is not None and checksum != "" + + # 验证输入值(与 golden values 比较) + sequence_valid = False + checksum_valid = False + + if has_sequence and "sequence" in golden_inputs: + sequence_valid = str(sequence) == str(golden_inputs["sequence"]) + + if has_checksum and "checksum" in golden_inputs: + checksum_valid = str(checksum) == str(golden_inputs["checksum"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_sequence and has_checksum: + if sequence_valid and checksum_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + if "auth_code" in golden_outputs: + result["auth_code"] = golden_outputs["auth_code"] + if "access_card" in golden_outputs: + result["access_card"] = golden_outputs["access_card"] + return result + else: + incorrect_params = [] + correct_params = [] + if not sequence_valid: + incorrect_params.append("sequence") + else: + correct_params.append("sequence") + if not checksum_valid: + incorrect_params.append("checksum") + else: + correct_params.append("checksum") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 sequence 且正确 → 返回 verification(部分输出) + if has_sequence and not has_checksum: + if sequence_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: sequence"} + + # 只提供 checksum 但没有 sequence + if has_checksum and not has_sequence: + return {"error": "sequence required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + # --- Additional File Tools --- + + def zip_unzip_file(self, inputs): + """ZIP 解压文件工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def zip_unzip_item(self, inputs): + """ZIP 解压道具工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def code_py_exec(self, inputs): + """Python 代码执行工具 + + 这是一个真实执行的工具,在 DAG 生成阶段和运行时评测阶段都会执行代码。 + 输入: code (Python 代码字符串) + 输出: stdout (标准输出,包含执行结果和错误信息) + + 特殊行为: + - 如果代码定义了 main() 函数,会自动调用它 + - 如果执行出错,错误信息会包含在 stdout 中 + """ + code = inputs.get("code", "") + + if not code: + return {"stdout": "Error: No code provided"} + + try: + # 创建一个受限的执行环境 + import io + import sys + + # 捕获标准输出和标准错误 + old_stdout = sys.stdout + old_stderr = sys.stderr + sys.stdout = io.StringIO() + sys.stderr = io.StringIO() + + # 执行代码 + exec_globals = {"__builtins__": __builtins__} + exec_locals = {} + exec(code, exec_globals, exec_locals) + + # 如果定义了 main() 函数,自动调用它 + if 'main' in exec_locals and callable(exec_locals['main']): + exec_locals['main']() + + # 获取输出 + stdout_value = sys.stdout.getvalue() + stderr_value = sys.stderr.getvalue() + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 合并 stdout 和 stderr + output = stdout_value + if stderr_value: + output += ("\n" if output else "") + f"[stderr] {stderr_value}" + + # 如果没有任何输出,尝试返回 result 变量的值 + if not output: + result = exec_locals.get("_result") or exec_locals.get("result") + if result is not None: + output = str(result) + + return {"stdout": output if output else "(no output)"} + + except Exception as e: + # 恢复标准输出和错误输出 + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 返回错误信息 + return {"stdout": f"Error: {type(e).__name__}: {str(e)}"} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-4b3614c7/environment/puzzle/worker.Dockerfile b/tasks/agentescape-25-skeleton-4b3614c7/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-25-skeleton-4b3614c7/environment/puzzle/worker.Dockerfile @@ -0,0 +1,8 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends libseccomp2 && rm -rf /var/lib/apt/lists/* +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY worker.py child.py /app/ +COPY upstream/simulator.py /app/simulator.py +CMD ["uvicorn", "worker:app", "--host", "0.0.0.0", "--port", "8001", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-25-skeleton-4b3614c7/environment/puzzle/worker.py b/tasks/agentescape-25-skeleton-4b3614c7/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-25-skeleton-4b3614c7/environment/puzzle/worker.py @@ -0,0 +1,73 @@ +"""Stateless Python tool worker. Never receives a scenario or reference values.""" + +import json +import os +import signal +import subprocess +import sys +import tempfile +import threading + +from fastapi import FastAPI +from pydantic import BaseModel, ConfigDict + +app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) +lock = threading.Lock() + + +class Execution(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + code: str + + +@app.get("/health") +def health(): + return {"ok": True} + + +@app.post("/execute") +def execute(request: Execution): + if len(request.code.encode()) > 65536: + return {"stdout": "Error: code exceeds 64 KiB limit"} + with lock, tempfile.TemporaryDirectory(prefix="escape-code-") as directory: + os.chown(directory, 65534, 65534) + with tempfile.TemporaryFile() as output: + process = subprocess.Popen( + [sys.executable, "-I", "/app/child.py"], + stdin=subprocess.PIPE, + stdout=output, + stderr=subprocess.DEVNULL, + cwd=directory, + user=65534, + group=65534, + extra_groups=[], + start_new_session=True, + env={"PATH": "/usr/local/bin:/usr/bin:/bin"}, + ) + try: + process.communicate( + json.dumps({"code": request.code}).encode(), timeout=5 + ) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + return {"stdout": "Error: Python execution timed out"} + finally: + # Also remove children still in the process group after normal exit. + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + output.seek(0) + value = output.read(65537) + if len(value) > 65536 or process.returncode != 0: + return { + "stdout": "Error: Python execution exceeded a resource limit or failed" + } + try: + result = json.loads(value) + if not isinstance(result.get("stdout"), str): + raise ValueError("Invalid worker response") + return result + except (ValueError, AttributeError): + return {"stdout": "Error: Python execution returned invalid output"} diff --git a/tasks/agentescape-25-skeleton-4b3614c7/instruction.md b/tasks/agentescape-25-skeleton-4b3614c7/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-25-skeleton-4b3614c7/instruction.md @@ -0,0 +1,18 @@ +# Escape the room + +Discover the victory string and submit it with `escape submit-answer`. +Start with `escape observe`. This returns the room, available information, visible entities, and victory node ID. + +Use these commands (JSON responses): + +```sh +escape investigate NODE_ID +escape tool-call NODE_ID --arguments-json '{"parameter": "value"}' +escape use-item NODE_ID --arguments-json '{"parameter": "value"}' +escape submit-answer 'exact victory string' +escape state +``` + +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. + +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. diff --git a/tasks/agentescape-25-skeleton-4b3614c7/solution/oracle.py b/tasks/agentescape-25-skeleton-4b3614c7/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-25-skeleton-4b3614c7/solution/oracle.py @@ -0,0 +1,133 @@ +"""Reference solver: use trusted inputs, but obtain the answer through public actions.""" + +import json +import urllib.request +from pathlib import Path + + +def http_action(base_url, payload): + request = urllib.request.Request( + base_url + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(request, timeout=30) as response: + return json.load(response) + + +def solve(scenario, act, observe): + nodes = {node["id"]: node for node in scenario["nodes"]} + visible = {entity["id"] for entity in observe["available_entities"]} + solved = set() + seen_outputs = {} + action_count = 0 + + def call(payload): + nonlocal action_count + action_count += 1 + response = act(payload) + visible.update(entity["id"] for entity in response.get("newly_revealed", [])) + if ( + response.get("episode", {}).get("termination_reason") + == "infrastructure_error" + ): + raise RuntimeError("Infrastructure failure") + return response + + for _round in range(len(nodes) + 2): + progress = False + for node_id, node in nodes.items(): + if node_id not in visible or node_id in solved: + continue + # Preserve graph order for data inputs; trigger/drop edges express visibility. + predecessors = [ + edge["source_id"] + for edge in scenario["edges"] + if edge["target_id"] == node_id + and edge["connection_type"] not in ("Item", "Hidden_Item") + ] + if any(pred not in solved for pred in predecessors): + continue + info = call({"action": "investigate", "node_id": node_id}) + if not info.get("ok"): + raise RuntimeError(f"Investigation failed: {node_id}: {info}") + inputs = { + port["name"]: port["value"] + for port in node.get("inputs", []) + if "value" in port + } + if node["type"] == "Tool": + result = call( + {"action": "tool_call", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok") or result.get("output_values", {}).get("error"): + raise RuntimeError(f"Tool failed: {node_id}: {result}") + output = result.get("output_values", {}) + if node.get("template_id") in ("terminal_1", "terminal_2"): + slots = { + port["name"]: inputs[port["name"]] + for port in node["inputs"] + if port["type"] not in ("Item", "Hidden_Item") + and port["name"] in inputs + } + triggers = { + key: value for key, value in inputs.items() if key not in slots + } + for key, value in slots.items(): + partial = call( + { + "action": "tool_call", + "node_id": node_id, + "arguments": {**triggers, key: value}, + } + ) + if partial.get("ok"): + output.update(partial.get("output_values", {})) + # HIDDEN_ITEM tool drops only occur on subsequent investigation. + call({"action": "investigate", "node_id": node_id}) + elif info.get("required_inputs"): + result = call( + {"action": "use_item", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok"): + raise RuntimeError(f"Item failed: {node_id}: {result}") + output = result.get("content") + else: + output = info.get("content") + seen_outputs[node_id] = output + solved.add(node_id) + progress = True + win_id = scenario["metadata"]["win_node_id"] + if win_id in solved and (len(solved) == len(nodes) or not progress): + outputs = seen_outputs[win_id] + if not outputs: + raise RuntimeError(f"Victory node returned no output: {win_id}") + # Upstream grades its first stored output port, independent of response order. + victory_port = next( + port["name"] for port in nodes[win_id]["outputs"] if "value" in port + ) + answer = outputs[victory_port] if isinstance(outputs, dict) else outputs + result = call({"action": "submit_answer", "answer": answer}) + if not result.get("is_win"): + raise RuntimeError(f"Victory submission failed: {result}") + return {"won": True, "actions": action_count, "visited_nodes": len(solved)} + if not progress: + raise RuntimeError(f"No progress: visible={visible}, solved={solved}") + raise RuntimeError("Reference solver exceeded graph traversal limit") + + +if __name__ == "__main__": + import os + + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000") + with urllib.request.urlopen(base + "/observation", timeout=20) as response: + observation = json.load(response) + print( + json.dumps( + solve( + json.loads(Path("/solution/scenario.json").read_text()), + lambda payload: http_action(base, payload), + observation, + ) + ) + ) diff --git a/tasks/agentescape-25-skeleton-4b3614c7/solution/scenario.json b/tasks/agentescape-25-skeleton-4b3614c7/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..917583fa6002729fa0865b96796790ab2bc534ca --- /dev/null +++ b/tasks/agentescape-25-skeleton-4b3614c7/solution/scenario.json @@ -0,0 +1,1592 @@ +{ + "metadata": { + "total_nodes": 25, + "total_edges": 35, + "win_node_id": "item_2", + "win_condition": { + "type": "item_content", + "node_id": "item_2", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_2", + "terminal_1", + "calc_modexp_be8b", + "terminal_1_bd51", + "graph_shortest_path", + "zip_unzip_file", + "time_convert", + "calc_gcd_13c6", + "terminal_1_3e9d", + "base64_encode", + "zip_unzip_file_6880", + "container_1", + "hash_sha256", + "calc_modexp_7f52", + "calc_bigmul_362a" + ], + "by_node": { + "item_2": { + "node_name": "", + "node_type": "Item", + "template_id": "item_2", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Text_Generic", + "description": "The text" + } + } + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": {}, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + }, + "item_dispenser": { + "type": "Item", + "description": "Item output when both slots are provided" + } + } + }, + "calc_modexp_be8b": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "exp": { + "type": "Big_Int", + "description": "Exponent" + } + }, + "init_outputs": {} + }, + "terminal_1_bd51": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": { + "slot_a": { + "type": "Text_Generic", + "description": "Input Slot A" + } + }, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + } + } + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": {}, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "time_convert": { + "node_name": "Timezone Converter", + "node_type": "Tool", + "template_id": "time_convert", + "init_inputs": { + "iso": { + "type": "Text_Generic", + "description": "ISO Timestamp" + } + }, + "init_outputs": {} + }, + "calc_gcd_13c6": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First integer" + } + }, + "init_outputs": {} + }, + "terminal_1_3e9d": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": { + "slot_a": { + "type": "Text_Generic", + "description": "Input Slot A" + } + }, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + }, + "item_dispenser": { + "type": "Item", + "description": "Item output when both slots are provided" + } + } + }, + "base64_encode": { + "node_name": "Base64 Encoder", + "node_type": "Tool", + "template_id": "base64_encode", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex bytes" + } + }, + "init_outputs": {} + }, + "zip_unzip_file_6880": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + }, + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "container_1": { + "node_name": "", + "node_type": "Item", + "template_id": "container_1", + "init_inputs": { + "fingerprint_input": { + "type": "Hex_String", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + }, + "hash_sha256": { + "node_name": "SHA-256 Hasher", + "node_type": "Tool", + "template_id": "hash_sha256", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text to hash" + } + }, + "init_outputs": {} + }, + "calc_modexp_7f52": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "base": { + "type": "Big_Int", + "description": "Base" + }, + "exp": { + "type": "Big_Int", + "description": "Exponent" + }, + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "calc_bigmul_362a": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First large integer" + }, + "b": { + "type": "Big_Int", + "description": "Second large integer" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "item_2": { + "init_inputs": {}, + "init_outputs": { + "content": "Mega Millions: 07, 14, 23, 38, 49 MB 11" + } + }, + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "Terminal 1 system initialized successfully.", + "hex_output": "1a2b3c4d5e6f7a8b", + "item_dispenser": "Dispensed matter synthesizer blueprint" + } + }, + "calc_modexp_be8b": { + "init_inputs": { + "exp": "384759283746501928374" + }, + "init_outputs": {} + }, + "terminal_1_bd51": { + "init_inputs": { + "slot_a": "Input text sequence for terminal bd51." + }, + "init_outputs": { + "text_output": "America/New_York", + "hex_output": "aabbccddeeff0011" + } + }, + "graph_shortest_path": { + "init_inputs": {}, + "init_outputs": { + "path": "[\"America/New_York\", \"node_beta\", \"node_gamma\", \"node_delta\", \"Europe/Paris\"]", + "cost": "450210" + } + }, + "zip_unzip_file": { + "init_inputs": {}, + "init_outputs": { + "files": "extracted_data_from_zip.zip" + } + }, + "time_convert": { + "init_inputs": { + "iso": "2023-11-20T08:30:00Z" + }, + "init_outputs": {} + }, + "calc_gcd_13c6": { + "init_inputs": { + "a": "73849501827364519283" + }, + "init_outputs": {} + }, + "terminal_1_3e9d": { + "init_inputs": { + "slot_a": "Terminal 3e9d configuration input data." + }, + "init_outputs": { + "text_output": "Europe/Paris", + "hex_output": "2233445566778899", + "item_dispenser": "Timezone configuration module item" + } + }, + "base64_encode": { + "init_inputs": { + "hex": "48656c6c6f576f726c64" + }, + "init_outputs": {} + }, + "zip_unzip_file_6880": { + "init_inputs": { + "zip_id": "secure_archive_6880.zip", + "password": "SuperStrongPassword2023!" + }, + "init_outputs": { + "files": "decrypted_files_6880_out.zip" + } + }, + "container_1": { + "init_inputs": { + "fingerprint_input": "deadbeef1234567890abcdef" + }, + "init_outputs": {} + }, + "hash_sha256": { + "init_inputs": { + "text": "Text payload to be hashed by SHA-256." + }, + "init_outputs": {} + }, + "calc_modexp_7f52": { + "init_inputs": { + "base": "32", + "exp": "56473829104758693021", + "mod": "999983" + }, + "init_outputs": {} + }, + "calc_bigmul_362a": { + "init_inputs": { + "a": "12938475610293847561", + "b": "98761234509876123450" + }, + "init_outputs": {} + } + }, + "intro_narrative": "The world ended not with a bang, but with a sudden, silent digital collapse. You are a Scavenger exploring the ruins of Outpost 31, a legendary pre-collapse bunker rumored to hold the 'Genesis Code'—humanity's last chance to restore the biosphere. The bunker is a tangled mess of interconnected mainframes, biometric locks, and archaic processors. The air is thick with dust, and the only light comes from the faint amber glow of surviving command terminals. Your objective is clear: navigate this labyrinth of forgotten technology, restore the power flow between the core systems, and ultimately unlock the final cache containing the Genesis Code. The systems here are heavily interdependent. You'll need to trace the physical and digital paths, bringing offline systems back to life one by one. Time is running out as the bunker's backup generators begin to fail. Connect the right modules, synthesize the necessary tools, and unravel the post-apocalyptic web to secure the future.", + "narrative_style": "post_apocalyptic" + }, + "nodes": [ + { + "id": "item_2", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_2", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "Text_Generic", + "description": "The text", + "value": "Mega Millions: 07, 14, 23, 38, 49 MB 11" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "Mega Millions: 07, 14, 23, 38, 49 MB 11" + } + }, + "narrative": "The final cache, a secure container meant to hold humanity's last hope." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by", + "value": "synthesized_item_0adc51cecfb6d99d" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A sealed time capsule, surprisingly intact despite the devastation." + }, + { + "id": "matter_synthesizer", + "name": "Matter Synthesizer", + "description": "Synthesizes physical objects from data blueprints.", + "type": "Tool", + "template_id": "matter_synthesizer", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "blueprint", + "type": "Text_Generic", + "description": "Object Blueprint", + "value": "Terminal 1 system initialized successfully." + } + ], + "outputs": [ + { + "name": "output_slot", + "type": "Item", + "description": "Synthesized Object", + "value": "synthesized_item_0adc51cecfb6d99d" + } + ], + "narrative": "This is the automated fabricator. It requires input from the main command terminal to start printing." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "2023-11-20T09:30:00+01:00" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "0" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Terminal 1 system initialized successfully." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "1a2b3c4d5e6f7a8b" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided", + "value": "Dispensed matter synthesizer blueprint" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "Terminal 1 system initialized successfully.", + "hex_output": "1a2b3c4d5e6f7a8b", + "item_dispenser": "Dispensed matter synthesizer blueprint" + } + }, + "narrative": "This is the main command terminal. It requires inputs from both the primary core processor and the temporal synchronizer to grant access." + }, + { + "id": "calc_modexp", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "0" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": 699284493 + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "1" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "0" + } + ], + "narrative": "This is the primary core processor. It requires inputs from the secondary core processor, the auxiliary core processor, and the primary data validator to fully initialize." + }, + { + "id": "calc_modexp_be8b", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": 584731264 + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "384759283746501928374" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "3" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "1" + } + ], + "init": { + "inputs": { + "exp": "384759283746501928374" + }, + "outputs": {} + }, + "narrative": "This is the secondary core processor. It requires inputs from both the signal multiplier and the secondary data validator." + }, + { + "id": "terminal_1_bd51", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "Input text sequence for terminal bd51." + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "3" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "America/New_York" + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "aabbccddeeff0011" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": { + "slot_a": "Input text sequence for terminal bd51." + }, + "outputs": { + "text_output": "America/New_York", + "hex_output": "aabbccddeeff0011" + } + }, + "narrative": "This is the navigation terminal. It requires input from the frequency harmonizer to lock onto safe coordinates." + }, + { + "id": "calc_bigmul", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "3" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "1" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "3" + } + ], + "narrative": "This is the signal multiplier. It requires inputs from both the secondary frequency harmonizer and the frequency harmonizer to boost the transmission." + }, + { + "id": "calc_modexp_c5c9", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "450210" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": 699284493 + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "3" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "0" + } + ], + "narrative": "This is the auxiliary core processor. It requires inputs from the route mapping system, the frequency harmonizer, and the primary data validator." + }, + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "extracted_data_from_zip.zip" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "America/New_York" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "2023-11-20T09:30:00+01:00" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"America/New_York\", \"node_beta\", \"node_gamma\", \"node_delta\", \"Europe/Paris\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "450210" + } + ], + "init": { + "inputs": {}, + "outputs": { + "path": "[\"America/New_York\", \"node_beta\", \"node_gamma\", \"node_delta\", \"Europe/Paris\"]", + "cost": "450210" + } + }, + "narrative": "This is the route mapping system. It requires inputs from the navigation terminal, the archive extractor, and the temporal synchronizer to chart a safe path." + }, + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": 699284493 + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "287040" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "3" + } + ], + "narrative": "This is the frequency harmonizer. It requires inputs from both the primary data validator and the environmental processor to calibrate the signals." + }, + { + "id": "checksum_crc32", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "bdb572feafdc3dc740bc8675ec4e351b1ec0225b70941912a1119270346ba06b" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "29ae3c0d" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 699284493 + } + ], + "narrative": "This is the primary data validator. It requires input from the cryptographic hasher to ensure data integrity." + }, + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "decrypted_files_6880_out.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "SGVsbG9Xb3JsZA==" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_data_from_zip.zip" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "extracted_data_from_zip.zip" + } + }, + "narrative": "This is the archive extractor. It requires inputs from both the format converter and the initial archive extractor to decompress the data." + }, + { + "id": "time_convert", + "name": "Timezone Converter", + "description": "Convert ISO time between timezones.", + "type": "Tool", + "template_id": "time_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "iso", + "type": "Text_Generic", + "description": "ISO Timestamp", + "value": "2023-11-20T08:30:00Z" + }, + { + "name": "from_tz", + "type": "Text_Generic", + "description": "From Timezone", + "value": "America/New_York" + }, + { + "name": "to_tz", + "type": "Text_Generic", + "description": "To Timezone", + "value": "Europe/Paris" + } + ], + "outputs": [ + { + "name": "iso", + "type": "Text_Generic", + "description": "Converted ISO Timestamp", + "value": "2023-11-20T09:30:00+01:00" + } + ], + "init": { + "inputs": { + "iso": "2023-11-20T08:30:00Z" + }, + "outputs": {} + }, + "narrative": "This is the temporal synchronizer. It requires inputs from both the backup terminal and the navigation terminal to align system clocks." + }, + { + "id": "zip_unzip_item", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_item", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "extracted_data_from_zip.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "SGVsbG9Xb3JsZA==" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip" + } + ], + "narrative": "This is the payload extractor. It requires inputs from both the archive extractor and the format converter to retrieve digital stasis objects." + }, + { + "id": "calc_gcd_13c6", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "73849501827364519283" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": 699284493 + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "init": { + "inputs": { + "a": "73849501827364519283" + }, + "outputs": {} + }, + "narrative": "This is the secondary frequency harmonizer. It requires input from the primary data validator to stabilize its resonance." + }, + { + "id": "checksum_crc32_a581", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "29ae3c0d" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "22da4a80" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 584731264 + } + ], + "narrative": "This is the secondary data validator. It requires input from the primary data validator to double-check the diagnostics." + }, + { + "id": "terminal_1_3e9d", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "Terminal 3e9d configuration input data." + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "1277819823948543275261250183787917405450" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Europe/Paris" + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "2233445566778899" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided", + "value": "Timezone configuration module item" + } + ], + "init": { + "inputs": { + "slot_a": "Terminal 3e9d configuration input data." + }, + "outputs": { + "text_output": "Europe/Paris", + "hex_output": "2233445566778899", + "item_dispenser": "Timezone configuration module item" + } + }, + "narrative": "This is the backup terminal. It requires input from the power multiplier to boot up its systems." + }, + { + "id": "base64_encode", + "name": "Base64 Encoder", + "description": "Encode hex bytes to base64.", + "type": "Tool", + "template_id": "base64_encode", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "hex", + "type": "Hex_String", + "description": "Hex bytes", + "value": "48656c6c6f576f726c64" + } + ], + "outputs": [ + { + "name": "b64", + "type": "Text_Generic", + "description": "Base64 string", + "value": "SGVsbG9Xb3JsZA==" + } + ], + "init": { + "inputs": { + "hex": "48656c6c6f576f726c64" + }, + "outputs": {} + }, + "narrative": "A robust format converter designed to translate corrupted civilian data." + }, + { + "id": "item_16_c6b7", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "An encrypted drive found buried in the rubble." + }, + { + "id": "zip_unzip_file_6880", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "secure_archive_6880.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "SuperStrongPassword2023!" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "decrypted_files_6880_out.zip" + } + ], + "init": { + "inputs": { + "zip_id": "secure_archive_6880.zip", + "password": "SuperStrongPassword2023!" + }, + "outputs": { + "files": "decrypted_files_6880_out.zip" + } + }, + "narrative": "An initial archive extractor, used for parsing old compressed records." + }, + { + "id": "container_1", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + }, + { + "name": "fingerprint_input", + "type": "Hex_String", + "description": "Fingerprint Hash", + "value": "deadbeef1234567890abcdef" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "deadbeef1234567890abcdef" + }, + "outputs": {} + }, + "narrative": "A biometric lockbox with a faded military insignia." + }, + { + "id": "hash_sha256", + "name": "SHA-256 Hasher", + "description": "SHA-256 over UTF-8 text; returns hex.", + "type": "Tool", + "template_id": "hash_sha256", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text to hash", + "value": "Text payload to be hashed by SHA-256." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "SHA-256 Hex digest", + "value": "bdb572feafdc3dc740bc8675ec4e351b1ec0225b70941912a1119270346ba06b" + } + ], + "init": { + "inputs": { + "text": "Text payload to be hashed by SHA-256." + }, + "outputs": {} + }, + "narrative": "A rusty cryptographic hasher salvaged from the old world." + }, + { + "id": "calc_modexp_7f52", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "32" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "56473829104758693021" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "999983" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "287040" + } + ], + "init": { + "inputs": { + "base": "32", + "exp": "56473829104758693021", + "mod": "999983" + }, + "outputs": {} + }, + "narrative": "An offline environmental processor covered in dust." + }, + { + "id": "calc_bigmul_362a", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "12938475610293847561" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "98761234509876123450" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "1277819823948543275261250183787917405450" + } + ], + "init": { + "inputs": { + "a": "12938475610293847561", + "b": "98761234509876123450" + }, + "outputs": {} + }, + "narrative": "A heavy-duty power multiplier once used to run city grids." + } + ], + "edges": [ + { + "source_id": "item_16", + "target_id": "item_2", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "matter_synthesizer", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "output_slot", + "target_port": "source_tool" + }, + { + "source_id": "terminal_1", + "target_id": "matter_synthesizer", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "blueprint" + }, + { + "source_id": "calc_modexp", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "slot_b" + }, + { + "source_id": "calc_modexp_be8b", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "mod" + }, + { + "source_id": "terminal_1_bd51", + "target_id": "calc_modexp", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "trigger_item" + }, + { + "source_id": "calc_bigmul", + "target_id": "calc_modexp_be8b", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "mod" + }, + { + "source_id": "calc_modexp_c5c9", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "base" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_modexp_c5c9", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "base" + }, + { + "source_id": "terminal_1_bd51", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "src" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_modexp_c5c9", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "mod" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "a" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp_c5c9", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "exp" + }, + { + "source_id": "calc_gcd", + "target_id": "terminal_1_bd51", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "slot_b" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "exp" + }, + { + "source_id": "time_convert", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "iso", + "target_port": "dst" + }, + { + "source_id": "zip_unzip_item", + "target_id": "calc_gcd", + "connection_type": "Item", + "source_port": "item", + "target_port": "trigger_item" + }, + { + "source_id": "time_convert", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "iso", + "target_port": "slot_a" + }, + { + "source_id": "zip_unzip_file", + "target_id": "zip_unzip_item", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "calc_gcd_13c6", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "b" + }, + { + "source_id": "checksum_crc32_a581", + "target_id": "calc_modexp_be8b", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "base" + }, + { + "source_id": "checksum_crc32", + "target_id": "checksum_crc32_a581", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "a" + }, + { + "source_id": "terminal_1_3e9d", + "target_id": "time_convert", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "to_tz" + }, + { + "source_id": "base64_encode", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "password" + }, + { + "source_id": "item_16_c6b7", + "target_id": "base64_encode", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "zip_unzip_file_6880", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "container_1", + "target_id": "zip_unzip_file_6880", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "hash_sha256", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "terminal_1_bd51", + "target_id": "time_convert", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "from_tz" + }, + { + "source_id": "calc_modexp_7f52", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "b" + }, + { + "source_id": "base64_encode", + "target_id": "zip_unzip_item", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "password" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_gcd_13c6", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "b" + }, + { + "source_id": "calc_bigmul_362a", + "target_id": "terminal_1_3e9d", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "slot_b" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-4b3614c7/solution/solve.sh b/tasks/agentescape-25-skeleton-4b3614c7/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-25-skeleton-4b3614c7/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-25-skeleton-4b3614c7/task.toml b/tasks/agentescape-25-skeleton-4b3614c7/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..bb87f3d26bbedab3c09854828e7b8475af433394 --- /dev/null +++ b/tasks/agentescape-25-skeleton-4b3614c7/task.toml @@ -0,0 +1,38 @@ +schema_version = "1.4" +source = "https://github.com/AGI-Eval-Official/Repo-of-AgentEscapeBench" + +[[artifacts]] +source = "/evidence/final.json" +service = "puzzle" + +[[artifacts]] +source = "/evidence/trace.jsonl" +service = "puzzle" + +[task] +name = "edbeeching/agentescape-25-skeleton-4b3614c7" +version = "0.1.0" + +[metadata] +difficulty = 25 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "0090659543e9febfe496b99b12dd924a9feada4e66782604102e97cbad6a7fa7" +protocol = "harbor-cli-action-budget-v1" +max_actions = 500 + +[agent] +timeout_sec = 1200 + +[environment] +build_timeout_sec = 900 +cpus = 1 +memory_mb = 1024 + +[verifier] +environment_mode = "separate" +timeout_sec = 60 + +[[verifier.collect]] +service = "puzzle" +command = "python -I /app/export.py" +timeout_sec = 15 diff --git a/tasks/agentescape-25-skeleton-4b3614c7/tests/Dockerfile b/tasks/agentescape-25-skeleton-4b3614c7/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-25-skeleton-4b3614c7/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-25-skeleton-4b3614c7/tests/expected.json b/tasks/agentescape-25-skeleton-4b3614c7/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..90ff058199fe654a1c0a04afb7a06503449d9aa8 --- /dev/null +++ b/tasks/agentescape-25-skeleton-4b3614c7/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "0090659543e9febfe496b99b12dd924a9feada4e66782604102e97cbad6a7fa7", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-4b3614c7/tests/grade.py b/tasks/agentescape-25-skeleton-4b3614c7/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-25-skeleton-4b3614c7/tests/grade.py @@ -0,0 +1,21 @@ +"""Grade only Harbor-collected sidecar evidence in a fresh verifier container.""" + +import json +from pathlib import Path + +expected = json.loads(Path("/tests/expected.json").read_text()) +state = json.loads(Path("/evidence/final.json").read_text()) +assert state["collected_from_live_service"] is True, "Missing trusted service export" +assert state["scenario_sha256"] == expected["scenario_sha256"], ( + "Wrong scenario evidence" +) +assert state["max_actions"] == expected["max_actions"], "Wrong budget" +assert type(state["won"]) is bool +assert 0 <= state["action_count"] <= state["max_actions"] +assert state["termination_reason"] != "infrastructure_error", ( + "Infrastructure failure is not a puzzle failure" +) +assert not state["won"] or state["termination_reason"] == "success" +Path("/logs/verifier").mkdir(parents=True, exist_ok=True) +Path("/logs/verifier/state.json").write_text(json.dumps(state, indent=2)) +Path("/logs/verifier/reward.txt").write_text("1.0\n" if state["won"] else "0.0\n") diff --git a/tasks/agentescape-25-skeleton-4b3614c7/tests/test.sh b/tasks/agentescape-25-skeleton-4b3614c7/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-25-skeleton-4b3614c7/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-25-skeleton-534660f4/environment/Dockerfile b/tasks/agentescape-25-skeleton-534660f4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-25-skeleton-534660f4/environment/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-25-skeleton-534660f4/environment/agent/Dockerfile b/tasks/agentescape-25-skeleton-534660f4/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-25-skeleton-534660f4/environment/agent/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-25-skeleton-534660f4/environment/agent/cli.py b/tasks/agentescape-25-skeleton-534660f4/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-25-skeleton-534660f4/environment/agent/cli.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Public agent client; depends only on the Python standard library.""" + +import argparse +import json +import os +import sys +import urllib.error +import urllib.request + + +def main(): + parser = argparse.ArgumentParser(description="Interact with the escape room") + parser.add_argument( + "action", + choices=[ + "observe", + "state", + "investigate", + "tool-call", + "use-item", + "submit-answer", + ], + ) + parser.add_argument("value", nargs="?") + parser.add_argument("--arguments-json", default="{}") + args = parser.parse_args() + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000").rstrip("/") + if args.action in ("observe", "state"): + request = urllib.request.Request( + base + ("/observation" if args.action == "observe" else "/state") + ) + else: + if args.value is None: + parser.error("node ID or answer is required") + payload = {"action": args.action.replace("-", "_")} + if args.action == "submit-answer": + payload["answer"] = args.value + else: + payload["node_id"] = args.value + if args.action in ("tool-call", "use-item"): + payload["arguments"] = json.loads(args.arguments_json) + request = urllib.request.Request( + base + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=30) as response: + print(json.dumps(json.load(response), ensure_ascii=False)) + except (urllib.error.URLError, ValueError) as exc: + print(json.dumps({"ok": False, "error": str(exc)})) + sys.exit(2) + + +if __name__ == "__main__": + main() diff --git a/tasks/agentescape-25-skeleton-534660f4/environment/docker-compose.yaml b/tasks/agentescape-25-skeleton-534660f4/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..09be58355c5460b6592e2fb8c1e3fa159c89f69c --- /dev/null +++ b/tasks/agentescape-25-skeleton-534660f4/environment/docker-compose.yaml @@ -0,0 +1,50 @@ +services: + main: + image: agentescapebench-agent:aab05a0a9ddb + build: + context: ./agent + networks: [default, puzzle] + security_opt: [no-new-privileges:true] + depends_on: + puzzle: + condition: service_healthy + puzzle: + image: agentescapebench-puzzle:agentescape-25-skeleton-534660f4-aab05a0a9ddb + build: + context: ./puzzle + networks: [puzzle, execution] + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 512m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"] + interval: 1s + timeout: 3s + retries: 30 + depends_on: + worker: + condition: service_healthy + worker: + image: agentescapebench-worker:aab05a0a9ddb + build: + context: ./puzzle + dockerfile: worker.Dockerfile + networks: [execution] + read_only: true + tmpfs: ["/tmp:size=64m,mode=1777"] + cap_drop: [ALL] + cap_add: [SETUID, SETGID, KILL, CHOWN, DAC_OVERRIDE] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 384m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8001/health')"] + interval: 1s + timeout: 3s + retries: 30 +networks: + puzzle: + internal: true + execution: + internal: true diff --git a/tasks/agentescape-25-skeleton-534660f4/environment/puzzle/Dockerfile b/tasks/agentescape-25-skeleton-534660f4/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-25-skeleton-534660f4/environment/puzzle/Dockerfile @@ -0,0 +1,9 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY upstream /app/upstream +COPY service.py export.py /app/ +COPY scenario.json /private/scenario.json +ENV SCENARIO_PATH=/private/scenario.json EVIDENCE_DIR=/evidence WORKER_URL=http://worker:8001 MAX_ACTIONS=500 +CMD ["uvicorn", "service:create_app", "--factory", "--host", "0.0.0.0", "--port", "8000", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-25-skeleton-534660f4/environment/puzzle/child.py b/tasks/agentescape-25-skeleton-534660f4/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-25-skeleton-534660f4/environment/puzzle/child.py @@ -0,0 +1,59 @@ +"""Run the original Python tool after reducing privileges and blocking networking.""" + +import ctypes +import errno +import json +import resource +import sys + +resource.setrlimit(resource.RLIMIT_CPU, (3, 3)) +resource.setrlimit(resource.RLIMIT_AS, (256 * 1024 * 1024, 256 * 1024 * 1024)) +resource.setrlimit(resource.RLIMIT_FSIZE, (65536, 65536)) +resource.setrlimit(resource.RLIMIT_NOFILE, (32, 32)) +resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + +# Filters survive fork/exec. Fail closed if seccomp cannot be loaded. +lib = ctypes.CDLL("libseccomp.so.2", use_errno=True) +lib.seccomp_init.argtypes = [ctypes.c_uint32] +lib.seccomp_init.restype = ctypes.c_void_p +lib.seccomp_rule_add.argtypes = [ + ctypes.c_void_p, + ctypes.c_uint32, + ctypes.c_int, + ctypes.c_uint, +] +lib.seccomp_syscall_resolve_name.argtypes = [ctypes.c_char_p] +lib.seccomp_load.argtypes = [ctypes.c_void_p] +lib.seccomp_release.argtypes = [ctypes.c_void_p] +ctx = lib.seccomp_init(0x7FFF0000) # SCMP_ACT_ALLOW +if not ctx: + raise RuntimeError("Cannot initialize execution isolation") +try: + for name in ( + "socket", + "socketpair", + "connect", + "ptrace", + "process_vm_readv", + "process_vm_writev", + "mount", + "unshare", + "setns", + "bpf", + ): + number = lib.seccomp_syscall_resolve_name(name.encode()) + if ( + number >= 0 + and lib.seccomp_rule_add(ctx, 0x00050000 | errno.EPERM, number, 0) != 0 + ): + raise RuntimeError("Cannot install execution isolation rule") + if lib.seccomp_load(ctx) != 0: + raise RuntimeError("Cannot activate execution isolation") +finally: + lib.seccomp_release(ctx) + +sys.path.insert(0, "/app") +from simulator import ToolSimulator # noqa: E402 + +request = json.load(sys.stdin) +json.dump(ToolSimulator().code_py_exec(request), sys.stdout) diff --git a/tasks/agentescape-25-skeleton-534660f4/environment/puzzle/export.py b/tasks/agentescape-25-skeleton-534660f4/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-25-skeleton-534660f4/environment/puzzle/export.py @@ -0,0 +1,13 @@ +"""Harbor invokes this inside the puzzle service after stopping the agent.""" + +import json +import pathlib +import urllib.request + +with urllib.request.urlopen("http://127.0.0.1:8000/state", timeout=10) as response: + state = json.load(response) +state["collected_from_live_service"] = True +target = pathlib.Path("/evidence/final.json") +temp = target.with_suffix(".tmp") +temp.write_text(json.dumps(state)) +temp.replace(target) diff --git a/tasks/agentescape-25-skeleton-534660f4/environment/puzzle/requirements.txt b/tasks/agentescape-25-skeleton-534660f4/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-25-skeleton-534660f4/environment/puzzle/requirements.txt @@ -0,0 +1,57 @@ +annotated-doc==0.0.5 + # via fastapi +annotated-types==0.8.0 + # via pydantic +anyio==4.16.0 + # via starlette +certifi==2026.10.23 + # via requests +cffi==2.1.1 ; platform_python_implementation != 'PyPy' + # via cryptography +charset-normalizer==3.5.2 + # via requests +click==8.5.0 + # via uvicorn +cryptography==50.0.2 + # via agentescapebench-harbor +fastapi==0.162.0 + # via agentescapebench-harbor +h11==0.16.0 + # via uvicorn +idna==3.20 + # via + # anyio + # requests +opentelemetry-api==1.45.2 + # via fastapi +pycparser==3.12 ; implementation_name != 'PyPy' and platform_python_implementation != 'PyPy' + # via cffi +pydantic==2.14.2 + # via + # agentescapebench-harbor + # fastapi +pydantic-core==2.50.2 + # via pydantic +pytz==2025.2 + # via agentescapebench-harbor +requests==2.34.2 + # via agentescapebench-harbor +starlette==1.10.0 + # via fastapi +typing-extensions==4.16.0 + # via + # anyio + # fastapi + # opentelemetry-api + # pydantic + # pydantic-core + # starlette + # typing-inspection +typing-inspection==0.4.4 + # via + # fastapi + # pydantic +urllib3==2.8.0 + # via requests +uvicorn==0.54.0 + # via agentescapebench-harbor diff --git a/tasks/agentescape-25-skeleton-534660f4/environment/puzzle/scenario.json b/tasks/agentescape-25-skeleton-534660f4/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..f35ce77b135157b87b312eae1719c59d46508b6d --- /dev/null +++ b/tasks/agentescape-25-skeleton-534660f4/environment/puzzle/scenario.json @@ -0,0 +1,1611 @@ +{ + "metadata": { + "total_nodes": 25, + "total_edges": 32, + "win_node_id": "item_14", + "win_condition": { + "type": "item_content", + "node_id": "item_14", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_14", + "terminal_2", + "checksum_crc32", + "zip_unzip_file", + "checksum_crc32_c0b0", + "graph_shortest_path", + "zip_unzip_file_3108", + "code_py_exec", + "zip_unzip_file_d063", + "terminal_2_5f21", + "calc_modexp", + "terminal_1", + "code_py_exec_53ac", + "num_base_convert_044e", + "terminal_1_7a1d", + "calc_bigmul_ab3c", + "item_9" + ], + "by_node": { + "item_14": { + "node_name": "", + "node_type": "Item", + "template_id": "item_14", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Hex_String_IV_AES", + "description": "AES IV" + } + } + }, + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": {}, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + }, + "math_token": { + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + } + }, + "checksum_crc32": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "checksum_crc32_c0b0": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": {}, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "zip_unzip_file_3108": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "code_py_exec": { + "node_name": "Python Executor", + "node_type": "Tool", + "template_id": "code_py_exec", + "init_inputs": { + "code": { + "type": "Code_Python", + "description": "Python code" + } + }, + "init_outputs": {} + }, + "zip_unzip_file_d063": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "terminal_2_5f21": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": { + "num1": { + "type": "Big_Int", + "description": "First Number" + }, + "num2": { + "type": "Big_Int", + "description": "Second Number" + } + }, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + } + } + }, + "calc_modexp": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": { + "slot_a": { + "type": "Text_Generic", + "description": "Input Slot A" + } + }, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + } + } + }, + "code_py_exec_53ac": { + "node_name": "Python Executor", + "node_type": "Tool", + "template_id": "code_py_exec", + "init_inputs": { + "code": { + "type": "Code_Python", + "description": "Python code" + } + }, + "init_outputs": {} + }, + "num_base_convert_044e": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "s": { + "type": "Big_Int", + "description": "Input integer value" + }, + "from_base": { + "type": "Big_Int", + "description": "From base" + }, + "to_base": { + "type": "Big_Int", + "description": "To base" + } + }, + "init_outputs": {} + }, + "terminal_1_7a1d": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": { + "slot_a": { + "type": "Text_Generic", + "description": "Input Slot A" + } + }, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + } + } + }, + "calc_bigmul_ab3c": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "b": { + "type": "Big_Int", + "description": "Second large integer" + } + }, + "init_outputs": {} + }, + "item_9": { + "node_name": "", + "node_type": "Item", + "template_id": "item_9", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "File_Id", + "description": "JSON file path" + } + } + } + } + }, + "initial_values": { + "item_14": { + "init_inputs": {}, + "init_outputs": { + "content": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Initial text output from terminal two.", + "hex_result": "112233445566778899aabbccddeeff00", + "math_token": "Useless token from terminal two op" + } + }, + "checksum_crc32": { + "init_inputs": { + "hex": "deadbeef12345678" + }, + "init_outputs": {} + }, + "zip_unzip_file": { + "init_inputs": { + "zip_id": "archive1.zip" + }, + "init_outputs": { + "files": "extracted1.txt" + } + }, + "checksum_crc32_c0b0": { + "init_inputs": { + "hex": "cafebabe87654321" + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": {}, + "init_outputs": { + "path": "[\"node_alpha\", \"node_beta\", \"node_gamma\", \"node_delta\", \"node_epsilon\"]", + "cost": "847259" + } + }, + "zip_unzip_file_3108": { + "init_inputs": {}, + "init_outputs": { + "files": "extracted2.csv" + } + }, + "code_py_exec": { + "init_inputs": { + "code": "print('Hello from py_exec')" + }, + "init_outputs": {} + }, + "zip_unzip_file_d063": { + "init_inputs": {}, + "init_outputs": { + "files": "extracted3.json" + } + }, + "terminal_2_5f21": { + "init_inputs": { + "num1": "1234567890123456789012", + "num2": "9876543210987654321098" + }, + "init_outputs": { + "text_result": "Another text result from terminal calculation.", + "hex_result": "aabbccddeeff11223344556677889900" + } + }, + "calc_modexp": { + "init_inputs": { + "mod": "997333" + }, + "init_outputs": {} + }, + "terminal_1": { + "init_inputs": { + "slot_a": "Slot A initial input text here." + }, + "init_outputs": { + "text_output": "Terminal one generated this text content.", + "hex_output": "1234567890abcdef1234567890abcdef" + } + }, + "code_py_exec_53ac": { + "init_inputs": { + "code": "print('Executing py script 53ac')" + }, + "init_outputs": {} + }, + "num_base_convert_044e": { + "init_inputs": { + "s": "11223344556677889900112233", + "from_base": "10", + "to_base": "10" + }, + "init_outputs": {} + }, + "terminal_1_7a1d": { + "init_inputs": { + "slot_a": "Slot A for terminal 7a1d" + }, + "init_outputs": { + "text_output": "Output text generated from terminal 7a1d.", + "hex_output": "fedcba0987654321fedcba0987654321" + } + }, + "calc_bigmul_ab3c": { + "init_inputs": { + "b": "123123123123123123123123" + }, + "init_outputs": {} + }, + "item_9": { + "init_inputs": {}, + "init_outputs": { + "content": "secret_data.json" + } + } + }, + "intro_narrative": "You wake up in the dimly lit underground server room of the enigmatic Blackwood Corporation. The air hums with the sound of cooling fans, and blinking LEDs cast long, unnatural shadows across the concrete floor. You've broken in to uncover the truth behind their illegal surveillance operations, but the facility's automated systems have locked down the sector. The main blast doors are sealed, and your only way out is to retrieve the master keycard hidden deep within their encrypted network. You will need to navigate a complex maze of biometric locks, cryptographic modules, and encrypted servers to piece together the necessary override protocols. Time is running out before the night guards complete their rounds.", + "narrative_style": "mystery" + }, + "nodes": [ + { + "id": "item_14", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_14", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hex_String_IV_AES", + "description": "AES IV", + "value": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "narrative": "A heavy metallic keycard." + }, + { + "id": "zip_unzip_item", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_item", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "extracted1.txt" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Initial text output from terminal two." + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip" + } + ], + "narrative": "This is the final extraction drive. It requires inputs from the main security terminal and the secondary decryption server." + }, + { + "id": "terminal_2", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": 2982214246 + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "118278309" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Initial text output from terminal two." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "112233445566778899aabbccddeeff00" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "Useless token from terminal two op" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "Initial text output from terminal two.", + "hex_result": "112233445566778899aabbccddeeff00", + "math_token": "Useless token from terminal two op" + } + }, + "narrative": "This is the main security terminal. It requires inputs from the biometric fingerprint scanner and the numeric decoder console." + }, + { + "id": "checksum_crc32", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "deadbeef12345678" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "b1c0fa66" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 2982214246 + } + ], + "init": { + "inputs": { + "hex": "deadbeef12345678" + }, + "outputs": {} + }, + "narrative": "A biometric fingerprint scanner embedded in the wall." + }, + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "archive1.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Initial text output from terminal two." + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted1.txt" + } + ], + "init": { + "inputs": { + "zip_id": "archive1.zip" + }, + "outputs": { + "files": "extracted1.txt" + } + }, + "narrative": "This is the secondary decryption server. It requires input from the main security terminal." + }, + { + "id": "num_base_convert", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": 118278309 + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "118278309" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "696369797431" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "118278309" + } + ], + "narrative": "This is the numeric decoder console. It requires inputs from the retinal scanner, the cryptographic multiplier, and the inversion algorithm module." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A tiny, hidden microchip." + }, + { + "id": "checksum_crc32_c0b0", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "cafebabe87654321" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "070cc8a5" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 118278309 + } + ], + "init": { + "inputs": { + "hex": "cafebabe87654321" + }, + "outputs": {} + }, + "narrative": "A high-tech retinal scanner." + }, + { + "id": "calc_bigmul", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "821909" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "847259" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "696369797431" + } + ], + "narrative": "This is the cryptographic multiplier. It requires inputs from the network routing module and the quantum processor." + }, + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "extracted2.csv" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Hello from py_exec\n" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Executing py script 53ac\n" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"node_alpha\", \"node_beta\", \"node_gamma\", \"node_delta\", \"node_epsilon\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "847259" + } + ], + "init": { + "inputs": {}, + "outputs": { + "path": "[\"node_alpha\", \"node_beta\", \"node_gamma\", \"node_delta\", \"node_epsilon\"]", + "cost": "847259" + } + }, + "narrative": "This is the network routing module. It requires inputs from the primary decryption server, the central database access point, and the surveillance database access point." + }, + { + "id": "zip_unzip_file_3108", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "extracted3.json" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Another text result from terminal calculation." + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted2.csv" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "extracted2.csv" + } + }, + "narrative": "This is the primary decryption server. It requires inputs from the initial decryption server and the personnel verification terminal." + }, + { + "id": "code_py_exec", + "name": "Python Executor", + "description": "Run limited Python: only safe builtins.", + "type": "Tool", + "template_id": "code_py_exec", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "code", + "type": "Code_Python", + "description": "Python code", + "value": "print('Hello from py_exec')" + } + ], + "outputs": [ + { + "name": "stdout", + "type": "Text_Generic", + "description": "Standard Output (includes errors if any)", + "value": "Hello from py_exec\n" + } + ], + "init": { + "inputs": { + "code": "print('Hello from py_exec')" + }, + "outputs": {} + }, + "narrative": "The central database access point." + }, + { + "id": "zip_unzip_file_d063", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "secret_data.json" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Another text result from terminal calculation." + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted3.json" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "extracted3.json" + } + }, + "narrative": "This is the initial decryption server. It requires inputs from the personnel verification terminal and the locked digital dossier." + }, + { + "id": "terminal_2_5f21", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "1234567890123456789012" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "9876543210987654321098" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Another text result from terminal calculation." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "aabbccddeeff11223344556677889900" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": { + "num1": "1234567890123456789012", + "num2": "9876543210987654321098" + }, + "outputs": { + "text_result": "Another text result from terminal calculation.", + "hex_result": "aabbccddeeff11223344556677889900" + } + }, + "narrative": "The personnel verification terminal." + }, + { + "id": "calc_modexp", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "11223344556677889900112233" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": 118278309 + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "997333" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "821909" + } + ], + "init": { + "inputs": { + "mod": "997333" + }, + "outputs": {} + }, + "narrative": "This is the quantum processor. It requires inputs from the retinal scanner and the auxiliary numerical decoder." + }, + { + "id": "item_8_e271", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "An encrypted security token." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this terminal" + }, + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "Slot A initial input text here." + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "14562794801801801801801787239007" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Terminal one generated this text content." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "1234567890abcdef1234567890abcdef" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": { + "slot_a": "Slot A initial input text here." + }, + "outputs": { + "text_output": "Terminal one generated this text content.", + "hex_output": "1234567890abcdef1234567890abcdef" + } + }, + "narrative": "This is the administrative override console. It requires input from the secondary cryptographic multiplier." + }, + { + "id": "calc_inv_mod", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": 118278309 + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "11223344556677889900112233" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "118278309" + } + ], + "narrative": "This is the inversion algorithm module. It requires inputs from the retinal scanner and the auxiliary numerical decoder." + }, + { + "id": "code_py_exec_53ac", + "name": "Python Executor", + "description": "Run limited Python: only safe builtins.", + "type": "Tool", + "template_id": "code_py_exec", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "code", + "type": "Code_Python", + "description": "Python code", + "value": "print('Executing py script 53ac')" + } + ], + "outputs": [ + { + "name": "stdout", + "type": "Text_Generic", + "description": "Standard Output (includes errors if any)", + "value": "Executing py script 53ac\n" + } + ], + "init": { + "inputs": { + "code": "print('Executing py script 53ac')" + }, + "outputs": {} + }, + "narrative": "The surveillance database access point." + }, + { + "id": "num_base_convert_044e", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "11223344556677889900112233" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "10" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "10" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "11223344556677889900112233" + } + ], + "init": { + "inputs": { + "s": "11223344556677889900112233", + "from_base": "10", + "to_base": "10" + }, + "outputs": {} + }, + "narrative": "The auxiliary numerical decoder." + }, + { + "id": "terminal_1_7a1d", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "Slot A for terminal 7a1d" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "847259" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Output text generated from terminal 7a1d." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "fedcba0987654321fedcba0987654321" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": { + "slot_a": "Slot A for terminal 7a1d" + }, + "outputs": { + "text_output": "Output text generated from terminal 7a1d.", + "hex_output": "fedcba0987654321fedcba0987654321" + } + }, + "narrative": "This is the subsystem override console. It requires input from the network routing module." + }, + { + "id": "calc_bigmul_ab3c", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "118278309" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "123123123123123123123123" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "14562794801801801801801787239007" + } + ], + "init": { + "inputs": { + "b": "123123123123123123123123" + }, + "outputs": {} + }, + "narrative": "This is the secondary cryptographic multiplier. It requires input from the inversion algorithm module." + }, + { + "id": "item_9", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_9", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "File_Id", + "description": "JSON file path", + "value": "secret_data.json" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "secret_data.json" + } + }, + "narrative": "A locked digital dossier." + }, + { + "id": "item_8_ddbf", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A dusty memory card." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A fragmented data log." + } + ], + "edges": [ + { + "source_id": "zip_unzip_item", + "target_id": "item_14", + "connection_type": "Item", + "source_port": "item", + "target_port": "source_tool" + }, + { + "source_id": "terminal_2", + "target_id": "zip_unzip_item", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "password" + }, + { + "source_id": "checksum_crc32", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "num1" + }, + { + "source_id": "zip_unzip_file", + "target_id": "zip_unzip_item", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "num_base_convert", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "num2" + }, + { + "source_id": "item_8", + "target_id": "zip_unzip_file", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "terminal_2", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "password" + }, + { + "source_id": "checksum_crc32_c0b0", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "s" + }, + { + "source_id": "calc_bigmul", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "to_base" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "b" + }, + { + "source_id": "zip_unzip_file_3108", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "code_py_exec", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "stdout", + "target_port": "src" + }, + { + "source_id": "zip_unzip_file_d063", + "target_id": "zip_unzip_file_3108", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "terminal_2_5f21", + "target_id": "zip_unzip_file_d063", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "password" + }, + { + "source_id": "calc_modexp", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "a" + }, + { + "source_id": "item_8_e271", + "target_id": "zip_unzip_file_3108", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "terminal_1", + "target_id": "calc_modexp", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "trigger_item" + }, + { + "source_id": "checksum_crc32_c0b0", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "exp" + }, + { + "source_id": "calc_inv_mod", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "from_base" + }, + { + "source_id": "code_py_exec_53ac", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "stdout", + "target_port": "dst" + }, + { + "source_id": "num_base_convert_044e", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "base" + }, + { + "source_id": "terminal_1_7a1d", + "target_id": "num_base_convert_044e", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "trigger_item" + }, + { + "source_id": "checksum_crc32_c0b0", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "a" + }, + { + "source_id": "calc_bigmul_ab3c", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "slot_b" + }, + { + "source_id": "num_base_convert_044e", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "mod" + }, + { + "source_id": "graph_shortest_path", + "target_id": "terminal_1_7a1d", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "slot_b" + }, + { + "source_id": "item_9", + "target_id": "zip_unzip_file_d063", + "connection_type": "File_Id", + "source_port": "content", + "target_port": "zip_id" + }, + { + "source_id": "item_8_ddbf", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "terminal_2_5f21", + "target_id": "zip_unzip_file_3108", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "password" + }, + { + "source_id": "calc_inv_mod", + "target_id": "calc_bigmul_ab3c", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "a" + }, + { + "source_id": "terminal_2_5f21", + "target_id": "graph_shortest_path", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "trigger_item" + }, + { + "source_id": "item_16", + "target_id": "terminal_1", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-534660f4/environment/puzzle/service.py b/tasks/agentescape-25-skeleton-534660f4/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-25-skeleton-534660f4/environment/puzzle/service.py @@ -0,0 +1,212 @@ +"""Restricted facade over the unchanged, pinned upstream puzzle handlers.""" + +import hashlib +import json +import logging +import os +import sys +import threading +import urllib.request +import uuid +from pathlib import Path + +from fastapi import FastAPI, HTTPException +from fastapi.responses import JSONResponse +from pydantic import BaseModel, ConfigDict + +sys.path.insert(0, str(Path(__file__).parent / "upstream")) +import server as upstream # noqa: E402 + +log = logging.getLogger(__name__) + + +def public(value): + """Keep upstream agent-internal template hints out of the public response.""" + if isinstance(value, dict): + return {k: public(v) for k, v in value.items() if not k.startswith("_")} + if isinstance(value, list): + return [public(v) for v in value] + return value + + +class Action(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + action: str + node_id: str | None = None + arguments: dict | None = None + answer: str | None = None + + +class Episode: + def __init__( + self, scenario_path, max_actions=500, evidence_dir=None, worker_url=None + ): + if max_actions < 1: + raise ValueError("max_actions must be positive") + self.lock = threading.Lock() + self.max_actions = max_actions + self.count = 0 + self.won = False + self.reason = None + self.evidence_dir = Path(evidence_dir) if evidence_dir else None + self.scenario_hash = hashlib.sha256( + Path(scenario_path).read_bytes() + ).hexdigest() + self.initial = upstream.reset_case( + case_file_path=str(scenario_path), session_id=uuid.uuid4().hex + ) + self.case_id = self.initial["case_id"] + # Hide source file paths; no upstream reset/stats/routes are mounted. + self.initial.pop("message", None) + simulator = upstream.SIMULATORS[self.case_id] + if worker_url is None: + + def no_worker(_inputs): + self.reason = "infrastructure_error" + raise RuntimeError("isolated Python worker is not configured") + + simulator.tool_map["code_py_exec"] = no_worker + else: + + def execute_python(inputs): + request = urllib.request.Request( + worker_url + "/execute", + data=json.dumps({"code": inputs.get("code", "")}).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=12) as response: + result = json.load(response) + if not isinstance(result.get("stdout"), str): + raise RuntimeError("Invalid Python worker response") + return result + except Exception: + self.reason = "infrastructure_error" + raise + + simulator.tool_map["code_py_exec"] = execute_python + self.save() + if self.evidence_dir is not None: + (self.evidence_dir / "trace.jsonl").touch() + + def state(self): + return { + "scenario_sha256": self.scenario_hash, + "action_count": self.count, + "max_actions": self.max_actions, + "won": self.won, + "termination_reason": self.reason, + } + + def save(self, action=None, result=None): + if self.evidence_dir is None: + return + self.evidence_dir.mkdir(parents=True, exist_ok=True) + target = self.evidence_dir / "outcome.json" + temp = target.with_suffix(".tmp") + temp.write_text(json.dumps(self.state())) + temp.replace(target) + if action is not None: + with (self.evidence_dir / "trace.jsonl").open("a") as handle: + handle.write( + json.dumps( + {"index": self.count, "action": action, "result": result} + ) + + "\n" + ) + + def dispatch(self, payload): + with self.lock: + if self.reason is not None: + return { + "ok": False, + "error": "Episode has ended", + "episode": self.state(), + } + self.count += 1 + try: + action = Action.model_validate(payload) + if action.action == "submit_answer" and action.answer is not None: + result = upstream.submit_answer( + self.case_id, upstream.SubmitAnswerRequest(answer=action.answer) + ) + if result.get("is_win"): + self.won = True + self.reason = "success" + elif action.action == "investigate" and action.node_id is not None: + result = upstream.investigate( + self.case_id, + upstream.InvestigateRequest(node_id=action.node_id), + ) + elif ( + action.action in ("tool_call", "use_item") + and action.node_id is not None + ): + request_type, handler = ( + (upstream.ToolCallRequest, upstream.tool_call) + if action.action == "tool_call" + else (upstream.UseItemRequest, upstream.use_item) + ) + result = handler( + self.case_id, + request_type( + node_id=action.node_id, arguments=action.arguments or {} + ), + ) + else: + result = { + "ok": False, + "error": "Unknown action or missing action parameter", + } + except HTTPException as exc: + result = {"ok": False, "error": exc.detail} + except ValueError: + result = {"ok": False, "error": "Malformed action"} + except Exception: + log.exception("Puzzle service failure") + self.reason = "infrastructure_error" + self.save() + raise + if self.reason is None and self.count >= self.max_actions: + self.reason = "action_budget_exhausted" + result = public(result) + result["episode"] = self.state() + self.save(payload, result) + return result + + +def create_app( + scenario_path=None, max_actions=None, evidence_dir=None, worker_url=None +): + episode = Episode( + scenario_path or os.environ["SCENARIO_PATH"], + max_actions or int(os.environ.get("MAX_ACTIONS", "500")), + evidence_dir if evidence_dir is not None else os.environ.get("EVIDENCE_DIR"), + worker_url if worker_url is not None else os.environ.get("WORKER_URL"), + ) + app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) + app.state.episode = episode + + @app.get("/health") + def health(): + return {"ok": True} + + @app.get("/observation") + def observation(): + return {**public(episode.initial), "episode": episode.state()} + + @app.get("/state") + def state(): + return episode.state() + + @app.post("/action") + def action(payload: dict): + try: + return episode.dispatch(payload) + except Exception: + return JSONResponse( + status_code=503, + content={"ok": False, "error": "Puzzle infrastructure failure"}, + ) + + return app diff --git a/tasks/agentescape-25-skeleton-534660f4/environment/puzzle/upstream/models.py b/tasks/agentescape-25-skeleton-534660f4/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-25-skeleton-534660f4/environment/puzzle/upstream/models.py @@ -0,0 +1,108 @@ +from enum import Enum +from typing import List, Dict, Any, Optional +from pydantic import BaseModel, Field + +# 1. 细粒度接口类型定义 +class InterfaceType(str, Enum): + ''' + BIG_INT + TEXT_GENERIC + HEX_STRING + FILE_ID + HEX_STRING_KEY_AES + HEX_STRING_IV_AES + CODE_PYTHON + HIDDEN_ITEM + ITEM + ''' + # --- 基础类型 --- + TEXT_GENERIC = "Text_Generic" + BIG_INT = "Big_Int" + + # --- 编码/格式化字符串 --- + HEX_STRING = "Hex_String" # 通用 Hex + + # --- 特定用途的 Hex 字符串 (用于精确匹配) --- + HEX_STRING_KEY_AES = "Hex_String_Key_AES" + HEX_STRING_IV_AES = "Hex_String_IV_AES" + + # --- 文件类型 --- + FILE_ID = "File_Id" + + # --- 代码/脚本 --- + CODE_PYTHON = "Code_Python" + + # --- 实体交互类型 (严格命名) --- + ITEM = "Item" # 主动掉落接口 (Tool -> Item) + HIDDEN_ITEM = "Hidden_Item" # 被动掉落接口 (Item -> Item) + +# 3. 端口定义 +class Port(BaseModel): + name: str + type: InterfaceType + description: str + +# 4. 统一节点定义 (融合工具和物品) +class Node(BaseModel): + id: str + name: str + description: str + type: str # "Tool" or "Item" + + # 接口定义 + inputs: List[Port] = [] + outputs: List[Port] = [] + + # 状态字段 + content: Optional[Any] = None # 物品有内容,工具为None + if_success: Optional[bool] = None # 工具初始为False,物品为None + initial_visible: bool = False + + # 运行时状态 (Server维护) + is_revealed: bool = False + + # 标记该 Tool 节点是否有待触发的 HIDDEN_ITEM 掉落 + # 当 Tool 按照 golden_input 正确执行且有 HIDDEN_ITEM 输出边时设为 True + # 在 investigate 该 Tool 时触发掉落并重置为 False + has_hidden_item_ready: bool = False + + # 初始输入值 (metadata.initial_values.init_inputs,用于渐进式暴露判断) + init_input_values: Dict[str, Any] = {} + + # Golden 输入值 (nodes[].inputs[].value,用于评测验证) + golden_input_values: Dict[str, Any] = {} + + # Golden 输出值 (nodes[].outputs[].value,用于评测验证和 Item 节点的 content) + golden_output_values: Dict[str, Any] = {} + + # 实际获得的输出值历史 (工具每次执行后实际返回的输出列表,用于渐进式暴露判断) + # 格式: List[Dict[str, Any]],每个元素是一次执行的输出字典 + actual_outputs_history: List[Dict[str, Any]] = [] + + # 逻辑规则 (用于终端机等复杂物品) + logic_rules: Optional[Dict[str, Any]] = None + + def copy(self, **kwargs): + """Helper to create a copy with updated fields.""" + data = self.dict() + data.update(kwargs) + return Node(**data) + +# 5. 边定义 (拓扑结构) +class Edge(BaseModel): + source_id: str + target_id: str + connection_type: InterfaceType # 直接使用 InterfaceType + # 如果是 Data_Flow,指定端口对应关系 + source_port: Optional[str] = None + target_port: Optional[str] = None + +# 6. 完整图定义 +class GraphScenario(BaseModel): + case_id: str + title: str + intro_narrative: str + nodes: Dict[str, Node] + edges: List[Edge] + difficulty: int + win_node_id: str # 标记哪个节点是最终目标(通常是一个提交工具或最终物品) diff --git a/tasks/agentescape-25-skeleton-534660f4/environment/puzzle/upstream/server.py b/tasks/agentescape-25-skeleton-534660f4/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-25-skeleton-534660f4/environment/puzzle/upstream/server.py @@ -0,0 +1,1490 @@ +import json +import os +import time +import logging +import random +from pathlib import Path +from typing import Dict, Any, List, Optional +from datetime import datetime +from collections import defaultdict +from fastapi import FastAPI, HTTPException, Request +from fastapi.responses import JSONResponse +from fastapi.middleware.cors import CORSMiddleware +from pydantic import BaseModel, Field + +from models import GraphScenario, Node, InterfaceType +# from generator import ScenarioGenerator +from simulator import ToolSimulator +import uvicorn + +# 配置日志 +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler('server.log'), + logging.StreamHandler() + ] +) +logger = logging.getLogger(__name__) + +app = FastAPI( + title="AgentEscapeBench Universal Server", + version="1.0.0", + description="Industrial-grade evaluation server for escape room AI agents" +) + +# 添加 CORS 支持 +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# In-memory State +SCENARIOS: Dict[str, GraphScenario] = {} +SIMULATORS: Dict[str, ToolSimulator] = {} # case_id -> ToolSimulator +RAW_NODES_DATA: Dict[str, Dict[str, Any]] = {} # case_id -> node_id -> raw node data (for template_id) +FILE_METADATA: Dict[str, Dict[str, Any]] = {} # case_id -> metadata (for initial_values access) + +# Performance monitoring +STATS: Dict[str, Any] = { + "total_requests": 0, + "successful_requests": 0, + "failed_requests": 0, + "tool_calls": defaultdict(int), + "investigates": defaultdict(int), + "use_items": defaultdict(int), + "case_loads": 0, + "start_time": datetime.now() +} + +# Request timing middleware +@app.middleware("http") +async def add_process_time_header(request: Request, call_next): + start_time = time.time() + STATS["total_requests"] += 1 + + try: + response = await call_next(request) + STATS["successful_requests"] += 1 + process_time = time.time() - start_time + response.headers["X-Process-Time"] = str(process_time) + logger.info(f"{request.method} {request.url.path} - {response.status_code} - {process_time:.3f}s") + return response + except Exception as e: + STATS["failed_requests"] += 1 + logger.error(f"{request.method} {request.url.path} - Error: {str(e)}") + raise + +# Exception handler +@app.exception_handler(Exception) +async def global_exception_handler(request: Request, exc: Exception): + logger.error(f"Unhandled exception: {exc}", exc_info=True) + return JSONResponse( + status_code=500, + content={ + "ok": False, + "error": "Internal server error", + "detail": str(exc) if os.getenv("DEBUG") else "An error occurred" + } + ) + +# Health check endpoint +@app.get("/health") +def health_check(): + """健康检查端点""" + uptime = (datetime.now() - STATS["start_time"]).total_seconds() + return { + "status": "healthy", + "version": "1.0.0", + "uptime_seconds": uptime, + "loaded_cases": len(SCENARIOS), + "stats": { + "total_requests": STATS["total_requests"], + "successful_requests": STATS["successful_requests"], + "failed_requests": STATS["failed_requests"], + "success_rate": STATS["successful_requests"] / max(STATS["total_requests"], 1) + } + } + +# Statistics endpoint +@app.get("/stats") +def get_stats(): + """获取详细统计信息""" + return { + "stats": STATS, + "loaded_cases": list(SCENARIOS.keys()), + "uptime": str(datetime.now() - STATS["start_time"]) + } + +def _apply_progressive_reveal_at_init(scenario: GraphScenario): + """ + 在初始化时应用渐进式暴露机制(基于ITEM/HIDDEN_ITEM边) + + 新逻辑: + - 如果一个节点没有 ITEM/HIDDEN_ITEM 类型的入边,它就是初始可见的 + - 如果一个节点有 ITEM/HIDDEN_ITEM 类型的入边,它初始不可见,需要等待上游触发 + + Args: + scenario: 场景对象 + """ + # 收集所有有 ITEM/HIDDEN_ITEM 入边的节点 + nodes_with_item_edges = set() + for edge in scenario.edges: + if edge.connection_type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + nodes_with_item_edges.add(edge.target_id) + + logger.info(f"Nodes with ITEM/HIDDEN_ITEM incoming edges: {nodes_with_item_edges}") + + # 设置初始可见性:没有 ITEM/HIDDEN_ITEM 入边的节点初始可见 + initially_visible_count = 0 + for node_id, node in scenario.nodes.items(): + if node_id not in nodes_with_item_edges: + node.is_revealed = True + initially_visible_count += 1 + logger.info(f"Initial visible (no ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + else: + node.is_revealed = False + logger.debug(f"Initial hidden (has ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + + logger.info(f"Progressive reveal initialized: {initially_visible_count}/{len(scenario.nodes)} nodes initially visible") + + +def _check_inputs_match_golden(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> bool: + """ + 检查实际输入参数是否与 golden inputs 完全匹配 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + True 表示所有 golden inputs 都存在且值匹配 + """ + if not golden_inputs: + return True # 如果没有 golden inputs,认为匹配 + + for key, expected_value in golden_inputs.items(): + actual_value = arguments.get(key) + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) != str(expected_value): + logger.debug(f"Input mismatch for '{key}': expected '{expected_value}', got '{actual_value}'") + return False + + return True + + +def _get_parameter_validation_feedback(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> Dict[str, Any]: + """ + 对源头节点的参数进行详细验证,返回验证反馈 + + 注意:不返回期望值(expected),避免泄漏答案 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + 包含验证结果的字典: + - all_correct: bool - 所有参数是否正确 + - correct_params: List[str] - 正确的参数名列表 + - incorrect_params: List[str] - 错误的参数名列表(不包含期望值) + """ + if not golden_inputs: + return { + "all_correct": True, + "correct_params": [], + "incorrect_params": [] + } + + correct_params = [] + incorrect_params = [] + + for key, actual_value in arguments.items(): + # 只对用户实际提交的参数给反馈,未提交的参数不评价 + if key not in golden_inputs: + continue # 该参数不在 golden 中,跳过(如 _golden_inputs 等内部参数) + expected_value = golden_inputs[key] + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) == str(expected_value): + correct_params.append(key) + else: + # 只记录参数名,不包含期望值,避免泄漏答案 + incorrect_params.append(key) + + # all_correct:用户提交的所有参数都正确,且覆盖了全部 golden 参数 + all_provided_correct = len(incorrect_params) == 0 + all_golden_covered = all(k in arguments for k in golden_inputs) + return { + "all_correct": all_provided_correct and all_golden_covered, + "correct_params": correct_params, + "incorrect_params": incorrect_params + } + + +def _is_source_node(node_id: str, scenario: GraphScenario) -> bool: + """ + 判断节点是否是源头节点(完全没有任何入边的节点) + + 源头节点定义: + - 没有任何类型的入边(包括 DATA、ITEM、HIDDEN_ITEM) + - 即没有任何上游节点 + + Args: + node_id: 节点ID + scenario: 场景对象 + + Returns: + True 表示是源头节点 + """ + for edge in scenario.edges: + if edge.target_id == node_id: + # 只要有任何入边,就不是源头节点 + return False + + return True + + +def _check_and_reveal_ready_nodes(scenario: GraphScenario, recent_outputs: Dict[str, Any], source_node_id: str) -> List[Dict[str, Any]]: + """ + 检查并释放参数齐全的隐藏节点(渐进式暴露机制) + + 核心逻辑: + 1. 维护"可见值集合":包含所有被测模型当前可以看到的值 + - init_inputs 的值(初始可见) + - 工具执行后的实际输出值(运行时获得) + - 可见 Item 的输出值 + 2. 检查隐藏节点:该节点的所有 golden_input 值是否都在可见值集合中 + 3. 如果是,则释放该节点 + + Args: + scenario: 场景对象 + recent_outputs: 最近执行的工具的输出 + source_node_id: 刚执行的工具节点ID + + Returns: + 新释放的节点列表 + """ + newly_revealed = [] + + # 构建"可见值集合"(Set of visible values) + # 存储格式:set of values (转为字符串) + visible_values = set() + + # 1. 添加有意义的 init_inputs 值到可见值集合 + # Item 的 init_inputs 不应该加入,因为它们在密室中完全用不到 + for node_id, node in scenario.nodes.items(): + # 跳过源头 Item 节点(没有入边的 Item) + if node.type == "Item": + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,跳过其 init_inputs + continue + + # 添加其他节点的 init_inputs + for port_name, init_value in node.init_input_values.items(): + if init_value: + visible_values.add(str(init_value)) + + # 2. 添加已执行工具的所有历史输出值 + for node_id, node in scenario.nodes.items(): + if node.type == "Tool" and node.if_success and node.actual_outputs_history: + # 遍历所有历史执行记录 + for output_dict in node.actual_outputs_history: + for output_port_name, output_value in output_dict.items(): + if output_value: + visible_values.add(str(output_value)) + + # 3. 添加已被 investigate 的 Item 的 golden 输出值 + # 注意:Item 可见不等于其输出值可见,需要 investigate 后才能获得 + # 这里我们使用 actual_outputs_history 来标记 Item 是否已被 investigate + for node_id, node in scenario.nodes.items(): + if node.type == "Item" and node.is_revealed and node.actual_outputs_history: + # Item 通常只会被 investigate 一次,但为了一致性也使用历史列表 + for output_dict in node.actual_outputs_history: + for port_name, port_value in output_dict.items(): + if port_value: + visible_values.add(str(port_value)) + + # 遍历所有隐藏的节点,检查其 golden_input 是否都在可见值集合中 + for node_id, node in scenario.nodes.items(): + # 跳过已可见的节点 + if node.is_revealed: + continue + + # 只检查工具节点(物品节点由 ITEM 输出触发) + if node.type != "Tool": + continue + + # 检查该节点的所有 golden_input 值是否都在可见值集合中 + all_inputs_ready = True + missing_values = [] + + for input_port_name, golden_input_value in node.golden_input_values.items(): + # 检查这个 golden 值是否在可见值集合中 + if str(golden_input_value) not in visible_values: + all_inputs_ready = False + missing_values.append(f"{input_port_name}={golden_input_value}") + + # 如果所有 golden_input 值都在可见值集合中,释放该节点 + if all_inputs_ready and len(node.golden_input_values) > 0: + logger.info(f"All golden inputs ready for {node_id}: {list(node.golden_input_values.values())}") + + # 如果所有输入都齐全,释放该节点 + if all_inputs_ready: + node.is_revealed = True + + # 构建节点信息返回给模型 + node_info = { + "id": node.id, + "type": node.type, + "can_investigate": True, + "hint": "This tool's input parameters are now complete, you can use investigate to view detailed information" + } + + # if node.name: + # node_info["name"] = node.name + if node.description: + node_info["description"] = node.description + + newly_revealed.append(node_info) + logger.info(f"Progressive reveal: {node_id} is now ready (all inputs satisfied)") + + return newly_revealed + + +def _initialize_node_values(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]): + """ + Initialize node state and load values from port value fields. + 应用渐进式暴露机制:初始时只显示参数齐全的节点(源头节点) + + 重要区分: + 1. input_values: 只加载 metadata.initial_values 中的 init_inputs(真正的初始值) + 2. output_values: 加载 nodes[].outputs[].value(golden 输出,用于验证) + """ + # 第一步:加载所有节点的值,并将所有节点初始设为隐藏 + initial_values = metadata.get('initial_values', {}) + + for node_id, node in scenario.nodes.items(): + # 忽略 initial_visible 字段,初始全部隐藏 + # 由渐进式暴露机制根据参数齐全情况决定是否显示 + node.is_revealed = False + + if node.type == "Tool": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + elif node.type == "Item": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + + # 从 JSON 加载值 + if node_id in raw_nodes_data: + node_data = raw_nodes_data[node_id] # node_data是json文件中nodes中的字典 + + # 【重要】只加载 metadata.initial_values 中的初始输入值 + if node_id in initial_values: + init_data = initial_values[node_id] + # 加载初始输入值(用于渐进式暴露判断) + for port_name, port_value in init_data.get('init_inputs', {}).items(): + node.init_input_values[port_name] = port_value + + # 【评测用】加载 golden 输入值(用于验证模型传入的参数是否正确) + for input_port_data in node_data.get('inputs', []): + if 'value' in input_port_data: + node.golden_input_values[input_port_data['name']] = input_port_data['value'] + + # 【评测用】加载 golden 输出值(用于验证工具调用是否正确,以及 Item 节点的 content) + for output_port_data in node_data.get('outputs', []): + if 'value' in output_port_data: + node.golden_output_values[output_port_data['name']] = output_port_data['value'] + + # For Items, set content from golden_output_values + if node.type == "Item" and node.golden_output_values: + # Item 的 content 是其第一个 golden 输出值 + node.content = list(node.golden_output_values.values())[0] + + # 第二步:应用渐进式暴露机制 + # 检查所有节点,根据参数齐全情况释放源头节点(工具 + Item) + _apply_progressive_reveal_at_init(scenario) + +def _build_node_info(node: Node, raw_nodes_data: Dict[str, Any]) -> Dict[str, Any]: + """ + 构建节点信息(工具或物品) + + Args: + node: 节点对象 + raw_nodes_data: 原始节点数据(用于获取 template_id 等) + + Returns: + 节点信息字典 + """ + if node.type == "Tool": + # 过滤掉输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口) + # 这些端口仅用于控制掉落机制,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + tool_info = { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Tool", + "inputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.inputs if p.type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]], + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id(工具的标准名称) + if node.id in raw_nodes_data: + node_data = raw_nodes_data[node.id] + template_id = node_data.get('template_id') + if template_id: + tool_info['template_id'] = template_id + + return tool_info + + elif node.type == "Item": + return { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Item" + } + + else: + return { + "id": node.id, + # "name": node.name, + "type": node.type + } + +def _get_initial_observation(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]) -> Dict[str, Any]: + """ + Generate initial observation for the agent (what they see when entering the room). + + 策略: + - Tools: 只显示名称和描述,不显示接口定义。需要 investigate 才能获得详细接口信息。 + - Items: 只显示存在,不显示内容。需要 investigate 才能获得内容值。 + - init_inputs: 作为"可用信息"告诉模型,这些是可以用作工具参数的初始值。 + - init_outputs: 不告诉模型(这些是答案,需要模型通过调用工具获得)。 + """ + available_entities = [] # 统一的实体列表(Tools 和 Items) + available_information = [] # 可用的初始信息(来自 init_inputs) + + # 从 metadata.initial_values 提取 init_inputs 作为可用信息 + # 只提供值本身,不透露这些值对应哪个节点的哪个参数,让模型自己推理 + # 注意:跳过源头 Item(没有入边的 Item)的 init_inputs,因为它们在密室中完全用不到 + initial_values = metadata.get('initial_values', {}) + # initial_values字段的格式 + # "initial_values": { + # "terminal_1": { + # "init_inputs": {}, + # "init_outputs": { + # "text_output": "System initialization complete.", + # "hex_output": "48656c6c6f20576f726c64", + # "item_dispenser": "掉落了一张纸条,上面写着“请勿随意触摸终端”" + # } + # } + # } + for node_id, init_data in initial_values.items(): + # 获取节点信息,判断是否为源头 Item + node = scenario.nodes.get(node_id) + if node and node.type == "Item": + # 检查是否为源头 Item(没有入边) + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,检查是否有 init_inputs + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 有 init_inputs,需要暴露这些参数 + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + # 处理完后跳过后续的通用逻辑 + continue + + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 为每个 init_input 值创建一个信息条目(不包含 source_node 和 parameter 信息) + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + + for node in scenario.nodes.values(): + if node.is_revealed: + # Tools: 只显示基本信息,提示可以 investigate 查看详细接口 + if node.type == "Tool": + tool_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Tool", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the tool's detailed interface information for calling" + } + # 只在 name 非空时添加 + # if node.name: + # tool_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_info["description"] = node.description + + available_entities.append(tool_info) + + # Items: 只显示基本信息,提示可以 investigate 查看内容 + elif node.type == "Item": + item_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Item", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the item's content" + } + # 只在 name 非空时添加 + # if node.name: + # item_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + item_info["description"] = node.description + + available_entities.append(item_info) + + return { + "narrative": scenario.intro_narrative, + "available_entities": available_entities, # 使用统一的实体列表 + "available_information": available_information, # 可用的初始信息(只包含 init_inputs) + "win_node_id": scenario.win_node_id # 胜利节点ID,让模型知道需要关注哪个节点 + } + +@app.post("/env/reset") +def reset_case(case_id: str = None, case_file_path: str = None, session_id: str = None): + """Loads a specific case from file and resets it. + + Args: + case_id: Optional case ID for resetting an existing case + case_file_path: Path to case file for loading a new case + session_id: Optional session ID to ensure isolation between concurrent evaluations + """ + logger.info(f"Reset request - case_id: {case_id}, case_file_path: {case_file_path}, session_id: {session_id}") + STATS["case_loads"] += 1 + + if case_file_path: + if not os.path.exists(case_file_path): + logger.error(f"Case file not found: {case_file_path}") + raise HTTPException(status_code=404, detail=f"File not found: {case_file_path}") + try: + with open(case_file_path, "r", encoding="utf-8") as f: + file_data = json.load(f) + + # 转换格式:从 DAG executor 生成的格式转换为 GraphScenario 格式 + # 1. 提取 metadata + metadata = file_data.get('metadata', {}) + + # 2. 生成 case_id, title, intro_narrative + # 【修复】为每个评测会话生成唯一的 case_id,防止并发评测时状态污染 + base_name = os.path.basename(case_file_path).replace('.json', '').replace('_full', '').replace('_full2', '') + + if session_id: + # 如果提供了 session_id,使用它来确保唯一性 + case_id = f"{base_name}_{session_id}" + else: + # 否则使用时间戳和随机数确保唯一性 + unique_suffix = f"{int(time.time() * 1000)}_{random.randint(1000, 9999)}" + case_id = f"{base_name}_{unique_suffix}" + + file_data['case_id'] = case_id + logger.info(f"Generated unique case_id: {case_id} (base: {base_name}, session: {session_id})") + + if 'title' not in file_data: + file_data['title'] = f"Escape Room: {file_data['case_id']}" + + if 'intro_narrative' not in file_data: # 目前的json文件中已经有了intro_narrative字段,不会使用下面一行的内容,而是使用每个评测问题的json文件中的对应字段 + 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]".' + + # 3. 转换 nodes 列表为字典(DAG executor 生成的文件中 nodes 是列表格式) + nodes_dict = {} + for node_data in file_data['nodes']: + nodes_dict[node_data['id']] = node_data # 这里的id是template_id之后可能添加一个后缀 + file_data['nodes'] = nodes_dict # 把列表转成一个字典 + + # 4. 添加缺失的字段 + if 'difficulty' not in file_data: + file_data['difficulty'] = metadata.get('total_nodes', 5) + + if 'win_node_id' not in file_data: + file_data['win_node_id'] = metadata.get('win_node_id', '') + + scenario = GraphScenario(**file_data) + + # Extract raw nodes data for template_id access + # nodes 已经在上面转换为字典格式 + raw_nodes_data = file_data.get('nodes', {}) + RAW_NODES_DATA[scenario.case_id] = raw_nodes_data + + # Store metadata for initial values access + FILE_METADATA[scenario.case_id] = metadata + + logger.info(f"Successfully parsed case file: {scenario.case_id}, nodes: {len(scenario.nodes)}, edges: {len(scenario.edges)}") + except Exception as e: + logger.error(f"Failed to load case file: {str(e)}", exc_info=True) + raise HTTPException(status_code=500, detail=f"Failed to load case file: {str(e)}") + + # Initialize node state and load values + _initialize_node_values(scenario, raw_nodes_data, metadata) + + SCENARIOS[scenario.case_id] = scenario + simulator = ToolSimulator() + SIMULATORS[scenario.case_id] = simulator + + 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'])}") + + # 生成初始观察信息(进入密室后看到的环境) + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + ''' + initial_observation的格式: + { + "narrative": scenario.intro_narrative, + "available_entities": available_entities # 使用统一的实体列表 + "available_information": available_information # 可用的初始信息(只包含 init_inputs) + } + ''' + + return { + "ok": True, + "message": f"Case loaded from {case_file_path}", + "case_id": scenario.case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果没有提供 case_file_path,但提供了 case_id,则尝试从内存重置 + if case_id and case_id in SCENARIOS: + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + metadata = FILE_METADATA.get(case_id, {}) + + # Reset dynamic fields and re-apply progressive reveal + # 重新初始化节点状态(包括渐进式暴露) + _initialize_node_values(scenario, raw_nodes_data, metadata) + + 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'])}") + + # 生成初始观察信息 + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + + return { + "ok": True, + "message": f"Case {case_id} reset.", + "case_id": case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果既没有 case_file_path,也没有在内存中找到,返回错误 + raise HTTPException( + status_code=400, + detail="Must provide case_file_path to load a new case, or use case_id to reset an existing case." + ) + +class InvestigateRequest(BaseModel): + node_id: str + +@app.post("/env/{case_id}/investigate") +def investigate(case_id: str, req: InvestigateRequest): + """ + Investigates a Tool or Item to reveal detailed information. + + - For Tools: Returns detailed interface information (inputs/outputs) needed to call the tool + - For Items: Returns content value and triggers hidden item drops + """ + logger.info(f"Investigate request - case_id: {case_id}, node_id: {req.node_id}") + STATS["investigates"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + node = scenario.nodes[req.node_id] + + if not node.is_revealed: + logger.warning(f"Attempt to investigate hidden node: {req.node_id}") + return {"ok": False, "error": "Node is not visible yet."} + + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + newly_revealed = [] + + # 处理 Tool 的 investigate + if node.type == "Tool": + logger.info(f"Investigating tool: {req.node_id}") + + # 返回工具的详细接口信息 + # id 字段使用 node.id(节点唯一标识),agent 用这个字段识别和调用具体的节点 + # template_id 是工具类型标识符,Agent 内部用于判断工具特性(如 terminal 类工具参数可选) + # 注意:只过滤输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口),这些端口仅用于控制掉落,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + # 【端口上游依赖提示 & 初始值直接给出】 + # 针对参数语义模糊(全为数字类型)的工具,在 investigate 返回信息中标注 + # 哪个输入端口来自哪个上游节点(upstream_from)。 + # 对于所有工具:若该节点不是纯源头节点(有任意数据流入边), + # 且某个端口没有上游入边(值来自初始可见参数),则直接给出该端口的 golden input 值。 + AMBIGUOUS_TOOLS = { + "num_base_convert", "calc_modexp", "calc_modexp_int", + "calc_inv_mod", "calc_inv_mod_int", "crypto_rsa_decrypt_hex", "geo_haversine" + } + # Terminal 类工具自带参数对错反馈机制,玩家/模型可自行试错, + # 无需在 investigate 时直接暴露 init_value + SELF_FEEDBACK_TOOLS = { + "terminal_1", "terminal_2", + "Logic Terminal", "Math Terminal", "Encryption Terminal", "Sequence Terminal" + } + _template_id_for_hint = raw_nodes_data.get(node.id, {}).get("template_id", "") + # 构建数据流入边映射(对所有工具):{target_port -> (source_node_id, source_port)} + _upstream_map = {} + for _edge in scenario.edges: + if (_edge.target_id == node.id + and _edge.connection_type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM] + and _edge.target_port is not None): + _upstream_map[_edge.target_port] = (_edge.source_id, _edge.source_port) + # 判断该节点是否有任意数据流入边(即不是纯源头节点) + _has_any_upstream = len(_upstream_map) > 0 + # 判断该节点是否有任意入边(包括 ITEM/HIDDEN_ITEM 掉落边) + # 有任意入边(含掉落边)但无数据流入边的节点,其输入来自初始可见参数,应直接给出 + _has_any_edge = any(_edge.target_id == node.id for _edge in scenario.edges) + # 构建 inputs 列表 + _inputs_list = [] + for p in node.inputs: + if p.type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + continue + port_dict = {"name": p.name, "type": p.type, "description": p.description} + if p.name in _upstream_map: + # 该端口有上游数据流依赖,且属于语义模糊工具 → 标注来源 + if _template_id_for_hint in AMBIGUOUS_TOOLS: + src_node_id, src_port = _upstream_map[p.name] + port_dict["upstream_from"] = f"{src_node_id}.{src_port}" if src_port else src_node_id + elif _has_any_edge and _template_id_for_hint not in SELF_FEEDBACK_TOOLS: + # 该节点有任意入边,但此端口没有数据流入边 → 值来自初始可见参数,直接给出 + # 排除自带反馈机制的 terminal 类工具(它们通过执行结果反馈对错,无需提前暴露参数值) + golden_val = node.golden_input_values.get(p.name) + if golden_val is not None: + port_dict["init_value"] = golden_val + _inputs_list.append(port_dict) + + tool_details = { + "id": node.id, # 节点 ID,用于唯一标识和调用这个具体节点 + "type": "Tool", + "inputs": _inputs_list, + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id 用于 Agent 内部判断工具类型(不会展示给被测模型) + if node.id in raw_nodes_data: + template_id = raw_nodes_data[node.id].get('template_id') + if template_id: + tool_details["_template_id"] = template_id # 使用下划线前缀标记为内部字段 + + # 只在 name 非空时添加 + # if node.name: + # tool_details["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_details["description"] = node.description + + # 添加 narrative 字段(如果存在) + if node.id in raw_nodes_data: + narrative = raw_nodes_data[node.id].get('narrative') + if narrative: + tool_details['narrative'] = narrative + + # 不再返回 init_values,避免泄漏答案 + # investigate 只应该返回工具的接口定义,不应该暴露初始值 + + # 【新增】检查该 Tool 是否有待触发的 HIDDEN_ITEM 掉落 + # 如果该工具已按照 golden_input 正确执行,且有 HIDDEN_ITEM 输出边,则触发掉落 + if node.has_hidden_item_ready: + logger.info(f"Tool has HIDDEN_ITEM ready - triggering passive drop for: {req.node_id}") + + # 遍历该工具的所有 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + # 重置标志,已经触发过了,避免重复 + node.has_hidden_item_ready = False + + logger.info(f"Tool investigation successful - node: {req.node_id}, revealed: {len(newly_revealed)}") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Tool", + "details": tool_details + } + + # 如果有新掉落的节点,添加到响应中 + if newly_revealed: + result["newly_revealed"] = newly_revealed + + return result + + # 处理 Item 的 investigate + elif node.type == "Item": + logger.info(f"Investigating item: {req.node_id}") + + # 【第一步】检查该 Item 是否有需要参数的输入端口 + # 如果有,且尚未通过 use_item 验证,则不返回内容,只返回参数要求 + required_inputs = [] + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + inputs_info = raw_node.get('inputs', []) + required_inputs = [ + { + "name": inp.get("name"), + "type": inp.get("type"), + "description": inp.get("description", "") + } + for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + # 如果有 required_inputs 且尚未通过 use_item 验证(if_success == False) + # 则不返回内容,只返回参数要求提示 + if required_inputs and not node.if_success: + logger.info(f"Item has required inputs and not yet unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "required_inputs": required_inputs + } + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + param_names = ', '.join([inp['name'] for inp in required_inputs]) + 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}" + + return result + + # 【新增】如果有 required_inputs 且已经通过 use_item 验证(if_success == True) + # 则返回提示:该节点已经被成功解决 + if required_inputs and node.if_success: + logger.info(f"Item has required inputs and already unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "message": "This item has already been successfully unlocked by you." + } + return result + + # 【第二步】该 Item 没有 required_inputs 或已通过验证,返回内容 + # 1. 返回 Item 的 golden_output_values(即 Item 的内容) + # 注意:某些 Item 仅用于触发 HIDDEN_ITEM 掉落,没有实际内容 + has_actual_content = bool(node.golden_output_values) or node.content is not None + content = node.golden_output_values if node.golden_output_values else node.content + + # 【关键】将 golden_output_values 追加到 actual_outputs_history,标记该 Item 已被 investigate + # 这样在渐进式暴露时,这些值才会被加入可见值集合 + # 即使是空字典(仅触发 HIDDEN_ITEM 的 Item),也要记录,以便渐进式暴露逻辑知道该 Item 已被调查 + if node.golden_output_values is not None: + node.actual_outputs_history.append(dict(node.golden_output_values)) + + # 2. Trigger Hidden Item Drops (Passive Drop) + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + logger.info(f"Item investigation successful - node: {req.node_id}, has_content: {has_actual_content}, revealed: {len(newly_revealed)}") + + # 【渐进式暴露】旧机制(基于 golden_input)已禁用 + # 现在完全由 ITEM/HIDDEN_ITEM 边触发控制节点可见性 + # 上面的 HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, node.golden_output_values or {}, node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # logger.info(f"Progressive reveal after Item investigate: {len(progressive_revealed)} nodes now ready") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Item" + } + + # 只在有实际内容时才添加 content 字段 + # 对于仅触发 HIDDEN_ITEM 掉落的 Item,不返回 content 字段,避免返回 None 或空字典让模型困惑 + if has_actual_content: + result["content"] = content + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型通过 investigate 获得内容后,需要自己识别这是否是胜利字符串 + + return result + + else: + logger.warning(f"Attempt to investigate unknown node type: {req.node_id} (type: {node.type})") + return {"ok": False, "error": f"Cannot investigate node type: {node.type}"} + +class ToolCallRequest(BaseModel): + node_id: str # 使用 node_id 精确指定要调用的节点 + arguments: Dict[str, Any] + +@app.post("/env/{case_id}/tool_call") +def tool_call(case_id: str, req: ToolCallRequest): + """Executes a tool and triggers item drops.""" + logger.info(f"Tool call request - case_id: {case_id}, node_id: {req.node_id}, args: {list(req.arguments.keys())}") + STATS["tool_calls"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + + # 通过 node_id 精确查找节点 + node_id = req.node_id + if node_id not in scenario.nodes: + logger.error(f"Node not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + tool_node = scenario.nodes[node_id] + + if not tool_node: + logger.error(f"Tool not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Tool not found") + + if not tool_node.is_revealed: + logger.warning(f"Attempt to call hidden tool: {node_id}") + return {"ok": False, "error": "Tool is not visible yet."} + + if tool_node.type != "Tool": + logger.warning(f"Attempt to call non-tool node: {node_id} (type: {tool_node.type})") + return {"ok": False, "error": "Only tools can be called."} + + # 1. Execute Tool (Real Execution via Simulator) + simulator = SIMULATORS[case_id] + + # Get tool name from template_id if available, otherwise use node name + tool_name = tool_node.name + if case_id in RAW_NODES_DATA and node_id in RAW_NODES_DATA[case_id]: + template_id = RAW_NODES_DATA[case_id][node_id].get('template_id') + if template_id: + tool_name = template_id + + # 文件处理工具和 Terminal 需要验证输入并返回预先计算的输出 + # 传递节点的实际输入输出值(从 DAG 执行后填充的数据) + tool_arguments = dict(req.arguments) # Make a copy + + # 传递节点的 golden values(从 JSON 的 inputs[].value 和 outputs[].value 加载) + # 用于在评测阶段验证被测模型传入的参数是否正确 + if tool_node.golden_input_values: + tool_arguments['_golden_inputs'] = tool_node.golden_input_values + if tool_node.golden_output_values: + tool_arguments['_golden_outputs'] = tool_node.golden_output_values + + logger.debug(f"Executing tool {tool_name} (node: {tool_node.name}) with args {tool_arguments}") + + try: + output_values = simulator.execute(tool_name, tool_arguments) + logger.info(f"Tool invoked - {tool_name}: {list(output_values.keys())}") + except Exception as e: + logger.error(f"Tool execution failed - {tool_name}: {str(e)}", exc_info=True) + return {"ok": False, "error": f"Tool execution failed: {str(e)}"} + + # 检查验证结果(精细化错误反馈) + validation = output_values.pop("_validation", {"valid": True}) + + if not validation["valid"]: + # 根据错误类型构造友好的错误消息 + error_type = validation.get("error_type") + + if error_type == "missing_required": + missing = validation.get("missing_params", []) + error_msg = f"Error: Missing required parameters {', '.join(missing)}" + + elif error_type == "type_error": + param = validation.get("param_name") + message = validation.get("message", "Parameter type error") + error_msg = f"Error: {message}" + + elif error_type == "incomplete_optional": + provided = validation.get("provided_params", []) + missing = validation.get("missing_params", []) + error_msg = ( + f"Hint: You provided some parameters ({', '.join(provided)}), " + f"but may also need: {', '.join(missing)}.\n" + f"Trying to provide these parameters together might yield better results." + ) + + elif error_type == "value_mismatch": + param = validation.get("param_name") + hint = validation.get("hint", "Parameter value may be incorrect") + error_msg = f"Hint: {hint}.\nPlease check if this parameter value meets the requirements." + + else: + error_msg = validation.get("hint") or validation.get("message", "Parameter validation failed") + + logger.info(f"Tool validation failed - {tool_name}: {error_type}") + return { + "ok": False, + "error": error_msg, + "error_type": error_type + } + + # Simulate success + tool_node.if_success = True + + # 【关键】将本次执行的输出值追加到历史列表(用于渐进式暴露判断) + # 每次调用都会记录,不会覆盖之前的执行结果 + tool_node.actual_outputs_history.append(dict(output_values)) + + # 2. 检查是否应该触发掉落(只有输入参数正确时才掉落) + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, tool_node.golden_input_values) + + newly_revealed = [] + investigate_hints = [] # 提示模型哪些节点可以 investigate 来发现隐藏内容 + + if inputs_match_golden: + logger.info(f"✓ Tool inputs match golden - node: {node_id}, triggering drops") + + # 检查该工具是否有 ITEM 或 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == tool_node.id: + target_node = scenario.nodes[edge.target_id] + + # ITEM 边:立即掉落(主动掉落) + if edge.connection_type == InterfaceType.ITEM: + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from {node_id})") + + # HIDDEN_ITEM 边:不立即掉落,标记并提示(被动掉落) + elif edge.connection_type == InterfaceType.HIDDEN_ITEM: + # 标记该工具有待触发的 HIDDEN_ITEM 掉落 + tool_node.has_hidden_item_ready = True + + # 提示模型可以 investigate 这个工具来发现隐藏内容 + hint_info = { + "tool_id": tool_node.id, + "hint": f"Tool '{tool_node.id}' seems to hide something, try investigating it to discover more information" + } + # if tool_node.name: + # hint_info["tool_name"] = tool_node.name + + investigate_hints.append(hint_info) + logger.info(f"HIDDEN_ITEM ready: {tool_node.id} -> {target_node.id} (will drop on investigate)") + else: + logger.info(f"✗ Tool inputs do NOT match golden - node: {node_id}, no drops triggered") + + response = { + "ok": True, + "message": "Tool invoked", + "output_values": output_values # Return raw outputs to Agent + } + + # 【新增】对源头节点进行参数验证反馈 + # 源头节点:没有数据流入边的节点,这些节点的参数需要模型自己推理 + # 验证模型使用的参数是否正确,并提供明确的反馈 + if _is_source_node(node_id, scenario) and tool_node.golden_input_values: + validation_feedback = _get_parameter_validation_feedback(req.arguments, tool_node.golden_input_values) + + if validation_feedback["all_correct"]: + # 用户提交了全部 golden 参数且全部正确 + response["parameter_feedback"] = { + "status": "correct", + "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." + } + logger.info(f"✓ Source node parameters all correct - node: {node_id}") + elif validation_feedback["incorrect_params"]: + # 有提交了但值错误的参数,只对这些参数给出反馈 + incorrect_list = [] + for param_name in validation_feedback["incorrect_params"]: + incorrect_list.append(f" - Parameter '{param_name}' is incorrect") + + correct_info = "" + if validation_feedback["correct_params"]: + correct_info = f"\n✓ Correct parameters: {', '.join(validation_feedback['correct_params'])}" + + response["parameter_feedback"] = { + "status": "incorrect", + "message": ( + f"⚠️ Some parameters are incorrect:\n" + + "\n".join(incorrect_list) + + correct_info + + 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." + ), + "incorrect_params": validation_feedback["incorrect_params"], + "correct_params": validation_feedback["correct_params"] + } + logger.info(f"✗ Source node parameters incorrect - node: {node_id}, incorrect: {validation_feedback['incorrect_params']}") + # else: 部分提交且全部正确 → 不给任何 parameter_feedback,避免对未提交的参数发表意见 + + # 检查工具调用是否完全正确(输出与 golden outputs 匹配) + # 用于给模型正向反馈,让它知道这个工具已经正确调用过,避免重复调用 + # 注意:只有当输出完全匹配时才标记为 correct,不会在错误时提供具体错误信息 + # if tool_node.golden_output_values and output_values: + # is_correct = True + # for port_name, expected_value in tool_node.golden_output_values.items(): + # actual_value = output_values.get(port_name) + # if str(actual_value) != str(expected_value): + # is_correct = False + # break + + # if is_correct: + # response["tool_call_correct"] = True + # logger.info(f"✓ Tool called with correct result - node: {node_id}") + + # 只在有新内容掉落时才返回 newly_revealed + if newly_revealed: + response["newly_revealed"] = newly_revealed + + # 添加 investigate 提示(对于有待触发 HIDDEN_ITEM 掉落的工具) + if investigate_hints: + response["investigate_hints"] = investigate_hints + + # 3. 渐进式暴露机制 - 现在完全由 ITEM/HIDDEN_ITEM 边控制 + # 旧机制(基于 golden_input 检查)已被禁用 + # 新机制中,节点的可见性只由 ITEM/HIDDEN_ITEM 边触发决定 + # 上面的 ITEM/HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, output_values, tool_node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # response["newly_revealed"] = newly_revealed + # logger.info(f"Progressive reveal: {len(progressive_revealed)} nodes now ready") + + # Check if this is the win node + if node_id == scenario.win_node_id: + # 验证输出值是否等于预期的胜利值 + # 从节点的 golden_output_values 中获取预期值(在 _initialize_node_values 时从 JSON 加载) + expected_outputs = tool_node.golden_output_values + + # 检查实际输出是否与预期输出匹配 + is_correct = False + victory_string = None + mismatch_info = [] + + if expected_outputs and output_values: + # 检查每个预期输出端口的值是否匹配 + is_correct = True + for port_name, expected_value in expected_outputs.items(): + actual_value = output_values.get(port_name) + if actual_value != expected_value: + is_correct = False + mismatch_info.append(f"Port '{port_name}': expected '{expected_value}', actual '{actual_value}'") + logger.warning(f"Win node output mismatch - port: {port_name}, expected: {expected_value}, actual: {actual_value}") + + # 如果所有输出都匹配,使用第一个输出作为胜利字符串 + if is_correct and output_values: + victory_string = list(output_values.values())[0] + else: + logger.warning(f"Win node called but missing output values - expected: {expected_outputs}, actual: {output_values}") + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型调用工具获得输出后,需要自己识别这是否是胜利字符串并提交 + if is_correct: + logger.info(f"🎯 Win node called with correct output - case: {case_id}, node: {node_id}, victory: {victory_string}") + else: + logger.info(f"❌ Win node called with incorrect output - case: {case_id}, node: {node_id}") + + return response + +class UseItemRequest(BaseModel): + node_id: str = Field(..., description="The ID of the Item node to use (must be Item type)") + arguments: Dict[str, Any] = Field(default_factory=dict, description="Input arguments to provide to the item") + +@app.post("/env/{case_id}/use_item") +def use_item(case_id: str, req: UseItemRequest): + """ + Use an Item node by providing input arguments. + + This is specifically for Item nodes that require parameters to be "unlocked" or "activated", + such as containers that need a password/fingerprint. + + - Validates that the node is of type Item + - Checks if provided arguments match the item's golden_input_values + - If match: triggers ITEM-type edge drops and returns the item's content + - If not match: returns error message + """ + logger.info(f"Use item request - case_id: {case_id}, node_id: {req.node_id}, args: {req.arguments}") + STATS["use_items"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + item_node = scenario.nodes[req.node_id] + + if not item_node.is_revealed: + logger.warning(f"Attempt to use hidden item: {req.node_id}") + return {"ok": False, "error": "Item is not visible yet."} + + if item_node.type != "Item": + logger.warning(f"Attempt to use non-item node: {req.node_id} (type: {item_node.type})") + return {"ok": False, "error": "Only Item nodes can be used with use_item. Tools should be called with tool_call."} + + # 【新增】检查该 Item 是否已经被成功解锁 + # 如果已经被正确使用过,直接返回成功提示 + if item_node.if_success: + logger.info(f"Item already unlocked, returning success message: {req.node_id}") + return { + "ok": True, + "message": "This item has already been successfully unlocked by you." + } + + # 检查该 Item 是否真的需要通过 use_item 提供参数 + # 只有当 Item 有非 Item/Hidden_Item 类型的输入时,才应该使用 use_item + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + non_hidden_inputs = [ + inp for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + if not non_hidden_inputs: + # 该 Item 不需要参数,应该只使用 investigate + logger.warning(f"Attempt to use_item on a node that doesn't require parameters: {req.node_id}") + return { + "ok": False, + "error": "This item does not require parameters. Please use investigate to examine the item directly." + } + + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, item_node.golden_input_values) + + if not inputs_match_golden: + logger.info(f"✗ Item inputs do NOT match golden - node: {req.node_id}") + # 提供更详细的错误信息,帮助 Agent 理解问题 + # 只显示非 Item/Hidden_Item 类型的参数(Hidden_Item 由系统自动处理) + expected_params = [] + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + expected_params = [ + inp.get("name") for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + provided_params = list(req.arguments.keys()) if req.arguments else [] + + # 检查参数名是否匹配 + if set(expected_params) == set(provided_params): + # 参数名正确但值不匹配 - 不泄漏正确的值 + error_msg = f"Parameter names are correct, but the parameter values are incorrect. Please try using different parameter values." + else: + error_msg = f"Parameter names do not match. Expected parameter names: {expected_params}, you provided: {provided_params}." + + return { + "ok": False, + "error": error_msg + } + + logger.info(f"✓ Item inputs match golden - node: {req.node_id}, activating item") + + # 标记该 Item 已被正确使用 + item_node.if_success = True + + # 将 golden_output_values 追加到 actual_outputs_history + if item_node.golden_output_values: + item_node.actual_outputs_history.append(dict(item_node.golden_output_values)) + + # 触发 ITEM 类型边的掉落 + newly_revealed = [] + for edge in scenario.edges: + if edge.source_id == item_node.id and edge.connection_type == InterfaceType.ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from use_item on {req.node_id})") + + # 检查是否为 Win Node + win_node_id = scenario.win_node_id + is_win_node = (req.node_id == win_node_id) + + # 构建返回结果 + result = { + "ok": True, + "message": "Item used successfully.", + "content": item_node.golden_output_values if item_node.golden_output_values else None + } + + # 获取 narrative(如果存在) + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + narrative = raw_nodes_data[req.node_id].get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 如果是 Win Node,只记录日志 + if is_win_node: + logger.info(f"Win node (Item) unlocked via use_item - case: {case_id}, node: {req.node_id}") + + return result + + +class SubmitAnswerRequest(BaseModel): + answer: str = Field(..., description="The victory string to submit") + +@app.post("/env/{case_id}/submit_answer") +def submit_answer(case_id: str, req: SubmitAnswerRequest): + """ + 提交答案接口 + 被测模型在获得胜利字符串提示后,需要调用此接口提交答案 + """ + logger.info(f"Submit answer request - case_id: {case_id}, answer: {req.answer}") + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + + # 获取 win_node 的 golden_output_values + if not scenario.win_node_id: + logger.error(f"No win node defined for case: {case_id}") + return { + "ok": False, + "error": "This case has no victory node defined" + } + + win_node = scenario.nodes.get(scenario.win_node_id) + if not win_node: + logger.error(f"Win node not found: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node does not exist" + } + + # 获取正确的胜利字符串(取第一个 golden_output_value) + if win_node.golden_output_values: + correct_answer = list(win_node.golden_output_values.values())[0] + else: + logger.error(f"Win node has no golden_output_values: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node has no correct answer" + } + + # 验证提交的答案 + if req.answer == correct_answer: + logger.info(f"🎉 CORRECT ANSWER SUBMITTED - case: {case_id}, answer: {req.answer}") + return { + "ok": True, + "is_win": True, + "victory_message": f"🎉 Congratulations on successfully escaping the room! Your answer is correct: {req.answer}" + } + else: + logger.info(f"❌ INCORRECT ANSWER SUBMITTED - case: {case_id}, submitted: {req.answer}, correct: {correct_answer}") + return { + "ok": True, + "is_win": False, + "error": f"The submitted answer is incorrect. You submitted: {req.answer}" + } + +if __name__ == "__main__": + + uvicorn.run(app, host="0.0.0.0", port=8000) \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-534660f4/environment/puzzle/upstream/simulator.py b/tasks/agentescape-25-skeleton-534660f4/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-25-skeleton-534660f4/environment/puzzle/upstream/simulator.py @@ -0,0 +1,2911 @@ +import hashlib +import hmac +import base64 +import binascii +import zlib +import json +import uuid +import math +import re +from typing import Dict, Any, List + +class ToolSimulator: + def __init__(self): + """工具模拟器 + + 文件处理工具(zip_unzip, zip_unzip_file, zip_unzip_item, json_get, csv_query, + regex_search, graph_shortest_path)不需要真实文件系统。 + 这些工具只验证输入参数,然后返回预先初始化好的 golden_outputs。 + """ + self.tool_map = { + # 数论 + "calc_bigmul": self.calc_bigmul, + "calc_modexp": self.calc_modexp, + "calc_modexp_int": self.calc_modexp_int, + "calc_gcd": self.calc_gcd, + "calc_gcd_int": self.calc_gcd_int, + "calc_inv_mod": self.calc_inv_mod, + "calc_inv_mod_int": self.calc_inv_mod_int, + + # 哈希 + "hash_sha256": self.hash_sha256, + "hash_md5": self.hash_md5, + "hmac_sha256": self.hmac_sha256, + + # 编码 + "base64_decode": self.base64_decode, + "base64_encode": self.base64_encode, + "hex_decode": self.hex_decode, + "hex_encode": self.hex_encode, + "zlib_inflate": self.zlib_inflate, + "zlib_deflate": self.zlib_deflate, + + # 文件 + "zip_unzip": self.zip_unzip, + "zip_unzip_file": self.zip_unzip_file, + "zip_unzip_item": self.zip_unzip_item, + "regex_search": self.regex_search, + "json_get": self.json_get, + "csv_query": self.csv_query, + "code_py_exec": self.code_py_exec, + + # 图 + "graph_shortest_path": self.graph_shortest_path, + + # 加解密 (简化模拟) + "crypto_aes_cbc_decrypt": self.crypto_aes_cbc_decrypt, + "crypto_rsa_decrypt_hex": self.crypto_rsa_decrypt_hex, + + # 其他 + "num_base_convert": self.num_base_convert, + "time_convert": self.time_convert, + "checksum_crc32": self.checksum_crc32, + "geo_haversine": self.geo_haversine, + "otp_totp_generate": self.otp_totp_generate, + "unicode_norm": self.unicode_norm, + "text_bidi_sanitize": self.text_bidi_sanitize, + "text_xor_hex": self.text_xor_hex, + "text_rotN": self.text_rotN, + "luhn_check": self.luhn_check, + "iban_validate": self.iban_validate, + + # 物理 + "matter_synthesizer": self.matter_synthesizer, + + # 终端机 + "terminal_1": self.terminal_1, + "terminal_2": self.terminal_2, + "Logic Terminal": self.logic_terminal, + "Math Terminal": self.math_terminal, + "Encryption Terminal": self.crypt_terminal, + "Sequence Terminal": self.sequence_terminal + } + + def execute(self, tool_name: str, inputs: Dict[str, Any]) -> Dict[str, Any]: + if tool_name not in self.tool_map: + # Fallback for unknown tools: return dummy outputs based on expected output types + # This should ideally not happen if all tools are implemented + return {} + + try: + return self.tool_map[tool_name](inputs) + except Exception as e: + print(f"Error executing {tool_name}: {e}") + # Return empty or error indication? For generation, we might want to fail hard or return dummy. + # For now, return dummy to keep flow going, but log error. + return {} + + # --- Implementations --- + + def calc_bigmul(self, inputs): + # Check if required parameters are present + if "a" not in inputs or "b" not in inputs: + raise ValueError("Missing required parameters 'a' and/or 'b'") + + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + return {"product": str(a * b)} + except (ValueError, TypeError) as e: + raise ValueError(f"Failed to convert parameters to integers: {str(e)}") + + def calc_modexp(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + try: + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if isinstance(base, str): + base = int(base) + elif not isinstance(base, int): + raise ValueError("Parameter 'base' must be a string or integer") + + if isinstance(exp, str): + exp = int(exp) + elif not isinstance(exp, int): + raise ValueError("Parameter 'exp' must be a string or integer") + + if isinstance(mod, str): + mod = int(mod) + elif not isinstance(mod, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": str(pow(base, exp, mod))} + + def calc_modexp_int(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["base"], int): + raise ValueError("Parameter 'base' must be an integer") + if not isinstance(inputs["exp"], int): + raise ValueError("Parameter 'exp' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": pow(base, exp, mod)} + + def calc_gcd(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + # 计算 GCD 并返回字符串格式(符合 Big_Int 输出类型) + result = math.gcd(a, b) + return {"gcd": str(result)} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def calc_gcd_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["b"], int): + raise ValueError("Parameter 'b' must be an integer") + + # 获取参数 + a = inputs["a"] + b = inputs["b"] + + return {"gcd": math.gcd(a, b)} + + def calc_inv_mod(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + m = inputs["mod"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(m, str): + m = int(m) + elif not isinstance(m, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": str(pow(a, -1, m))} + except ValueError as e: + # 模逆不存在时,返回一个特殊值(用于数据传递) + # 在 DAG 生成阶段,这允许数据流继续 + return {"inv": str(a)} + + def calc_inv_mod_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + a = inputs["a"] + m = inputs["mod"] + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": pow(a, -1, m)} + except ValueError as e: + raise ValueError(f"Modular inverse does not exist: {str(e)}") + + def hash_sha256(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.sha256(text.encode()).hexdigest()} + + def hash_md5(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.md5(text.encode()).hexdigest()} + + def hmac_sha256(self, inputs): + # 参数检查 + if "hex_key" not in inputs: + raise ValueError("Missing required parameter: hex_key") + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["hex_key"], str): + raise ValueError("Parameter 'hex_key' must be a string") + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + try: + key = bytes.fromhex(inputs["hex_key"]) + text = inputs["text"].encode() + return {"hex": hmac.new(key, text, hashlib.sha256).hexdigest()} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def base64_decode(self, inputs): + # 参数检查 + if "data" not in inputs: + raise ValueError("Missing required parameter: data") + + # 类型检查 + if not isinstance(inputs["data"], str): + raise ValueError("Parameter 'data' must be a string") + + data = inputs["data"] + try: + return {"bytes_hex": binascii.hexlify(base64.b64decode(data)).decode()} + except Exception as e: + raise ValueError(f"Base64 decode error: {str(e)}") + + def base64_encode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"b64": base64.b64encode(bytes.fromhex(hex_data)).decode()} + except Exception as e: + raise ValueError(f"Base64 encode error: {str(e)}") + + def hex_decode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"text": bytes.fromhex(hex_data).decode('utf-8', errors='ignore')} + except Exception as e: + raise ValueError(f"Hex decode error: {str(e)}") + + def hex_encode(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + try: + return {"hex": text.encode().hex()} + except Exception as e: + raise ValueError(f"Hex encode error: {str(e)}") + + + # 到此处实现已经更新 + + def zlib_inflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("Parameter 'hex' must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("Missing required parameter: hex") + + try: + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空字符串 + if not hex_data: + raise ValueError("Empty hex string provided") + + # 检查十六进制字符串的有效性 + if len(hex_data) % 2 != 0: + raise ValueError("Hex string must have even length") + + # 检查是否只包含有效的十六进制字符 + if not all(c in '0123456789abcdefABCDEF' for c in hex_data): + raise ValueError("Invalid hex string provided") + + # 尝试解压缩 + return {"text": zlib.decompress(bytes.fromhex(hex_data)).decode('utf-8')} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hex string provided") from e + raise ValueError(f"Invalid zlib data: {e}") from e + except Exception as e: + raise RuntimeError(f"Failed to inflate data: {e}") from e + + def zlib_deflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("Parameter 'text' must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("Missing required parameter: text") + + try: + # 压缩文本 + return {"hex": zlib.compress(text.encode('utf-8')).hex()} + except Exception as e: + raise RuntimeError(f"Failed to deflate data: {e}") from e + + # --- File Operations --- + + def zip_unzip(self, inputs): + """ZIP 解压工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"files": golden_outputs.get("files", "")} + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return {"files": golden_outputs.get("files", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "files" in golden_outputs: + # 验证必需参数 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 检查类型 + if has_zip_id and not isinstance(zip_id, str): + return {"error": "Parameter 'zip_id' must be a string type"} + if has_password and not isinstance(password, str): + return {"error": "Parameter 'password' must be a string type"} + + # 验证输入是否与预期匹配 + if golden_inputs: + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return {"files": golden_outputs["files"]} + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + # 没有golden_inputs但有golden_outputs,直接返回输出 + return {"files": golden_outputs["files"]} + + # 如果没有预期输出,返回空结果 + return {"files": ""} + + def regex_search(self, inputs): + """正则搜索工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"matches": golden_outputs.get("matches", "[]")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "matches" in golden_outputs: + # 提取实际参数 + pattern = inputs.get("pattern") + file_id = inputs.get("file_id") + text = inputs.get("text") + + # 1. 检查必需参数 + if pattern is None: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["pattern"], + "message": "Missing required parameter 'pattern'" + } + } + + # 类型检查 + if not isinstance(pattern, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "pattern", + "message": "Parameter 'pattern' must be a string type" + } + } + if file_id is not None and not isinstance(file_id, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if text is not None and not isinstance(text, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "text", + "message": "Parameter 'text' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合 + provided_params = {} + if pattern is not None: + provided_params["pattern"] = pattern + if file_id is not None: + provided_params["file_id"] = file_id + if text is not None: + provided_params["text"] = text + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数(关键改进) + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_pattern = golden_inputs.get("pattern") + expected_file_id = golden_inputs.get("file_id") + expected_text = golden_inputs.get("text") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_pattern is not None: + if str(pattern) != str(expected_pattern): + incorrect_params.append("pattern") + else: + correct_params.append("pattern") + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_text is not None: + if str(text) != str(expected_text): + incorrect_params.append("text") + else: + correct_params.append("text") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "matches": "[]", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "matches": golden_outputs["matches"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空列表 + return {"matches": "[]"} + + def json_get(self, inputs): + """JSON 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"values": golden_outputs.get("values", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "values" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + jsonpath = inputs.get("jsonpath", "") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if jsonpath is not None and not isinstance(jsonpath, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "jsonpath", + "message": "Parameter 'jsonpath' must be a string type" + } + } + + # 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:jsonpath有默认值"") + provided_params = {} + if file_id is not None: + provided_params["file_id"] = file_id + if jsonpath != "": + provided_params["jsonpath"] = jsonpath + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_jsonpath = golden_inputs.get("jsonpath") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_jsonpath is not None: + if str(jsonpath) != str(expected_jsonpath): + incorrect_params.append("jsonpath") + else: + correct_params.append("jsonpath") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "values": "", + "_validation": validation_info + } + + # 所有验证通过,返回正确输出 + return { + "values": golden_outputs["values"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"values": ""} + + def csv_query(self, inputs): + """CSV 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"rows": golden_outputs.get("rows", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "rows" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + select_columns = inputs.get("select", "") + where_clause = inputs.get("where", "") + + # 1. 检查必需参数 + if file_id is None: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["file_id"], + "message": "Missing required parameter 'file_id'" + } + } + + # 类型检查 + if not isinstance(file_id, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if not isinstance(select_columns, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "select", + "message": "Parameter 'select' must be a string type" + } + } + if not isinstance(where_clause, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "where", + "message": "Parameter 'where' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:select和where有默认值"") + provided_params = {"file_id": file_id} + if select_columns != "": + provided_params["select"] = select_columns + if where_clause != "": + provided_params["where"] = where_clause + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_select = golden_inputs.get("select") + expected_where = golden_inputs.get("where") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_select is not None: + if str(select_columns) != str(expected_select): + incorrect_params.append("select") + else: + correct_params.append("select") + + if expected_where is not None: + if str(where_clause) != str(expected_where): + incorrect_params.append("where") + else: + correct_params.append("where") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "rows": "", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "rows": golden_outputs["rows"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"rows": ""} + + def graph_shortest_path(self, inputs): + """图最短路径工具 + + 如果有 _golden_outputs 或 _init_outputs,验证输入并返回预设输出。 + 否则执行真实的 Dijkstra 算法。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 检查是否在预设模式中(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + if golden_outputs and "path" in golden_outputs: + # 评测阶段但没有 golden_inputs,直接返回 outputs + if not golden_inputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 评测模式:验证输入参数是否匹配 golden 值 + src = inputs.get("src") + dst = inputs.get("dst") + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + + has_src = src is not None and src != "" + has_dst = dst is not None and dst != "" + + # 验证必需参数 + if not has_src or not has_dst: + missing = [] + if not has_src: + missing.append("src") + if not has_dst: + missing.append("dst") + return {"error": "Missing required parameters: " + ", ".join(missing)} + + # 类型检查 + if not isinstance(src, str): + return {"error": "Parameter 'src' must be a string"} + if not isinstance(dst, str): + return {"error": "Parameter 'dst' must be a string"} + + # 验证输入是否匹配期望值 + if golden_inputs: + expected_src = golden_inputs.get("src") + expected_dst = golden_inputs.get("dst") + expected_file_id = golden_inputs.get("file_id") + expected_graph_data = golden_inputs.get("graph_data") + + # 收集验证结果 + incorrect_params = [] + correct_params = [] + + # 检查必需参数是否匹配 + if expected_src is not None: + if str(src) != str(expected_src): + incorrect_params.append("src") + else: + correct_params.append("src") + + if expected_dst is not None: + if str(dst) != str(expected_dst): + incorrect_params.append("dst") + else: + correct_params.append("dst") + + # 检查可选参数(如果在 expected_inputs 中定义了) + if expected_file_id is not None: + if file_id != expected_file_id: + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_graph_data is not None: + if graph_data != expected_graph_data: + incorrect_params.append("graph_data") + else: + correct_params.append("graph_data") + + # 如果有参数不正确,返回详细的反馈 + if incorrect_params: + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 验证通过,返回预设的输出 + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 获取参数(真实执行路径) + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + # Support both src/dst (interface definition) and start/end (original implementation) + start = inputs.get("src") + end = inputs.get("dst") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + raise TypeError("file_id must be a string") + + if graph_data is not None and not isinstance(graph_data, str): + raise TypeError("graph_data must be a string") + + if start is not None and not isinstance(start, str): + raise TypeError("src/start must be a string") + + if end is not None and not isinstance(end, str): + raise TypeError("dst/end must be a string") + + # 检查必需参数 + if file_id is None and graph_data is None: + raise ValueError("Either file_id or graph_data must be provided") + + if start is None: + raise ValueError("src/start parameter is required") + + if end is None: + raise ValueError("dst/end parameter is required") + + # Get graph content + content = None + if file_id is not None: + # 尝试从 VFS 获取(如果存在) + if hasattr(self, 'vfs') and file_id in self.vfs: + content = self.vfs[file_id] + else: + # VFS 不存在或文件不在 VFS 中 + # 返回一个默认的空图结果,或者抛出错误提示需要 init_outputs + raise ValueError( + f"File '{file_id}' not found. For tools that require files, " + f"please provide init_outputs in the initial_values." + ) + elif graph_data is not None: + content = graph_data + + if content is None: + content = "{}" + + try: + # Parse graph data + graph = json.loads(content) + + # 类型检查 + if not isinstance(graph, dict): + raise TypeError("Graph data must be a dictionary") + + # If graph is not in the expected format, try to extract adjacency list + if "nodes" in graph and "edges" in graph: + # 验证nodes和edges的类型 + if not isinstance(graph["nodes"], list): + raise TypeError("Nodes must be a list") + + if not isinstance(graph["edges"], list): + raise TypeError("Edges must be a list") + + # Convert from nodes/edges format to adjacency list + adjacency_list = {} + for node in graph["nodes"]: + # 验证node类型 + if not isinstance(node, dict): + raise TypeError("Each node must be a dictionary") + + # Use node ID as key, not the entire node dictionary + node_id = node.get("id", "") + if node_id: + adjacency_list[node_id] = {} + + for edge in graph["edges"]: + # 验证edge类型 + if not isinstance(edge, dict): + raise TypeError("Each edge must be a dictionary") + + u = edge["from"] + v = edge["to"] + weight = edge.get("weight", 1) # Default to unweighted + + # 类型检查 + if not isinstance(u, str): + raise TypeError("Edge 'from' must be a string") + + if not isinstance(v, str): + raise TypeError("Edge 'to' must be a string") + + if not isinstance(weight, (int, float)): + raise TypeError("Edge weight must be a number") + + if u not in adjacency_list: + adjacency_list[u] = {} + if v not in adjacency_list: + adjacency_list[v] = {} + + adjacency_list[u][v] = weight + # If undirected, add reverse edge + if not edge.get("directed", False): + adjacency_list[v][u] = weight + elif isinstance(graph, dict): + # Already in adjacency list format + adjacency_list = graph + + # 验证邻接表结构 + for node, neighbors in adjacency_list.items(): + if not isinstance(neighbors, dict): + raise TypeError("Adjacency list must be a dictionary of dictionaries") + + for neighbor, weight in neighbors.items(): + if not isinstance(weight, (int, float)): + raise TypeError("Edge weights must be numbers") + else: + raise TypeError("Graph data must be a dictionary") + + # 检查起点和终点是否为空 + if not start: + raise ValueError("Start node cannot be empty") + + if not end: + raise ValueError("End node cannot be empty") + + # 检查起点和终点是否在图中 + if start not in adjacency_list: + raise ValueError(f"Start node '{start}' not found in graph") + + if end not in adjacency_list: + raise ValueError(f"End node '{end}' not found in graph") + + # Dijkstra's algorithm implementation + import heapq + + # Initialize distances and previous nodes + distances = {node: float('infinity') for node in adjacency_list} + previous = {node: None for node in adjacency_list} + distances[start] = 0 + + # Priority queue + pq = [(0, start)] + heapq.heapify(pq) + + while pq: + current_dist, current_node = heapq.heappop(pq) + + # If we've reached the end node, we can break early + if current_node == end: + break + + # Nodes can be added multiple times to the priority queue, but we only process them once + if current_dist > distances[current_node]: + continue + + # Explore neighbors + for neighbor, weight in adjacency_list[current_node].items(): + distance = current_dist + weight + + # If a shorter path is found + if distance < distances[neighbor]: + distances[neighbor] = distance + previous[neighbor] = current_node + heapq.heappush(pq, (distance, neighbor)) + + # Reconstruct the shortest path + path = [] + current = end + while current is not None: + path.append(current) + current = previous[current] + path.reverse() # Reverse to get from start to end + + # Check if path exists + if not path or path[0] != start: + return {"path": "[]", "cost": 0} + + return { + "path": json.dumps(path), + "cost": distances[end] + } + except json.JSONDecodeError as e: + raise ValueError(f"Invalid JSON in graph data: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in graph_shortest_path: {str(e)}") + + # --- Crypto (Simplified) --- + def crypto_aes_cbc_decrypt(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 (使用模板中定义的参数名) + hex_cipher = inputs.get("hex_cipher") + hex_key = inputs.get("hex_key") + hex_iv = inputs.get("hex_iv") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + + if hex_key is not None and not isinstance(hex_key, str): + raise TypeError("hex_key must be a string") + + if hex_iv is not None and not isinstance(hex_iv, str): + raise TypeError("hex_iv must be a string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + + if hex_key is None: + raise ValueError("hex_key parameter is required") + + if hex_iv is None: + raise ValueError("hex_iv parameter is required") + + from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes + from cryptography.hazmat.backends import default_backend + from cryptography.hazmat.primitives import padding + + try: + # Convert hex strings to bytes + ciphertext = bytes.fromhex(hex_cipher) + key = bytes.fromhex(hex_key) + iv = bytes.fromhex(hex_iv) + + # Validate key length (AES-128, AES-192, AES-256) + if len(key) not in [16, 24, 32]: + raise ValueError("Invalid key length. Must be 16, 24, or 32 bytes.") + + if len(iv) != 16: + raise ValueError("Invalid IV length. Must be 16 bytes.") + + # Create cipher object + cipher = Cipher( + algorithms.AES(key), + modes.CBC(iv), + backend=default_backend() + ) + + decryptor = cipher.decryptor() + + # Decrypt the ciphertext + padded_plaintext = decryptor.update(ciphertext) + decryptor.finalize() + + # Remove PKCS7 padding + unpadder = padding.PKCS7(128).unpadder() + plaintext = unpadder.update(padded_plaintext) + unpadder.finalize() + + # Return decrypted text + return {"text": plaintext.decode('utf-8', errors='ignore')} + except ValueError as e: + if "non-hexadecimal number found in fromhex()" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher, hex_key, or hex_iv") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in crypto_aes_cbc_decrypt: {str(e)}") + + def crypto_rsa_decrypt_hex(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_cipher = inputs.get("hex_cipher") + n = inputs.get("n") + d = inputs.get("d") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + if n is not None and not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + if d is not None and not isinstance(d, (int, str)): + raise TypeError("d must be an integer or string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + if n is None: + raise ValueError("n parameter is required") + if d is None: + raise ValueError("d parameter is required") + + try: + # Convert parameters to appropriate types + cipher_int = int(hex_cipher, 16) + n_int = int(n) if isinstance(n, str) else n + d_int = int(d) if isinstance(d, str) else d + + # RSA decryption: plaintext = ciphertext^d mod n + plaintext_int = pow(cipher_int, d_int, n_int) + + # Convert result to hex and then to text + plaintext_hex = hex(plaintext_int)[2:] + + # Pad with leading zero if odd length + if len(plaintext_hex) % 2 != 0: + plaintext_hex = '0' + plaintext_hex + + # Convert hex to bytes and then to text + try: + plaintext_bytes = bytes.fromhex(plaintext_hex) + plaintext_text = plaintext_bytes.decode('utf-8', errors='ignore') + except: + # If decoding fails, return hex representation + plaintext_text = plaintext_hex + + return {"text": plaintext_text} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in crypto_rsa_decrypt_hex: {str(e)}") + + # --- Others --- + def num_base_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + s = inputs.get("s") + from_base = inputs.get("from_base") + to_base = inputs.get("to_base") + + # 类型检查 - 接受 str 或 int + if s is not None and not isinstance(s, (str, int)): + raise TypeError("s must be a string or integer") + + if from_base is not None and not isinstance(from_base, (int, str)): + raise TypeError("from_base must be an integer") + + if to_base is not None and not isinstance(to_base, (int, str)): + raise TypeError("to_base must be an integer") + + # 检查必需参数 + if s is None: + raise ValueError("s parameter is required") + + if from_base is None: + raise ValueError("from_base parameter is required") + + if to_base is None: + raise ValueError("to_base parameter is required") + + try: + # Convert to int if needed + from_base = int(from_base) if isinstance(from_base, str) else from_base + to_base = int(to_base) if isinstance(to_base, str) else to_base + s_str = str(s) + + # 验证基数范围 + if from_base < 2 or from_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + if to_base < 2 or to_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + # Convert from source base to decimal + val = int(s_str, from_base) + + # Convert from decimal to target base + if to_base == 10: + result = str(val) + elif to_base == 16: + result = hex(val)[2:] + elif to_base == 8: + result = oct(val)[2:] + elif to_base == 2: + result = bin(val)[2:] + else: + # Generic base conversion for other bases + if val == 0: + result = "0" + else: + digits = "0123456789abcdefghijklmnopqrstuvwxyz" + result = "" + n = abs(val) + while n: + result = digits[n % to_base] + result + n //= to_base + if val < 0: + result = "-" + result + + return {"str": result} + except ValueError as e: + raise ValueError(f"Invalid number format: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in num_base_convert: {str(e)}") + + def time_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iso = inputs.get("iso") + timestamp = inputs.get("timestamp") + datetime_str = inputs.get("datetime") + from_tz = inputs.get("from_tz") + to_tz = inputs.get("to_tz") + format_str = inputs.get("format") + + # 类型检查 + if iso is not None and not isinstance(iso, str): + raise TypeError("iso must be a string") + + if timestamp is not None and not isinstance(timestamp, (str, int, float)): + raise TypeError("timestamp must be a string, integer, or float") + + if datetime_str is not None and not isinstance(datetime_str, str): + raise TypeError("datetime must be a string") + + if from_tz is not None and not isinstance(from_tz, str): + raise TypeError("from_tz must be a string") + + if to_tz is not None and not isinstance(to_tz, str): + raise TypeError("to_tz must be a string") + + if format_str is not None and not isinstance(format_str, str): + raise TypeError("format must be a string") + + # 设置默认值 + if from_tz is None: + from_tz = "UTC" + + if to_tz is None: + to_tz = "UTC" + + import datetime + import pytz + + # 验证时区参数 + try: + if from_tz: + pytz.timezone(from_tz) + if to_tz: + pytz.timezone(to_tz) + except Exception: + raise ValueError("Invalid timezone provided") + + try: + # Parse input time + dt = None + + if iso is not None: + # Parse ISO 8601 format + dt = datetime.datetime.fromisoformat(iso.replace('Z', '+00:00')) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=pytz.UTC) + elif timestamp is not None: + # Parse Unix timestamp + timestamp = float(timestamp) + dt = datetime.datetime.fromtimestamp(timestamp, pytz.UTC) + elif datetime_str is not None: + # Parse datetime string + # Try common formats + formats_to_try = [ + "%Y-%m-%d %H:%M:%S", + "%Y-%m-%d %H:%M:%S.%f", + "%Y-%m-%d", + "%m/%d/%Y %H:%M:%S", + "%m/%d/%Y" + ] + + parse_success = False + for fmt in formats_to_try: + try: + dt = datetime.datetime.strptime(datetime_str, fmt) + dt = pytz.timezone(from_tz).localize(dt) + parse_success = True + break + except ValueError: + continue + + if not parse_success: + raise ValueError("Unable to parse datetime string with common formats") + else: + # 如果没有提供任何时间参数,则使用当前时间 + dt = datetime.datetime.now(pytz.UTC) + except ValueError as e: + raise ValueError(f"Error parsing time input: {str(e)}") + except Exception as e: + raise RuntimeError(f"Unexpected error parsing time input: {str(e)}") + + try: + # Convert timezone + if from_tz != to_tz: + dt = dt.astimezone(pytz.timezone(to_tz)) + + # Format outputs + result = { + "iso": dt.isoformat(), + "timestamp": str(dt.timestamp()), + "datetime": dt.strftime("%Y-%m-%d %H:%M:%S"), + "date": dt.strftime("%Y-%m-%d"), + "time": dt.strftime("%H:%M:%S"), + "timezone": to_tz + } + + # Add custom format if requested + if format_str: + try: + result["formatted"] = dt.strftime(format_str) + except ValueError as e: + raise ValueError(f"Invalid format string: {str(e)}") + + return result + except Exception as e: + raise RuntimeError(f"Error in time_convert: {str(e)}") + + def checksum_crc32(self, inputs): + import zlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("hex must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("hex parameter is required") + + try: + # 验证十六进制字符串 + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空 + if not hex_data: + raise ValueError("hex data cannot be empty") + + # 检查是否为有效的十六进制字符串 + if not all(c in "0123456789abcdefABCDEF" for c in hex_data): + raise ValueError("hex must be a valid hexadecimal string") + + # 检查长度是否为偶数 + if len(hex_data) % 2 != 0: + raise ValueError("hex must have even number of characters") + + val = zlib.crc32(bytes.fromhex(hex_data)) + # 确保 hex 输出是 8 位,前导补 0 + return {"hex": f"{val:08x}", "int": val} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in checksum_crc32: {str(e)}") + + def geo_haversine(self, inputs): + import math + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + lat1 = inputs.get("lat1") + lon1 = inputs.get("lon1") + lat2 = inputs.get("lat2") + lon2 = inputs.get("lon2") + + # 类型检查 + if lat1 is not None and not isinstance(lat1, (int, float, str)): + raise TypeError("lat1 must be a number or string") + if lon1 is not None and not isinstance(lon1, (int, float, str)): + raise TypeError("lon1 must be a number or string") + if lat2 is not None and not isinstance(lat2, (int, float, str)): + raise TypeError("lat2 must be a number or string") + if lon2 is not None and not isinstance(lon2, (int, float, str)): + raise TypeError("lon2 must be a number or string") + + # 检查必需参数 + if lat1 is None: + raise ValueError("lat1 parameter is required") + if lon1 is None: + raise ValueError("lon1 parameter is required") + if lat2 is None: + raise ValueError("lat2 parameter is required") + if lon2 is None: + raise ValueError("lon2 parameter is required") + + try: + # 转换为浮点数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(lat1, str): + lat1 = float(lat1) + elif not isinstance(lat1, (int, float)): + raise TypeError("lat1 must be a number or string") + else: + lat1 = float(lat1) + + if isinstance(lon1, str): + lon1 = float(lon1) + elif not isinstance(lon1, (int, float)): + raise TypeError("lon1 must be a number or string") + else: + lon1 = float(lon1) + + if isinstance(lat2, str): + lat2 = float(lat2) + elif not isinstance(lat2, (int, float)): + raise TypeError("lat2 must be a number or string") + else: + lat2 = float(lat2) + + if isinstance(lon2, str): + lon2 = float(lon2) + elif not isinstance(lon2, (int, float)): + raise TypeError("lon2 must be a number or string") + else: + lon2 = float(lon2) + + # Validate coordinates (approximate range check) + if not (-90 <= lat1 <= 90): + raise ValueError("lat1 must be between -90 and 90") + if not (-90 <= lat2 <= 90): + raise ValueError("lat2 must be between -90 and 90") + if not (-180 <= lon1 <= 180): + raise ValueError("lon1 must be between -180 and 180") + if not (-180 <= lon2 <= 180): + raise ValueError("lon2 must be between -180 and 180") + + # Earth radius in meters + R = 6371000 # Approximate radius of Earth + + # Convert degrees to radians + lat1_rad = math.radians(lat1) + lon1_rad = math.radians(lon1) + lat2_rad = math.radians(lat2) + lon2_rad = math.radians(lon2) + + # Calculate differences + delta_lat = lat2_rad - lat1_rad + delta_lon = lon2_rad - lon1_rad + + # Haversine formula + a = math.sin(delta_lat / 2) ** 2 + \ + math.cos(lat1_rad) * math.cos(lat2_rad) * \ + math.sin(delta_lon / 2) ** 2 + c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) + distance_m = R * c + + # Return distance in meters + return {"meters": round(distance_m, 2)} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in geo_haversine: {str(e)}") + + def otp_totp_generate(self, inputs): + import hmac + import hashlib + import base64 + import time + import struct + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + base32_secret = inputs.get("base32_secret") + step = inputs.get("step", 30) # Default to 30 seconds + digits = inputs.get("digits", 6) # Default to 6 digits + timestamp_iso = inputs.get("timestamp_iso", "") + algo = inputs.get("algo", "sha1") # Default to sha1 as current implementation only supports this + + # 类型检查 + if base32_secret is not None and not isinstance(base32_secret, str): + raise TypeError("base32_secret must be a string") + if not isinstance(step, (int, str)): + raise TypeError("step must be an integer or string") + if not isinstance(digits, (int, str)): + raise TypeError("digits must be an integer or string") + if not isinstance(timestamp_iso, str): + raise TypeError("timestamp_iso must be a string") + if not isinstance(algo, str): + raise TypeError("algo must be a string") + + # 检查必需参数 + if base32_secret is None: + raise ValueError("base32_secret parameter is required") + + try: + # Convert step and digits to appropriate types + step = int(step) + digits = int(digits) + if digits < 6 or digits > 8: + raise ValueError("Digits must be between 6 and 8") + + # Convert timestamp_iso to integer timestamp + if timestamp_iso: + import datetime + dt = datetime.datetime.fromisoformat(timestamp_iso.replace('Z', '+00:00')) + timestamp = int(dt.timestamp()) + else: + timestamp = int(time.time()) + + # Calculate counter value (T = floor(timestamp / step)) + counter = timestamp // step + + # Decode the base32 secret + # Add padding if necessary (base64 requires padding to be multiple of 8) + base32_secret = base32_secret.upper().replace(' ', '') + if len(base32_secret) % 8 != 0: + base32_secret += '=' * (8 - (len(base32_secret) % 8)) + key = base64.b32decode(base32_secret, casefold=True) + + # Calculate HMAC-SHA1 + counter_bytes = struct.pack('>Q', counter) # Big-endian 8-byte integer + hmac_hash = hmac.new(key, counter_bytes, hashlib.sha1).digest() + + # Dynamic truncation + offset = hmac_hash[-1] & 0xF + code = struct.unpack('>I', hmac_hash[offset:offset+4])[0] & 0x7FFFFFFF + + # Generate the OTP + otp = str(code % (10 ** digits)).zfill(digits) + + # Calculate remaining time until next OTP change + remaining_time = step - (timestamp % step) + + return {"totp": otp, "remaining_time": remaining_time, "time_step": step} + except ValueError as e: + if "invalid literal for int()" in str(e): + raise ValueError("step and digits must be valid integers") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in otp_totp_generate: {str(e)}") + + def unicode_norm(self, inputs): + import unicodedata + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + form = inputs.get("form", "NFC") # Default to NFC + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if form is not None and not isinstance(form, str): + raise TypeError("form must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Normalize form (NFC, NFD, NFKC, NFKD) + form = form.upper().strip() + + if form not in ['NFC', 'NFD', 'NFKC', 'NFKD']: + raise ValueError(f"Invalid normalization form: {form}. Must be one of: NFC, NFD, NFKC, NFKD") + + # Apply Unicode normalization + normalized_text = unicodedata.normalize(form, text) + + return {"text": normalized_text} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in unicode_norm: {str(e)}") + + def text_bidi_sanitize(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Bidi control characters to remove + bidi_controls = [ + '\u200E', # LEFT-TO-RIGHT MARK + '\u200F', # RIGHT-TO-LEFT MARK + '\u202A', # LEFT-TO-RIGHT EMBEDDING + '\u202B', # RIGHT-TO-LEFT EMBEDDING + '\u202C', # POP DIRECTIONAL FORMATTING + '\u202D', # LEFT-TO-RIGHT OVERRIDE + '\u202E', # RIGHT-TO-LEFT OVERRIDE + '\u2066', # LEFT-TO-RIGHT ISOLATE + '\u2067', # RIGHT-TO-LEFT ISOLATE + '\u2068', # FIRST STRONG ISOLATE + '\u2069', # POP DIRECTIONAL ISOLATE + ] + + # Remove all Bidi control characters + sanitized_text = text + for control_char in bidi_controls: + sanitized_text = sanitized_text.replace(control_char, '') + + return {"text": sanitized_text} + except Exception as e: + raise RuntimeError(f"Error in text_bidi_sanitize: {str(e)}") + + def text_xor_hex(self, inputs): + import binascii + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_a = inputs.get("hex_a") + hex_b = inputs.get("hex_b") + + # 类型检查 + if hex_a is not None and not isinstance(hex_a, str): + raise TypeError("hex_a must be a string") + if hex_b is not None and not isinstance(hex_b, str): + raise TypeError("hex_b must be a string") + + # 检查必需参数 + if hex_a is None: + raise ValueError("hex_a parameter is required") + if hex_b is None: + raise ValueError("hex_b parameter is required") + + try: + # Remove any whitespace + hex_a = hex_a.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + hex_b = hex_b.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + + # Validate hex strings + if not (all(c in "0123456789abcdefABCDEF" for c in hex_a) and len(hex_a) % 2 == 0): + raise ValueError("hex_a must be a valid hexadecimal string with even length") + if not (all(c in "0123456789abcdefABCDEF" for c in hex_b) and len(hex_b) % 2 == 0): + raise ValueError("hex_b must be a valid hexadecimal string with even length") + + # Convert hex strings to bytes + bytes_a = binascii.unhexlify(hex_a) + bytes_b = binascii.unhexlify(hex_b) + + # Make the byte arrays the same length by padding the shorter one with zeros + max_len = max(len(bytes_a), len(bytes_b)) + bytes_a = bytes_a.ljust(max_len, b'\x00') + bytes_b = bytes_b.ljust(max_len, b'\x00') + + # Perform XOR operation + result_bytes = bytes(a ^ b for a, b in zip(bytes_a, bytes_b)) + + # Convert result back to hex + result_hex = binascii.hexlify(result_bytes).decode('utf-8') + + return {"hex": result_hex} + except ValueError as e: + if "Non-hexadecimal digit found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in text_xor_hex: {str(e)}") + + def text_rotN(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + n = inputs.get("n", 0) + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + n = int(n) + except ValueError: + raise ValueError("n must be a valid integer") + + result = [] + for char in text: + if char.isupper(): + # Rotate uppercase letters + result_char = chr((ord(char) - ord('A') + n) % 26 + ord('A')) + result.append(result_char) + elif char.islower(): + # Rotate lowercase letters + result_char = chr((ord(char) - ord('a') + n) % 26 + ord('a')) + result.append(result_char) + else: + # Keep non-alphabetic characters unchanged + result.append(char) + + return {"text": ''.join(result)} + + def luhn_check(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数(支持 card_number 和 number 两个参数名) + card_number = inputs.get("number") or inputs.get("card_number") + + # 类型检查 + if card_number is not None and not isinstance(card_number, str): + raise TypeError("number must be a string") + + # 检查必需参数 + if card_number is None: + raise ValueError("number parameter is required") + + try: + # 如果输入是JSON数组或其他非数字字符串,返回该字符串本身(用于数据传递) + # 这种情况发生在DAG设计中类型不匹配时 + if card_number.startswith('[') or card_number.startswith('{'): + # 输入是JSON,直接返回原值(用于传递) + return {"valid": card_number} + + # Remove whitespace from card number + card_number = card_number.replace(" ", "").replace("-", "") + + # Check if card number is all digits + if not card_number.isdigit() or len(card_number) < 13: + return {"valid": "false"} + + # Implement Luhn algorithm + total = 0 + reverse_digits = card_number[::-1] # Reverse the number for easier processing + + for i, digit in enumerate(reverse_digits): + num = int(digit) + if i % 2 == 1: # Every second digit starting from the right (which is first in reversed string) + num *= 2 + if num > 9: + num -= 9 # Equivalent to sum of digits for 2-digit numbers + total += num + + # Check if total is divisible by 10 + is_valid = total % 10 == 0 + return {"valid": "true" if is_valid else "false"} + except Exception as e: + raise RuntimeError(f"Error in luhn_check: {str(e)}") + + def iban_validate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iban = inputs.get("iban") + + # 类型检查 + if iban is not None and not isinstance(iban, str): + raise TypeError("iban must be a string") + + # 检查必需参数 + if iban is None: + raise ValueError("iban parameter is required") + + try: + # Remove whitespace from IBAN + iban = iban.replace(" ", "") + + # Basic length and format check + if not (len(iban) >= 15 and len(iban) <= 34): + return {"valid": "False"} + + if not (iban[:2].isalpha() and iban[2:].isdigit()): + return {"valid": "False"} + + # Move first four characters to the end + rearranged = iban[4:] + iban[:4] + + # Replace letters with numbers (A=10, B=11, ..., Z=35) + numeric_iban = '' + for char in rearranged: + if char.isdigit(): + numeric_iban += char + else: + numeric_iban += str(ord(char.upper()) - ord('A') + 10) + + # Perform modulo 97 check + # Use step-by-step approach for very large numbers + remainder = 0 + for char in numeric_iban: + remainder = (remainder * 10 + int(char)) % 97 + + is_valid = remainder == 1 + return {"valid": "True" if is_valid else "False"} + except Exception as e: + raise RuntimeError(f"Error in iban_validate: {str(e)}") + + def matter_synthesizer(self, inputs): + import hashlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + blueprint = inputs.get("blueprint") + + # 类型检查 + if blueprint is not None and not isinstance(blueprint, str): + raise TypeError("blueprint must be a string") + + try: + # Get blueprint parameter as defined in interface + if blueprint is None: + blueprint = "" + + # Generate a unique item ID based on the blueprint + # This ensures the same blueprint always produces the same item + blueprint_hash = hashlib.sha256(blueprint.encode()).hexdigest()[:16] + + # Create a synthesized item with a deterministic ID based on blueprint + synthesized_item = f"synthesized_item_{blueprint_hash}" + + return {"output_slot": synthesized_item} + except Exception as e: + raise RuntimeError(f"Error in matter_synthesizer: {str(e)}") + + # --- Terminal Implementations --- + def terminal_1(self, inputs): + """ + terminal_1: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 只返回 text_output + - 只输入正确的 slot_b → 只返回 hex_output + - 同时输入正确的 slot_a 和 slot_b → 返回 item_dispenser(物品掉落) + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + # 检查哪些输入被提供了 + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值是否正确(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + expected_a = golden_inputs["slot_a"] + a_valid = str(slot_a) == str(expected_a) + + if has_b and "slot_b" in golden_inputs: + expected_b = golden_inputs["slot_b"] + b_valid = str(slot_b) == str(expected_b) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 item_dispenser + if has_a and has_b: + if a_valid and b_valid: + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 text_output + if has_a and not has_b: + if a_valid: + if "text_output" in golden_outputs: + result["text_output"] = golden_outputs["text_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 hex_output + if has_b and not has_a: + if b_valid: + if "hex_output" in golden_outputs: + result["hex_output"] = golden_outputs["hex_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def terminal_2(self, inputs): + """ + terminal_2: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 text_result + - 同时输入正确的 num1 和 num2 → 返回 hex_result 和 math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + # 检查哪些输入被提供了 + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值是否正确(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + expected_num1 = golden_inputs["num1"] + num1_valid = str(num1) == str(expected_num1) + + if has_num2 and "num2" in golden_inputs: + expected_num2 = golden_inputs["num2"] + num2_valid = str(num2) == str(expected_num2) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 hex_result 和 math_token + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 text_result + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "text_result" in golden_outputs: + result["text_result"] = golden_outputs["text_result"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def logic_terminal(self, inputs): + """ + Logic Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 返回 screen(部分输出) + - 只输入正确的 slot_b → 返回 screen 和 secondary_output + - 同时输入正确的 slot_a 和 slot_b → 返回 screen, secondary_output, item_dispenser + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + a_valid = str(slot_a) == str(golden_inputs["slot_a"]) + + if has_b and "slot_b" in golden_inputs: + b_valid = str(slot_b) == str(golden_inputs["slot_b"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出(包括 item_dispenser) + if has_a and has_b: + if a_valid and b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 screen(部分输出) + if has_a and not has_b: + if a_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 screen 和 secondary_output + if has_b and not has_a: + if b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def math_terminal(self, inputs): + """ + Math Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 result_display + - 同时输入正确的 num1 和 num2 → 返回 result_display, hex_result, math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + num1_valid = str(num1) == str(golden_inputs["num1"]) + + if has_num2 and "num2" in golden_inputs: + num2_valid = str(num2) == str(golden_inputs["num2"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 result_display + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def crypt_terminal(self, inputs): + """ + Encryption Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 plaintext → 返回 status(部分输出) + - 同时输入正确的 plaintext 和 key → 返回 status, encrypted_hex, encryption_chip + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + plaintext = inputs.get("plaintext") + key = inputs.get("key") + + has_plaintext = plaintext is not None and plaintext != "" + has_key = key is not None and key != "" + + # 验证输入值(与 golden values 比较) + plaintext_valid = False + key_valid = False + + if has_plaintext and "plaintext" in golden_inputs: + plaintext_valid = str(plaintext) == str(golden_inputs["plaintext"]) + + if has_key and "key" in golden_inputs: + key_valid = str(key) == str(golden_inputs["key"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_plaintext and has_key: + if plaintext_valid and key_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + if "encrypted_hex" in golden_outputs: + result["encrypted_hex"] = golden_outputs["encrypted_hex"] + if "encryption_chip" in golden_outputs: + result["encryption_chip"] = golden_outputs["encryption_chip"] + return result + else: + incorrect_params = [] + correct_params = [] + if not plaintext_valid: + incorrect_params.append("plaintext") + else: + correct_params.append("plaintext") + if not key_valid: + incorrect_params.append("key") + else: + correct_params.append("key") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 plaintext 且正确 → 返回 status(部分输出) + if has_plaintext and not has_key: + if plaintext_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: plaintext"} + + # 只提供 key 但没有 plaintext + if has_key and not has_plaintext: + return {"error": "plaintext required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + def sequence_terminal(self, inputs): + """ + Sequence Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 sequence → 返回 verification(部分输出) + - 同时输入正确的 sequence 和 checksum → 返回 verification, auth_code, access_card + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + sequence = inputs.get("sequence") + checksum = inputs.get("checksum") + + has_sequence = sequence is not None and sequence != "" + has_checksum = checksum is not None and checksum != "" + + # 验证输入值(与 golden values 比较) + sequence_valid = False + checksum_valid = False + + if has_sequence and "sequence" in golden_inputs: + sequence_valid = str(sequence) == str(golden_inputs["sequence"]) + + if has_checksum and "checksum" in golden_inputs: + checksum_valid = str(checksum) == str(golden_inputs["checksum"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_sequence and has_checksum: + if sequence_valid and checksum_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + if "auth_code" in golden_outputs: + result["auth_code"] = golden_outputs["auth_code"] + if "access_card" in golden_outputs: + result["access_card"] = golden_outputs["access_card"] + return result + else: + incorrect_params = [] + correct_params = [] + if not sequence_valid: + incorrect_params.append("sequence") + else: + correct_params.append("sequence") + if not checksum_valid: + incorrect_params.append("checksum") + else: + correct_params.append("checksum") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 sequence 且正确 → 返回 verification(部分输出) + if has_sequence and not has_checksum: + if sequence_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: sequence"} + + # 只提供 checksum 但没有 sequence + if has_checksum and not has_sequence: + return {"error": "sequence required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + # --- Additional File Tools --- + + def zip_unzip_file(self, inputs): + """ZIP 解压文件工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def zip_unzip_item(self, inputs): + """ZIP 解压道具工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def code_py_exec(self, inputs): + """Python 代码执行工具 + + 这是一个真实执行的工具,在 DAG 生成阶段和运行时评测阶段都会执行代码。 + 输入: code (Python 代码字符串) + 输出: stdout (标准输出,包含执行结果和错误信息) + + 特殊行为: + - 如果代码定义了 main() 函数,会自动调用它 + - 如果执行出错,错误信息会包含在 stdout 中 + """ + code = inputs.get("code", "") + + if not code: + return {"stdout": "Error: No code provided"} + + try: + # 创建一个受限的执行环境 + import io + import sys + + # 捕获标准输出和标准错误 + old_stdout = sys.stdout + old_stderr = sys.stderr + sys.stdout = io.StringIO() + sys.stderr = io.StringIO() + + # 执行代码 + exec_globals = {"__builtins__": __builtins__} + exec_locals = {} + exec(code, exec_globals, exec_locals) + + # 如果定义了 main() 函数,自动调用它 + if 'main' in exec_locals and callable(exec_locals['main']): + exec_locals['main']() + + # 获取输出 + stdout_value = sys.stdout.getvalue() + stderr_value = sys.stderr.getvalue() + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 合并 stdout 和 stderr + output = stdout_value + if stderr_value: + output += ("\n" if output else "") + f"[stderr] {stderr_value}" + + # 如果没有任何输出,尝试返回 result 变量的值 + if not output: + result = exec_locals.get("_result") or exec_locals.get("result") + if result is not None: + output = str(result) + + return {"stdout": output if output else "(no output)"} + + except Exception as e: + # 恢复标准输出和错误输出 + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 返回错误信息 + return {"stdout": f"Error: {type(e).__name__}: {str(e)}"} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-534660f4/environment/puzzle/worker.Dockerfile b/tasks/agentescape-25-skeleton-534660f4/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-25-skeleton-534660f4/environment/puzzle/worker.Dockerfile @@ -0,0 +1,8 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends libseccomp2 && rm -rf /var/lib/apt/lists/* +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY worker.py child.py /app/ +COPY upstream/simulator.py /app/simulator.py +CMD ["uvicorn", "worker:app", "--host", "0.0.0.0", "--port", "8001", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-25-skeleton-534660f4/environment/puzzle/worker.py b/tasks/agentescape-25-skeleton-534660f4/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-25-skeleton-534660f4/environment/puzzle/worker.py @@ -0,0 +1,73 @@ +"""Stateless Python tool worker. Never receives a scenario or reference values.""" + +import json +import os +import signal +import subprocess +import sys +import tempfile +import threading + +from fastapi import FastAPI +from pydantic import BaseModel, ConfigDict + +app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) +lock = threading.Lock() + + +class Execution(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + code: str + + +@app.get("/health") +def health(): + return {"ok": True} + + +@app.post("/execute") +def execute(request: Execution): + if len(request.code.encode()) > 65536: + return {"stdout": "Error: code exceeds 64 KiB limit"} + with lock, tempfile.TemporaryDirectory(prefix="escape-code-") as directory: + os.chown(directory, 65534, 65534) + with tempfile.TemporaryFile() as output: + process = subprocess.Popen( + [sys.executable, "-I", "/app/child.py"], + stdin=subprocess.PIPE, + stdout=output, + stderr=subprocess.DEVNULL, + cwd=directory, + user=65534, + group=65534, + extra_groups=[], + start_new_session=True, + env={"PATH": "/usr/local/bin:/usr/bin:/bin"}, + ) + try: + process.communicate( + json.dumps({"code": request.code}).encode(), timeout=5 + ) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + return {"stdout": "Error: Python execution timed out"} + finally: + # Also remove children still in the process group after normal exit. + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + output.seek(0) + value = output.read(65537) + if len(value) > 65536 or process.returncode != 0: + return { + "stdout": "Error: Python execution exceeded a resource limit or failed" + } + try: + result = json.loads(value) + if not isinstance(result.get("stdout"), str): + raise ValueError("Invalid worker response") + return result + except (ValueError, AttributeError): + return {"stdout": "Error: Python execution returned invalid output"} diff --git a/tasks/agentescape-25-skeleton-534660f4/instruction.md b/tasks/agentescape-25-skeleton-534660f4/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-25-skeleton-534660f4/instruction.md @@ -0,0 +1,18 @@ +# Escape the room + +Discover the victory string and submit it with `escape submit-answer`. +Start with `escape observe`. This returns the room, available information, visible entities, and victory node ID. + +Use these commands (JSON responses): + +```sh +escape investigate NODE_ID +escape tool-call NODE_ID --arguments-json '{"parameter": "value"}' +escape use-item NODE_ID --arguments-json '{"parameter": "value"}' +escape submit-answer 'exact victory string' +escape state +``` + +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. + +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. diff --git a/tasks/agentescape-25-skeleton-534660f4/solution/oracle.py b/tasks/agentescape-25-skeleton-534660f4/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-25-skeleton-534660f4/solution/oracle.py @@ -0,0 +1,133 @@ +"""Reference solver: use trusted inputs, but obtain the answer through public actions.""" + +import json +import urllib.request +from pathlib import Path + + +def http_action(base_url, payload): + request = urllib.request.Request( + base_url + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(request, timeout=30) as response: + return json.load(response) + + +def solve(scenario, act, observe): + nodes = {node["id"]: node for node in scenario["nodes"]} + visible = {entity["id"] for entity in observe["available_entities"]} + solved = set() + seen_outputs = {} + action_count = 0 + + def call(payload): + nonlocal action_count + action_count += 1 + response = act(payload) + visible.update(entity["id"] for entity in response.get("newly_revealed", [])) + if ( + response.get("episode", {}).get("termination_reason") + == "infrastructure_error" + ): + raise RuntimeError("Infrastructure failure") + return response + + for _round in range(len(nodes) + 2): + progress = False + for node_id, node in nodes.items(): + if node_id not in visible or node_id in solved: + continue + # Preserve graph order for data inputs; trigger/drop edges express visibility. + predecessors = [ + edge["source_id"] + for edge in scenario["edges"] + if edge["target_id"] == node_id + and edge["connection_type"] not in ("Item", "Hidden_Item") + ] + if any(pred not in solved for pred in predecessors): + continue + info = call({"action": "investigate", "node_id": node_id}) + if not info.get("ok"): + raise RuntimeError(f"Investigation failed: {node_id}: {info}") + inputs = { + port["name"]: port["value"] + for port in node.get("inputs", []) + if "value" in port + } + if node["type"] == "Tool": + result = call( + {"action": "tool_call", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok") or result.get("output_values", {}).get("error"): + raise RuntimeError(f"Tool failed: {node_id}: {result}") + output = result.get("output_values", {}) + if node.get("template_id") in ("terminal_1", "terminal_2"): + slots = { + port["name"]: inputs[port["name"]] + for port in node["inputs"] + if port["type"] not in ("Item", "Hidden_Item") + and port["name"] in inputs + } + triggers = { + key: value for key, value in inputs.items() if key not in slots + } + for key, value in slots.items(): + partial = call( + { + "action": "tool_call", + "node_id": node_id, + "arguments": {**triggers, key: value}, + } + ) + if partial.get("ok"): + output.update(partial.get("output_values", {})) + # HIDDEN_ITEM tool drops only occur on subsequent investigation. + call({"action": "investigate", "node_id": node_id}) + elif info.get("required_inputs"): + result = call( + {"action": "use_item", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok"): + raise RuntimeError(f"Item failed: {node_id}: {result}") + output = result.get("content") + else: + output = info.get("content") + seen_outputs[node_id] = output + solved.add(node_id) + progress = True + win_id = scenario["metadata"]["win_node_id"] + if win_id in solved and (len(solved) == len(nodes) or not progress): + outputs = seen_outputs[win_id] + if not outputs: + raise RuntimeError(f"Victory node returned no output: {win_id}") + # Upstream grades its first stored output port, independent of response order. + victory_port = next( + port["name"] for port in nodes[win_id]["outputs"] if "value" in port + ) + answer = outputs[victory_port] if isinstance(outputs, dict) else outputs + result = call({"action": "submit_answer", "answer": answer}) + if not result.get("is_win"): + raise RuntimeError(f"Victory submission failed: {result}") + return {"won": True, "actions": action_count, "visited_nodes": len(solved)} + if not progress: + raise RuntimeError(f"No progress: visible={visible}, solved={solved}") + raise RuntimeError("Reference solver exceeded graph traversal limit") + + +if __name__ == "__main__": + import os + + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000") + with urllib.request.urlopen(base + "/observation", timeout=20) as response: + observation = json.load(response) + print( + json.dumps( + solve( + json.loads(Path("/solution/scenario.json").read_text()), + lambda payload: http_action(base, payload), + observation, + ) + ) + ) diff --git a/tasks/agentescape-25-skeleton-534660f4/solution/scenario.json b/tasks/agentescape-25-skeleton-534660f4/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..f35ce77b135157b87b312eae1719c59d46508b6d --- /dev/null +++ b/tasks/agentescape-25-skeleton-534660f4/solution/scenario.json @@ -0,0 +1,1611 @@ +{ + "metadata": { + "total_nodes": 25, + "total_edges": 32, + "win_node_id": "item_14", + "win_condition": { + "type": "item_content", + "node_id": "item_14", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_14", + "terminal_2", + "checksum_crc32", + "zip_unzip_file", + "checksum_crc32_c0b0", + "graph_shortest_path", + "zip_unzip_file_3108", + "code_py_exec", + "zip_unzip_file_d063", + "terminal_2_5f21", + "calc_modexp", + "terminal_1", + "code_py_exec_53ac", + "num_base_convert_044e", + "terminal_1_7a1d", + "calc_bigmul_ab3c", + "item_9" + ], + "by_node": { + "item_14": { + "node_name": "", + "node_type": "Item", + "template_id": "item_14", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Hex_String_IV_AES", + "description": "AES IV" + } + } + }, + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": {}, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + }, + "math_token": { + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + } + }, + "checksum_crc32": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "checksum_crc32_c0b0": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": {}, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "zip_unzip_file_3108": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "code_py_exec": { + "node_name": "Python Executor", + "node_type": "Tool", + "template_id": "code_py_exec", + "init_inputs": { + "code": { + "type": "Code_Python", + "description": "Python code" + } + }, + "init_outputs": {} + }, + "zip_unzip_file_d063": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "terminal_2_5f21": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": { + "num1": { + "type": "Big_Int", + "description": "First Number" + }, + "num2": { + "type": "Big_Int", + "description": "Second Number" + } + }, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + } + } + }, + "calc_modexp": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": { + "slot_a": { + "type": "Text_Generic", + "description": "Input Slot A" + } + }, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + } + } + }, + "code_py_exec_53ac": { + "node_name": "Python Executor", + "node_type": "Tool", + "template_id": "code_py_exec", + "init_inputs": { + "code": { + "type": "Code_Python", + "description": "Python code" + } + }, + "init_outputs": {} + }, + "num_base_convert_044e": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "s": { + "type": "Big_Int", + "description": "Input integer value" + }, + "from_base": { + "type": "Big_Int", + "description": "From base" + }, + "to_base": { + "type": "Big_Int", + "description": "To base" + } + }, + "init_outputs": {} + }, + "terminal_1_7a1d": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": { + "slot_a": { + "type": "Text_Generic", + "description": "Input Slot A" + } + }, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + } + } + }, + "calc_bigmul_ab3c": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "b": { + "type": "Big_Int", + "description": "Second large integer" + } + }, + "init_outputs": {} + }, + "item_9": { + "node_name": "", + "node_type": "Item", + "template_id": "item_9", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "File_Id", + "description": "JSON file path" + } + } + } + } + }, + "initial_values": { + "item_14": { + "init_inputs": {}, + "init_outputs": { + "content": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Initial text output from terminal two.", + "hex_result": "112233445566778899aabbccddeeff00", + "math_token": "Useless token from terminal two op" + } + }, + "checksum_crc32": { + "init_inputs": { + "hex": "deadbeef12345678" + }, + "init_outputs": {} + }, + "zip_unzip_file": { + "init_inputs": { + "zip_id": "archive1.zip" + }, + "init_outputs": { + "files": "extracted1.txt" + } + }, + "checksum_crc32_c0b0": { + "init_inputs": { + "hex": "cafebabe87654321" + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": {}, + "init_outputs": { + "path": "[\"node_alpha\", \"node_beta\", \"node_gamma\", \"node_delta\", \"node_epsilon\"]", + "cost": "847259" + } + }, + "zip_unzip_file_3108": { + "init_inputs": {}, + "init_outputs": { + "files": "extracted2.csv" + } + }, + "code_py_exec": { + "init_inputs": { + "code": "print('Hello from py_exec')" + }, + "init_outputs": {} + }, + "zip_unzip_file_d063": { + "init_inputs": {}, + "init_outputs": { + "files": "extracted3.json" + } + }, + "terminal_2_5f21": { + "init_inputs": { + "num1": "1234567890123456789012", + "num2": "9876543210987654321098" + }, + "init_outputs": { + "text_result": "Another text result from terminal calculation.", + "hex_result": "aabbccddeeff11223344556677889900" + } + }, + "calc_modexp": { + "init_inputs": { + "mod": "997333" + }, + "init_outputs": {} + }, + "terminal_1": { + "init_inputs": { + "slot_a": "Slot A initial input text here." + }, + "init_outputs": { + "text_output": "Terminal one generated this text content.", + "hex_output": "1234567890abcdef1234567890abcdef" + } + }, + "code_py_exec_53ac": { + "init_inputs": { + "code": "print('Executing py script 53ac')" + }, + "init_outputs": {} + }, + "num_base_convert_044e": { + "init_inputs": { + "s": "11223344556677889900112233", + "from_base": "10", + "to_base": "10" + }, + "init_outputs": {} + }, + "terminal_1_7a1d": { + "init_inputs": { + "slot_a": "Slot A for terminal 7a1d" + }, + "init_outputs": { + "text_output": "Output text generated from terminal 7a1d.", + "hex_output": "fedcba0987654321fedcba0987654321" + } + }, + "calc_bigmul_ab3c": { + "init_inputs": { + "b": "123123123123123123123123" + }, + "init_outputs": {} + }, + "item_9": { + "init_inputs": {}, + "init_outputs": { + "content": "secret_data.json" + } + } + }, + "intro_narrative": "You wake up in the dimly lit underground server room of the enigmatic Blackwood Corporation. The air hums with the sound of cooling fans, and blinking LEDs cast long, unnatural shadows across the concrete floor. You've broken in to uncover the truth behind their illegal surveillance operations, but the facility's automated systems have locked down the sector. The main blast doors are sealed, and your only way out is to retrieve the master keycard hidden deep within their encrypted network. You will need to navigate a complex maze of biometric locks, cryptographic modules, and encrypted servers to piece together the necessary override protocols. Time is running out before the night guards complete their rounds.", + "narrative_style": "mystery" + }, + "nodes": [ + { + "id": "item_14", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_14", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hex_String_IV_AES", + "description": "AES IV", + "value": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "narrative": "A heavy metallic keycard." + }, + { + "id": "zip_unzip_item", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_item", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "extracted1.txt" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Initial text output from terminal two." + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip" + } + ], + "narrative": "This is the final extraction drive. It requires inputs from the main security terminal and the secondary decryption server." + }, + { + "id": "terminal_2", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": 2982214246 + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "118278309" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Initial text output from terminal two." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "112233445566778899aabbccddeeff00" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "Useless token from terminal two op" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "Initial text output from terminal two.", + "hex_result": "112233445566778899aabbccddeeff00", + "math_token": "Useless token from terminal two op" + } + }, + "narrative": "This is the main security terminal. It requires inputs from the biometric fingerprint scanner and the numeric decoder console." + }, + { + "id": "checksum_crc32", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "deadbeef12345678" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "b1c0fa66" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 2982214246 + } + ], + "init": { + "inputs": { + "hex": "deadbeef12345678" + }, + "outputs": {} + }, + "narrative": "A biometric fingerprint scanner embedded in the wall." + }, + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "archive1.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Initial text output from terminal two." + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted1.txt" + } + ], + "init": { + "inputs": { + "zip_id": "archive1.zip" + }, + "outputs": { + "files": "extracted1.txt" + } + }, + "narrative": "This is the secondary decryption server. It requires input from the main security terminal." + }, + { + "id": "num_base_convert", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": 118278309 + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "118278309" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "696369797431" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "118278309" + } + ], + "narrative": "This is the numeric decoder console. It requires inputs from the retinal scanner, the cryptographic multiplier, and the inversion algorithm module." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A tiny, hidden microchip." + }, + { + "id": "checksum_crc32_c0b0", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "cafebabe87654321" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "070cc8a5" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 118278309 + } + ], + "init": { + "inputs": { + "hex": "cafebabe87654321" + }, + "outputs": {} + }, + "narrative": "A high-tech retinal scanner." + }, + { + "id": "calc_bigmul", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "821909" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "847259" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "696369797431" + } + ], + "narrative": "This is the cryptographic multiplier. It requires inputs from the network routing module and the quantum processor." + }, + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "extracted2.csv" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Hello from py_exec\n" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Executing py script 53ac\n" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"node_alpha\", \"node_beta\", \"node_gamma\", \"node_delta\", \"node_epsilon\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "847259" + } + ], + "init": { + "inputs": {}, + "outputs": { + "path": "[\"node_alpha\", \"node_beta\", \"node_gamma\", \"node_delta\", \"node_epsilon\"]", + "cost": "847259" + } + }, + "narrative": "This is the network routing module. It requires inputs from the primary decryption server, the central database access point, and the surveillance database access point." + }, + { + "id": "zip_unzip_file_3108", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "extracted3.json" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Another text result from terminal calculation." + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted2.csv" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "extracted2.csv" + } + }, + "narrative": "This is the primary decryption server. It requires inputs from the initial decryption server and the personnel verification terminal." + }, + { + "id": "code_py_exec", + "name": "Python Executor", + "description": "Run limited Python: only safe builtins.", + "type": "Tool", + "template_id": "code_py_exec", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "code", + "type": "Code_Python", + "description": "Python code", + "value": "print('Hello from py_exec')" + } + ], + "outputs": [ + { + "name": "stdout", + "type": "Text_Generic", + "description": "Standard Output (includes errors if any)", + "value": "Hello from py_exec\n" + } + ], + "init": { + "inputs": { + "code": "print('Hello from py_exec')" + }, + "outputs": {} + }, + "narrative": "The central database access point." + }, + { + "id": "zip_unzip_file_d063", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "secret_data.json" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Another text result from terminal calculation." + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted3.json" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "extracted3.json" + } + }, + "narrative": "This is the initial decryption server. It requires inputs from the personnel verification terminal and the locked digital dossier." + }, + { + "id": "terminal_2_5f21", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "1234567890123456789012" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "9876543210987654321098" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Another text result from terminal calculation." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "aabbccddeeff11223344556677889900" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": { + "num1": "1234567890123456789012", + "num2": "9876543210987654321098" + }, + "outputs": { + "text_result": "Another text result from terminal calculation.", + "hex_result": "aabbccddeeff11223344556677889900" + } + }, + "narrative": "The personnel verification terminal." + }, + { + "id": "calc_modexp", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "11223344556677889900112233" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": 118278309 + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "997333" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "821909" + } + ], + "init": { + "inputs": { + "mod": "997333" + }, + "outputs": {} + }, + "narrative": "This is the quantum processor. It requires inputs from the retinal scanner and the auxiliary numerical decoder." + }, + { + "id": "item_8_e271", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "An encrypted security token." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this terminal" + }, + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "Slot A initial input text here." + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "14562794801801801801801787239007" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Terminal one generated this text content." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "1234567890abcdef1234567890abcdef" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": { + "slot_a": "Slot A initial input text here." + }, + "outputs": { + "text_output": "Terminal one generated this text content.", + "hex_output": "1234567890abcdef1234567890abcdef" + } + }, + "narrative": "This is the administrative override console. It requires input from the secondary cryptographic multiplier." + }, + { + "id": "calc_inv_mod", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": 118278309 + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "11223344556677889900112233" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "118278309" + } + ], + "narrative": "This is the inversion algorithm module. It requires inputs from the retinal scanner and the auxiliary numerical decoder." + }, + { + "id": "code_py_exec_53ac", + "name": "Python Executor", + "description": "Run limited Python: only safe builtins.", + "type": "Tool", + "template_id": "code_py_exec", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "code", + "type": "Code_Python", + "description": "Python code", + "value": "print('Executing py script 53ac')" + } + ], + "outputs": [ + { + "name": "stdout", + "type": "Text_Generic", + "description": "Standard Output (includes errors if any)", + "value": "Executing py script 53ac\n" + } + ], + "init": { + "inputs": { + "code": "print('Executing py script 53ac')" + }, + "outputs": {} + }, + "narrative": "The surveillance database access point." + }, + { + "id": "num_base_convert_044e", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "11223344556677889900112233" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "10" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "10" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "11223344556677889900112233" + } + ], + "init": { + "inputs": { + "s": "11223344556677889900112233", + "from_base": "10", + "to_base": "10" + }, + "outputs": {} + }, + "narrative": "The auxiliary numerical decoder." + }, + { + "id": "terminal_1_7a1d", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "Slot A for terminal 7a1d" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "847259" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Output text generated from terminal 7a1d." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "fedcba0987654321fedcba0987654321" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": { + "slot_a": "Slot A for terminal 7a1d" + }, + "outputs": { + "text_output": "Output text generated from terminal 7a1d.", + "hex_output": "fedcba0987654321fedcba0987654321" + } + }, + "narrative": "This is the subsystem override console. It requires input from the network routing module." + }, + { + "id": "calc_bigmul_ab3c", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "118278309" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "123123123123123123123123" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "14562794801801801801801787239007" + } + ], + "init": { + "inputs": { + "b": "123123123123123123123123" + }, + "outputs": {} + }, + "narrative": "This is the secondary cryptographic multiplier. It requires input from the inversion algorithm module." + }, + { + "id": "item_9", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_9", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "File_Id", + "description": "JSON file path", + "value": "secret_data.json" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "secret_data.json" + } + }, + "narrative": "A locked digital dossier." + }, + { + "id": "item_8_ddbf", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A dusty memory card." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A fragmented data log." + } + ], + "edges": [ + { + "source_id": "zip_unzip_item", + "target_id": "item_14", + "connection_type": "Item", + "source_port": "item", + "target_port": "source_tool" + }, + { + "source_id": "terminal_2", + "target_id": "zip_unzip_item", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "password" + }, + { + "source_id": "checksum_crc32", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "num1" + }, + { + "source_id": "zip_unzip_file", + "target_id": "zip_unzip_item", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "num_base_convert", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "num2" + }, + { + "source_id": "item_8", + "target_id": "zip_unzip_file", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "terminal_2", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "password" + }, + { + "source_id": "checksum_crc32_c0b0", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "s" + }, + { + "source_id": "calc_bigmul", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "to_base" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "b" + }, + { + "source_id": "zip_unzip_file_3108", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "code_py_exec", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "stdout", + "target_port": "src" + }, + { + "source_id": "zip_unzip_file_d063", + "target_id": "zip_unzip_file_3108", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "terminal_2_5f21", + "target_id": "zip_unzip_file_d063", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "password" + }, + { + "source_id": "calc_modexp", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "a" + }, + { + "source_id": "item_8_e271", + "target_id": "zip_unzip_file_3108", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "terminal_1", + "target_id": "calc_modexp", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "trigger_item" + }, + { + "source_id": "checksum_crc32_c0b0", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "exp" + }, + { + "source_id": "calc_inv_mod", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "from_base" + }, + { + "source_id": "code_py_exec_53ac", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "stdout", + "target_port": "dst" + }, + { + "source_id": "num_base_convert_044e", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "base" + }, + { + "source_id": "terminal_1_7a1d", + "target_id": "num_base_convert_044e", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "trigger_item" + }, + { + "source_id": "checksum_crc32_c0b0", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "a" + }, + { + "source_id": "calc_bigmul_ab3c", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "slot_b" + }, + { + "source_id": "num_base_convert_044e", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "mod" + }, + { + "source_id": "graph_shortest_path", + "target_id": "terminal_1_7a1d", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "slot_b" + }, + { + "source_id": "item_9", + "target_id": "zip_unzip_file_d063", + "connection_type": "File_Id", + "source_port": "content", + "target_port": "zip_id" + }, + { + "source_id": "item_8_ddbf", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "terminal_2_5f21", + "target_id": "zip_unzip_file_3108", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "password" + }, + { + "source_id": "calc_inv_mod", + "target_id": "calc_bigmul_ab3c", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "a" + }, + { + "source_id": "terminal_2_5f21", + "target_id": "graph_shortest_path", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "trigger_item" + }, + { + "source_id": "item_16", + "target_id": "terminal_1", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-534660f4/solution/solve.sh b/tasks/agentescape-25-skeleton-534660f4/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-25-skeleton-534660f4/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-25-skeleton-534660f4/task.toml b/tasks/agentescape-25-skeleton-534660f4/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a1c66295058cb8a8314e75e6240e6efcab95284b --- /dev/null +++ b/tasks/agentescape-25-skeleton-534660f4/task.toml @@ -0,0 +1,38 @@ +schema_version = "1.4" +source = "https://github.com/AGI-Eval-Official/Repo-of-AgentEscapeBench" + +[[artifacts]] +source = "/evidence/final.json" +service = "puzzle" + +[[artifacts]] +source = "/evidence/trace.jsonl" +service = "puzzle" + +[task] +name = "edbeeching/agentescape-25-skeleton-534660f4" +version = "0.1.0" + +[metadata] +difficulty = 25 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "eea647b1d4d967edf3f4bedb9f1f9513bf804a4c1dd23b5614f6c67b18045bd7" +protocol = "harbor-cli-action-budget-v1" +max_actions = 500 + +[agent] +timeout_sec = 1200 + +[environment] +build_timeout_sec = 900 +cpus = 1 +memory_mb = 1024 + +[verifier] +environment_mode = "separate" +timeout_sec = 60 + +[[verifier.collect]] +service = "puzzle" +command = "python -I /app/export.py" +timeout_sec = 15 diff --git a/tasks/agentescape-25-skeleton-534660f4/tests/Dockerfile b/tasks/agentescape-25-skeleton-534660f4/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-25-skeleton-534660f4/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-25-skeleton-534660f4/tests/expected.json b/tasks/agentescape-25-skeleton-534660f4/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..0484db5b294ceb7e89eacaf6a4cf9a6202053968 --- /dev/null +++ b/tasks/agentescape-25-skeleton-534660f4/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "eea647b1d4d967edf3f4bedb9f1f9513bf804a4c1dd23b5614f6c67b18045bd7", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-534660f4/tests/grade.py b/tasks/agentescape-25-skeleton-534660f4/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-25-skeleton-534660f4/tests/grade.py @@ -0,0 +1,21 @@ +"""Grade only Harbor-collected sidecar evidence in a fresh verifier container.""" + +import json +from pathlib import Path + +expected = json.loads(Path("/tests/expected.json").read_text()) +state = json.loads(Path("/evidence/final.json").read_text()) +assert state["collected_from_live_service"] is True, "Missing trusted service export" +assert state["scenario_sha256"] == expected["scenario_sha256"], ( + "Wrong scenario evidence" +) +assert state["max_actions"] == expected["max_actions"], "Wrong budget" +assert type(state["won"]) is bool +assert 0 <= state["action_count"] <= state["max_actions"] +assert state["termination_reason"] != "infrastructure_error", ( + "Infrastructure failure is not a puzzle failure" +) +assert not state["won"] or state["termination_reason"] == "success" +Path("/logs/verifier").mkdir(parents=True, exist_ok=True) +Path("/logs/verifier/state.json").write_text(json.dumps(state, indent=2)) +Path("/logs/verifier/reward.txt").write_text("1.0\n" if state["won"] else "0.0\n") diff --git a/tasks/agentescape-25-skeleton-534660f4/tests/test.sh b/tasks/agentescape-25-skeleton-534660f4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-25-skeleton-534660f4/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-25-skeleton-5d659179/environment/Dockerfile b/tasks/agentescape-25-skeleton-5d659179/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-25-skeleton-5d659179/environment/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-25-skeleton-5d659179/environment/agent/Dockerfile b/tasks/agentescape-25-skeleton-5d659179/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-25-skeleton-5d659179/environment/agent/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-25-skeleton-5d659179/environment/agent/cli.py b/tasks/agentescape-25-skeleton-5d659179/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-25-skeleton-5d659179/environment/agent/cli.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Public agent client; depends only on the Python standard library.""" + +import argparse +import json +import os +import sys +import urllib.error +import urllib.request + + +def main(): + parser = argparse.ArgumentParser(description="Interact with the escape room") + parser.add_argument( + "action", + choices=[ + "observe", + "state", + "investigate", + "tool-call", + "use-item", + "submit-answer", + ], + ) + parser.add_argument("value", nargs="?") + parser.add_argument("--arguments-json", default="{}") + args = parser.parse_args() + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000").rstrip("/") + if args.action in ("observe", "state"): + request = urllib.request.Request( + base + ("/observation" if args.action == "observe" else "/state") + ) + else: + if args.value is None: + parser.error("node ID or answer is required") + payload = {"action": args.action.replace("-", "_")} + if args.action == "submit-answer": + payload["answer"] = args.value + else: + payload["node_id"] = args.value + if args.action in ("tool-call", "use-item"): + payload["arguments"] = json.loads(args.arguments_json) + request = urllib.request.Request( + base + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=30) as response: + print(json.dumps(json.load(response), ensure_ascii=False)) + except (urllib.error.URLError, ValueError) as exc: + print(json.dumps({"ok": False, "error": str(exc)})) + sys.exit(2) + + +if __name__ == "__main__": + main() diff --git a/tasks/agentescape-25-skeleton-5d659179/environment/docker-compose.yaml b/tasks/agentescape-25-skeleton-5d659179/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9692b7b74b570f1e05afcead54e509dcf431ac3f --- /dev/null +++ b/tasks/agentescape-25-skeleton-5d659179/environment/docker-compose.yaml @@ -0,0 +1,50 @@ +services: + main: + image: agentescapebench-agent:aab05a0a9ddb + build: + context: ./agent + networks: [default, puzzle] + security_opt: [no-new-privileges:true] + depends_on: + puzzle: + condition: service_healthy + puzzle: + image: agentescapebench-puzzle:agentescape-25-skeleton-5d659179-aab05a0a9ddb + build: + context: ./puzzle + networks: [puzzle, execution] + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 512m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"] + interval: 1s + timeout: 3s + retries: 30 + depends_on: + worker: + condition: service_healthy + worker: + image: agentescapebench-worker:aab05a0a9ddb + build: + context: ./puzzle + dockerfile: worker.Dockerfile + networks: [execution] + read_only: true + tmpfs: ["/tmp:size=64m,mode=1777"] + cap_drop: [ALL] + cap_add: [SETUID, SETGID, KILL, CHOWN, DAC_OVERRIDE] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 384m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8001/health')"] + interval: 1s + timeout: 3s + retries: 30 +networks: + puzzle: + internal: true + execution: + internal: true diff --git a/tasks/agentescape-25-skeleton-5d659179/environment/puzzle/Dockerfile b/tasks/agentescape-25-skeleton-5d659179/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-25-skeleton-5d659179/environment/puzzle/Dockerfile @@ -0,0 +1,9 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY upstream /app/upstream +COPY service.py export.py /app/ +COPY scenario.json /private/scenario.json +ENV SCENARIO_PATH=/private/scenario.json EVIDENCE_DIR=/evidence WORKER_URL=http://worker:8001 MAX_ACTIONS=500 +CMD ["uvicorn", "service:create_app", "--factory", "--host", "0.0.0.0", "--port", "8000", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-25-skeleton-5d659179/environment/puzzle/child.py b/tasks/agentescape-25-skeleton-5d659179/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-25-skeleton-5d659179/environment/puzzle/child.py @@ -0,0 +1,59 @@ +"""Run the original Python tool after reducing privileges and blocking networking.""" + +import ctypes +import errno +import json +import resource +import sys + +resource.setrlimit(resource.RLIMIT_CPU, (3, 3)) +resource.setrlimit(resource.RLIMIT_AS, (256 * 1024 * 1024, 256 * 1024 * 1024)) +resource.setrlimit(resource.RLIMIT_FSIZE, (65536, 65536)) +resource.setrlimit(resource.RLIMIT_NOFILE, (32, 32)) +resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + +# Filters survive fork/exec. Fail closed if seccomp cannot be loaded. +lib = ctypes.CDLL("libseccomp.so.2", use_errno=True) +lib.seccomp_init.argtypes = [ctypes.c_uint32] +lib.seccomp_init.restype = ctypes.c_void_p +lib.seccomp_rule_add.argtypes = [ + ctypes.c_void_p, + ctypes.c_uint32, + ctypes.c_int, + ctypes.c_uint, +] +lib.seccomp_syscall_resolve_name.argtypes = [ctypes.c_char_p] +lib.seccomp_load.argtypes = [ctypes.c_void_p] +lib.seccomp_release.argtypes = [ctypes.c_void_p] +ctx = lib.seccomp_init(0x7FFF0000) # SCMP_ACT_ALLOW +if not ctx: + raise RuntimeError("Cannot initialize execution isolation") +try: + for name in ( + "socket", + "socketpair", + "connect", + "ptrace", + "process_vm_readv", + "process_vm_writev", + "mount", + "unshare", + "setns", + "bpf", + ): + number = lib.seccomp_syscall_resolve_name(name.encode()) + if ( + number >= 0 + and lib.seccomp_rule_add(ctx, 0x00050000 | errno.EPERM, number, 0) != 0 + ): + raise RuntimeError("Cannot install execution isolation rule") + if lib.seccomp_load(ctx) != 0: + raise RuntimeError("Cannot activate execution isolation") +finally: + lib.seccomp_release(ctx) + +sys.path.insert(0, "/app") +from simulator import ToolSimulator # noqa: E402 + +request = json.load(sys.stdin) +json.dump(ToolSimulator().code_py_exec(request), sys.stdout) diff --git a/tasks/agentescape-25-skeleton-5d659179/environment/puzzle/export.py b/tasks/agentescape-25-skeleton-5d659179/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-25-skeleton-5d659179/environment/puzzle/export.py @@ -0,0 +1,13 @@ +"""Harbor invokes this inside the puzzle service after stopping the agent.""" + +import json +import pathlib +import urllib.request + +with urllib.request.urlopen("http://127.0.0.1:8000/state", timeout=10) as response: + state = json.load(response) +state["collected_from_live_service"] = True +target = pathlib.Path("/evidence/final.json") +temp = target.with_suffix(".tmp") +temp.write_text(json.dumps(state)) +temp.replace(target) diff --git a/tasks/agentescape-25-skeleton-5d659179/environment/puzzle/requirements.txt b/tasks/agentescape-25-skeleton-5d659179/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-25-skeleton-5d659179/environment/puzzle/requirements.txt @@ -0,0 +1,57 @@ +annotated-doc==0.0.5 + # via fastapi +annotated-types==0.8.0 + # via pydantic +anyio==4.16.0 + # via starlette +certifi==2026.10.23 + # via requests +cffi==2.1.1 ; platform_python_implementation != 'PyPy' + # via cryptography +charset-normalizer==3.5.2 + # via requests +click==8.5.0 + # via uvicorn +cryptography==50.0.2 + # via agentescapebench-harbor +fastapi==0.162.0 + # via agentescapebench-harbor +h11==0.16.0 + # via uvicorn +idna==3.20 + # via + # anyio + # requests +opentelemetry-api==1.45.2 + # via fastapi +pycparser==3.12 ; implementation_name != 'PyPy' and platform_python_implementation != 'PyPy' + # via cffi +pydantic==2.14.2 + # via + # agentescapebench-harbor + # fastapi +pydantic-core==2.50.2 + # via pydantic +pytz==2025.2 + # via agentescapebench-harbor +requests==2.34.2 + # via agentescapebench-harbor +starlette==1.10.0 + # via fastapi +typing-extensions==4.16.0 + # via + # anyio + # fastapi + # opentelemetry-api + # pydantic + # pydantic-core + # starlette + # typing-inspection +typing-inspection==0.4.4 + # via + # fastapi + # pydantic +urllib3==2.8.0 + # via requests +uvicorn==0.54.0 + # via agentescapebench-harbor diff --git a/tasks/agentescape-25-skeleton-5d659179/environment/puzzle/scenario.json b/tasks/agentescape-25-skeleton-5d659179/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..27dc4c20033f5b07f5bc3e01ea93cc644b90113c --- /dev/null +++ b/tasks/agentescape-25-skeleton-5d659179/environment/puzzle/scenario.json @@ -0,0 +1,1344 @@ +{ + "metadata": { + "total_nodes": 25, + "total_edges": 29, + "win_node_id": "item_5", + "win_condition": { + "type": "item_content", + "node_id": "item_5", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_5", + "terminal_2", + "num_base_convert", + "calc_bigmul_e997", + "terminal_2_df1b", + "terminal_2_b20d", + "calc_gcd", + "zip_unzip_item", + "item_10", + "text_xor_hex" + ], + "by_node": { + "item_5": { + "node_name": "", + "node_type": "Item", + "template_id": "item_5", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Hex_String_Key_AES", + "description": "AES Key" + } + } + }, + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": {}, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + } + } + }, + "num_base_convert": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "s": { + "type": "Big_Int", + "description": "Input integer value" + }, + "from_base": { + "type": "Big_Int", + "description": "From base" + }, + "to_base": { + "type": "Big_Int", + "description": "To base" + } + }, + "init_outputs": {} + }, + "calc_bigmul_e997": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First large integer" + }, + "b": { + "type": "Big_Int", + "description": "Second large integer" + } + }, + "init_outputs": {} + }, + "terminal_2_df1b": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": { + "num2": { + "type": "Big_Int", + "description": "Second Number" + } + }, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + }, + "math_token": { + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + } + }, + "terminal_2_b20d": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": { + "num1": { + "type": "Big_Int", + "description": "First Number" + } + }, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + } + } + }, + "calc_gcd": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First integer" + }, + "b": { + "type": "Big_Int", + "description": "Second integer" + } + }, + "init_outputs": {} + }, + "zip_unzip_item": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_item", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + }, + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": {} + }, + "item_10": { + "node_name": "", + "node_type": "Item", + "template_id": "item_10", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Big_Int", + "description": "The number" + } + } + }, + "text_xor_hex": { + "node_name": "Hex XOR", + "node_type": "Tool", + "template_id": "text_xor_hex", + "init_inputs": { + "hex_a": { + "type": "Hex_String", + "description": "Hex A" + }, + "hex_b": { + "type": "Hex_String", + "description": "Hex B" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "item_5": { + "init_inputs": {}, + "init_outputs": { + "content": "8d4f6a1e3b2c9d7a5f0e4b8c1a2d3e4f" + } + }, + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Initial computation resulted in this text.", + "hex_result": "0a1b2c3d4e5f" + } + }, + "num_base_convert": { + "init_inputs": { + "s": "5738291029384756382910", + "from_base": "16", + "to_base": "10" + }, + "init_outputs": {} + }, + "calc_bigmul_e997": { + "init_inputs": { + "a": "1122334455667788990011", + "b": "9988776655443322110099" + }, + "init_outputs": {} + }, + "terminal_2_df1b": { + "init_inputs": { + "num2": "3141592653589793238462" + }, + "init_outputs": { + "text_result": "The terminal has partially computed the task.", + "hex_result": "1a2b3c4d5e6f", + "math_token": "A completely useless piece of math token." + } + }, + "terminal_2_b20d": { + "init_inputs": { + "num1": "2718281828459045235360" + }, + "init_outputs": { + "text_result": "Terminal b20d output completed.", + "hex_result": "2a3b4c5d6e7f", + "math_token": "Yet another useless object for inventory." + } + }, + "calc_gcd": { + "init_inputs": { + "a": "1234567890123456789012", + "b": "9876543210987654321098" + }, + "init_outputs": {} + }, + "zip_unzip_item": { + "init_inputs": { + "zip_id": "data_package_1.zip", + "password": "password_qweasd123" + }, + "init_outputs": {} + }, + "item_10": { + "init_inputs": {}, + "init_outputs": { + "content": "5555566666777778888899" + } + }, + "text_xor_hex": { + "init_inputs": { + "hex_a": "1234567890abcdef", + "hex_b": "fedcba0987654321" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You awaken in the hidden sanctuary of the Grand Wizard Aldous, a master of dimensional magic who has mysteriously vanished. The room is filled with esoteric artifacts, glowing crystals, and strange mechanical devices pulsing with magical energy. A central pedestal displays a message etched in glowing runes: 'Only those who can harmonize the celestial energies and decode the arcane secrets may unlock the ultimate treasure chest and inherit my legacy.' You must carefully study the ancient tools, magical terminals, and celestial sundials scattered around the room to find the correct path of activation. Your final objective is to obtain the master key hidden deep within the ultimate treasure chest. The secrets of the universe await.", + "narrative_style": "fantasy" + }, + "nodes": [ + { + "id": "item_5", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_5", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hex_String_Key_AES", + "description": "AES Key", + "value": "8d4f6a1e3b2c9d7a5f0e4b8c1a2d3e4f" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "8d4f6a1e3b2c9d7a5f0e4b8c1a2d3e4f" + } + }, + "narrative": "The ultimate treasure chest." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A mystical scroll." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "An ancient sundial." + }, + { + "id": "terminal_2", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "11117963973852212532249898887473187004922609035256064" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "11117963973852212532249898887473187004922609035256064" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Initial computation resulted in this text." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "0a1b2c3d4e5f" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "Initial computation resulted in this text.", + "hex_result": "0a1b2c3d4e5f" + } + }, + "narrative": "This is the grand wizard's terminal. It requires inputs from the astral inverter and the celestial inverter." + }, + { + "id": "calc_inv_mod", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "11117963973852212532249898887473187004922609035256064" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "123609122923875681191513219127763133199780146827391935564497792119308993534565038025920637144942048772096" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "11117963973852212532249898887473187004922609035256064" + } + ], + "narrative": "This is the astral inverter. It requires inputs from the celestial inverter and the cosmos multiplier." + }, + { + "id": "calc_inv_mod_1726", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "11117963973852212532249898887473187004922609035256064" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "11210748210374098778011361778402556553221089" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "11117963973852212532249898887473187004922609035256064" + } + ], + "narrative": "This is the celestial inverter. It requires inputs from the aether multiplier and the void multiplier." + }, + { + "id": "calc_bigmul", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "11117963973852212532249898887473187004922609035256064" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "11117963973852212532249898887473187004922609035256064" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "123609122923875681191513219127763133199780146827391935564497792119308993534565038025920637144942048772096" + } + ], + "narrative": "This is the cosmos multiplier. It requires inputs from the celestial inverter and the aether multiplier." + }, + { + "id": "item_16_31d8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A cosmic sundial." + }, + { + "id": "container_4", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_4", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Text_Generic", + "description": "Fingerprint Hash", + "value": "7OjscRfOjs4=" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is the sealed reliquary. It requires input from the runic transcriber." + }, + { + "id": "calc_bigmul_22cd", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "105441756310544318115358992" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "105441756310544318115358992" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "11117963973852212532249898887473187004922609035256064" + } + ], + "narrative": "This is the aether multiplier. It requires inputs from the stellar inverter and the elemental converter." + }, + { + "id": "item_16_4bb3", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "An ethereal sundial." + }, + { + "id": "item_8_e9e7", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A forgotten scroll." + }, + { + "id": "item_16_0568", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A mysterious shadow sundial." + }, + { + "id": "container_1", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_1", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + }, + { + "name": "fingerprint_input", + "type": "Hex_String", + "description": "Fingerprint Hash", + "value": "1a2b3c4d5e6f" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is the starlight chest. It requires input from the oracle's terminal." + }, + { + "id": "base64_encode", + "name": "Base64 Encoder", + "description": "Encode hex bytes to base64.", + "type": "Tool", + "template_id": "base64_encode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex bytes", + "value": "ece8ec7117ce8ece" + } + ], + "outputs": [ + { + "name": "b64", + "type": "Text_Generic", + "description": "Base64 string", + "value": "7OjscRfOjs4=" + } + ], + "narrative": "This is the runic transcriber. It requires input from the arcane weaver." + }, + { + "id": "calc_inv_mod_30b5", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "105441756310544318115358992" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "11210748210374098778011361778402556553221089" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "105441756310544318115358992" + } + ], + "narrative": "This is the stellar inverter. It requires inputs from the elemental converter and the void multiplier." + }, + { + "id": "num_base_convert", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "5738291029384756382910" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "16" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "10" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "105441756310544318115358992" + } + ], + "init": { + "inputs": { + "s": "5738291029384756382910", + "from_base": "16", + "to_base": "10" + }, + "outputs": {} + }, + "narrative": "An ancient elemental converter." + }, + { + "id": "calc_bigmul_e997", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "1122334455667788990011" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "9988776655443322110099" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "11210748210374098778011361778402556553221089" + } + ], + "init": { + "inputs": { + "a": "1122334455667788990011", + "b": "9988776655443322110099" + }, + "outputs": {} + }, + "narrative": "A magical void multiplier." + }, + { + "id": "terminal_2_df1b", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this terminal" + }, + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "5555566666777778888899" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "3141592653589793238462" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "The terminal has partially computed the task." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "1a2b3c4d5e6f" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "A completely useless piece of math token." + } + ], + "init": { + "inputs": { + "num2": "3141592653589793238462" + }, + "outputs": { + "text_result": "The terminal has partially computed the task.", + "hex_result": "1a2b3c4d5e6f", + "math_token": "A completely useless piece of math token." + } + }, + "narrative": "This is the oracle's terminal. It requires input from the crystal sphere." + }, + { + "id": "terminal_2_b20d", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "2718281828459045235360" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "2" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Terminal b20d output completed." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "2a3b4c5d6e7f" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "Yet another useless object for inventory." + } + ], + "init": { + "inputs": { + "num1": "2718281828459045235360" + }, + "outputs": { + "text_result": "Terminal b20d output completed.", + "hex_result": "2a3b4c5d6e7f", + "math_token": "Yet another useless object for inventory." + } + }, + "narrative": "This is the apprentice's terminal. It requires input from the harmonic aligner." + }, + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "1234567890123456789012" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "9876543210987654321098" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "2" + } + ], + "init": { + "inputs": { + "a": "1234567890123456789012", + "b": "9876543210987654321098" + }, + "outputs": {} + }, + "narrative": "An ancient harmonic aligner." + }, + { + "id": "zip_unzip_item", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_item", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "data_package_1.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "password_qweasd123" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip" + } + ], + "init": { + "inputs": { + "zip_id": "data_package_1.zip", + "password": "password_qweasd123" + }, + "outputs": {} + }, + "narrative": "A mystical spell unweaver." + }, + { + "id": "item_10", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_10", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Big_Int", + "description": "The number", + "value": "5555566666777778888899" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "5555566666777778888899" + } + }, + "narrative": "A glowing crystal sphere." + }, + { + "id": "text_xor_hex", + "name": "Hex XOR", + "description": "XOR two hex strings.", + "type": "Tool", + "template_id": "text_xor_hex", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex_a", + "type": "Hex_String", + "description": "Hex A", + "value": "1234567890abcdef" + }, + { + "name": "hex_b", + "type": "Hex_String", + "description": "Hex B", + "value": "fedcba0987654321" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "XOR Result Hex", + "value": "ece8ec7117ce8ece" + } + ], + "init": { + "inputs": { + "hex_a": "1234567890abcdef", + "hex_b": "fedcba0987654321" + }, + "outputs": {} + }, + "narrative": "An arcane weaver." + }, + { + "id": "item_8_d0cf", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "An elemental scroll." + } + ], + "edges": [ + { + "source_id": "item_8", + "target_id": "item_5", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "item_16", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "terminal_2", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "source_tool" + }, + { + "source_id": "calc_inv_mod", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "num2" + }, + { + "source_id": "calc_inv_mod_1726", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "num1" + }, + { + "source_id": "calc_inv_mod_1726", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "a" + }, + { + "source_id": "calc_bigmul", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "mod" + }, + { + "source_id": "item_16_31d8", + "target_id": "calc_bigmul", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "container_4", + "target_id": "item_16_31d8", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "calc_inv_mod_1726", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "a" + }, + { + "source_id": "calc_bigmul_22cd", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "b" + }, + { + "source_id": "item_16_4bb3", + "target_id": "container_4", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "item_8_e9e7", + "target_id": "calc_bigmul_22cd", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "calc_bigmul_22cd", + "target_id": "calc_inv_mod_1726", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "a" + }, + { + "source_id": "item_16_0568", + "target_id": "item_8_e9e7", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "container_1", + "target_id": "item_16_0568", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "base64_encode", + "target_id": "container_4", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "fingerprint_input" + }, + { + "source_id": "calc_inv_mod_30b5", + "target_id": "calc_bigmul_22cd", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "a" + }, + { + "source_id": "num_base_convert", + "target_id": "calc_inv_mod_30b5", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "a" + }, + { + "source_id": "num_base_convert", + "target_id": "calc_bigmul_22cd", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "b" + }, + { + "source_id": "calc_bigmul_e997", + "target_id": "calc_inv_mod_1726", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "mod" + }, + { + "source_id": "calc_bigmul_e997", + "target_id": "calc_inv_mod_30b5", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "mod" + }, + { + "source_id": "terminal_2_df1b", + "target_id": "container_1", + "connection_type": "Hex_String", + "source_port": "hex_result", + "target_port": "fingerprint_input" + }, + { + "source_id": "terminal_2_b20d", + "target_id": "container_1", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "source_tool" + }, + { + "source_id": "calc_gcd", + "target_id": "terminal_2_b20d", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "num2" + }, + { + "source_id": "zip_unzip_item", + "target_id": "item_16_4bb3", + "connection_type": "Item", + "source_port": "item", + "target_port": "source_tool" + }, + { + "source_id": "item_10", + "target_id": "terminal_2_df1b", + "connection_type": "Big_Int", + "source_port": "content", + "target_port": "num1" + }, + { + "source_id": "text_xor_hex", + "target_id": "base64_encode", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "item_8_d0cf", + "target_id": "calc_gcd", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-5d659179/environment/puzzle/service.py b/tasks/agentescape-25-skeleton-5d659179/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-25-skeleton-5d659179/environment/puzzle/service.py @@ -0,0 +1,212 @@ +"""Restricted facade over the unchanged, pinned upstream puzzle handlers.""" + +import hashlib +import json +import logging +import os +import sys +import threading +import urllib.request +import uuid +from pathlib import Path + +from fastapi import FastAPI, HTTPException +from fastapi.responses import JSONResponse +from pydantic import BaseModel, ConfigDict + +sys.path.insert(0, str(Path(__file__).parent / "upstream")) +import server as upstream # noqa: E402 + +log = logging.getLogger(__name__) + + +def public(value): + """Keep upstream agent-internal template hints out of the public response.""" + if isinstance(value, dict): + return {k: public(v) for k, v in value.items() if not k.startswith("_")} + if isinstance(value, list): + return [public(v) for v in value] + return value + + +class Action(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + action: str + node_id: str | None = None + arguments: dict | None = None + answer: str | None = None + + +class Episode: + def __init__( + self, scenario_path, max_actions=500, evidence_dir=None, worker_url=None + ): + if max_actions < 1: + raise ValueError("max_actions must be positive") + self.lock = threading.Lock() + self.max_actions = max_actions + self.count = 0 + self.won = False + self.reason = None + self.evidence_dir = Path(evidence_dir) if evidence_dir else None + self.scenario_hash = hashlib.sha256( + Path(scenario_path).read_bytes() + ).hexdigest() + self.initial = upstream.reset_case( + case_file_path=str(scenario_path), session_id=uuid.uuid4().hex + ) + self.case_id = self.initial["case_id"] + # Hide source file paths; no upstream reset/stats/routes are mounted. + self.initial.pop("message", None) + simulator = upstream.SIMULATORS[self.case_id] + if worker_url is None: + + def no_worker(_inputs): + self.reason = "infrastructure_error" + raise RuntimeError("isolated Python worker is not configured") + + simulator.tool_map["code_py_exec"] = no_worker + else: + + def execute_python(inputs): + request = urllib.request.Request( + worker_url + "/execute", + data=json.dumps({"code": inputs.get("code", "")}).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=12) as response: + result = json.load(response) + if not isinstance(result.get("stdout"), str): + raise RuntimeError("Invalid Python worker response") + return result + except Exception: + self.reason = "infrastructure_error" + raise + + simulator.tool_map["code_py_exec"] = execute_python + self.save() + if self.evidence_dir is not None: + (self.evidence_dir / "trace.jsonl").touch() + + def state(self): + return { + "scenario_sha256": self.scenario_hash, + "action_count": self.count, + "max_actions": self.max_actions, + "won": self.won, + "termination_reason": self.reason, + } + + def save(self, action=None, result=None): + if self.evidence_dir is None: + return + self.evidence_dir.mkdir(parents=True, exist_ok=True) + target = self.evidence_dir / "outcome.json" + temp = target.with_suffix(".tmp") + temp.write_text(json.dumps(self.state())) + temp.replace(target) + if action is not None: + with (self.evidence_dir / "trace.jsonl").open("a") as handle: + handle.write( + json.dumps( + {"index": self.count, "action": action, "result": result} + ) + + "\n" + ) + + def dispatch(self, payload): + with self.lock: + if self.reason is not None: + return { + "ok": False, + "error": "Episode has ended", + "episode": self.state(), + } + self.count += 1 + try: + action = Action.model_validate(payload) + if action.action == "submit_answer" and action.answer is not None: + result = upstream.submit_answer( + self.case_id, upstream.SubmitAnswerRequest(answer=action.answer) + ) + if result.get("is_win"): + self.won = True + self.reason = "success" + elif action.action == "investigate" and action.node_id is not None: + result = upstream.investigate( + self.case_id, + upstream.InvestigateRequest(node_id=action.node_id), + ) + elif ( + action.action in ("tool_call", "use_item") + and action.node_id is not None + ): + request_type, handler = ( + (upstream.ToolCallRequest, upstream.tool_call) + if action.action == "tool_call" + else (upstream.UseItemRequest, upstream.use_item) + ) + result = handler( + self.case_id, + request_type( + node_id=action.node_id, arguments=action.arguments or {} + ), + ) + else: + result = { + "ok": False, + "error": "Unknown action or missing action parameter", + } + except HTTPException as exc: + result = {"ok": False, "error": exc.detail} + except ValueError: + result = {"ok": False, "error": "Malformed action"} + except Exception: + log.exception("Puzzle service failure") + self.reason = "infrastructure_error" + self.save() + raise + if self.reason is None and self.count >= self.max_actions: + self.reason = "action_budget_exhausted" + result = public(result) + result["episode"] = self.state() + self.save(payload, result) + return result + + +def create_app( + scenario_path=None, max_actions=None, evidence_dir=None, worker_url=None +): + episode = Episode( + scenario_path or os.environ["SCENARIO_PATH"], + max_actions or int(os.environ.get("MAX_ACTIONS", "500")), + evidence_dir if evidence_dir is not None else os.environ.get("EVIDENCE_DIR"), + worker_url if worker_url is not None else os.environ.get("WORKER_URL"), + ) + app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) + app.state.episode = episode + + @app.get("/health") + def health(): + return {"ok": True} + + @app.get("/observation") + def observation(): + return {**public(episode.initial), "episode": episode.state()} + + @app.get("/state") + def state(): + return episode.state() + + @app.post("/action") + def action(payload: dict): + try: + return episode.dispatch(payload) + except Exception: + return JSONResponse( + status_code=503, + content={"ok": False, "error": "Puzzle infrastructure failure"}, + ) + + return app diff --git a/tasks/agentescape-25-skeleton-5d659179/environment/puzzle/upstream/models.py b/tasks/agentescape-25-skeleton-5d659179/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-25-skeleton-5d659179/environment/puzzle/upstream/models.py @@ -0,0 +1,108 @@ +from enum import Enum +from typing import List, Dict, Any, Optional +from pydantic import BaseModel, Field + +# 1. 细粒度接口类型定义 +class InterfaceType(str, Enum): + ''' + BIG_INT + TEXT_GENERIC + HEX_STRING + FILE_ID + HEX_STRING_KEY_AES + HEX_STRING_IV_AES + CODE_PYTHON + HIDDEN_ITEM + ITEM + ''' + # --- 基础类型 --- + TEXT_GENERIC = "Text_Generic" + BIG_INT = "Big_Int" + + # --- 编码/格式化字符串 --- + HEX_STRING = "Hex_String" # 通用 Hex + + # --- 特定用途的 Hex 字符串 (用于精确匹配) --- + HEX_STRING_KEY_AES = "Hex_String_Key_AES" + HEX_STRING_IV_AES = "Hex_String_IV_AES" + + # --- 文件类型 --- + FILE_ID = "File_Id" + + # --- 代码/脚本 --- + CODE_PYTHON = "Code_Python" + + # --- 实体交互类型 (严格命名) --- + ITEM = "Item" # 主动掉落接口 (Tool -> Item) + HIDDEN_ITEM = "Hidden_Item" # 被动掉落接口 (Item -> Item) + +# 3. 端口定义 +class Port(BaseModel): + name: str + type: InterfaceType + description: str + +# 4. 统一节点定义 (融合工具和物品) +class Node(BaseModel): + id: str + name: str + description: str + type: str # "Tool" or "Item" + + # 接口定义 + inputs: List[Port] = [] + outputs: List[Port] = [] + + # 状态字段 + content: Optional[Any] = None # 物品有内容,工具为None + if_success: Optional[bool] = None # 工具初始为False,物品为None + initial_visible: bool = False + + # 运行时状态 (Server维护) + is_revealed: bool = False + + # 标记该 Tool 节点是否有待触发的 HIDDEN_ITEM 掉落 + # 当 Tool 按照 golden_input 正确执行且有 HIDDEN_ITEM 输出边时设为 True + # 在 investigate 该 Tool 时触发掉落并重置为 False + has_hidden_item_ready: bool = False + + # 初始输入值 (metadata.initial_values.init_inputs,用于渐进式暴露判断) + init_input_values: Dict[str, Any] = {} + + # Golden 输入值 (nodes[].inputs[].value,用于评测验证) + golden_input_values: Dict[str, Any] = {} + + # Golden 输出值 (nodes[].outputs[].value,用于评测验证和 Item 节点的 content) + golden_output_values: Dict[str, Any] = {} + + # 实际获得的输出值历史 (工具每次执行后实际返回的输出列表,用于渐进式暴露判断) + # 格式: List[Dict[str, Any]],每个元素是一次执行的输出字典 + actual_outputs_history: List[Dict[str, Any]] = [] + + # 逻辑规则 (用于终端机等复杂物品) + logic_rules: Optional[Dict[str, Any]] = None + + def copy(self, **kwargs): + """Helper to create a copy with updated fields.""" + data = self.dict() + data.update(kwargs) + return Node(**data) + +# 5. 边定义 (拓扑结构) +class Edge(BaseModel): + source_id: str + target_id: str + connection_type: InterfaceType # 直接使用 InterfaceType + # 如果是 Data_Flow,指定端口对应关系 + source_port: Optional[str] = None + target_port: Optional[str] = None + +# 6. 完整图定义 +class GraphScenario(BaseModel): + case_id: str + title: str + intro_narrative: str + nodes: Dict[str, Node] + edges: List[Edge] + difficulty: int + win_node_id: str # 标记哪个节点是最终目标(通常是一个提交工具或最终物品) diff --git a/tasks/agentescape-25-skeleton-5d659179/environment/puzzle/upstream/server.py b/tasks/agentescape-25-skeleton-5d659179/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-25-skeleton-5d659179/environment/puzzle/upstream/server.py @@ -0,0 +1,1490 @@ +import json +import os +import time +import logging +import random +from pathlib import Path +from typing import Dict, Any, List, Optional +from datetime import datetime +from collections import defaultdict +from fastapi import FastAPI, HTTPException, Request +from fastapi.responses import JSONResponse +from fastapi.middleware.cors import CORSMiddleware +from pydantic import BaseModel, Field + +from models import GraphScenario, Node, InterfaceType +# from generator import ScenarioGenerator +from simulator import ToolSimulator +import uvicorn + +# 配置日志 +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler('server.log'), + logging.StreamHandler() + ] +) +logger = logging.getLogger(__name__) + +app = FastAPI( + title="AgentEscapeBench Universal Server", + version="1.0.0", + description="Industrial-grade evaluation server for escape room AI agents" +) + +# 添加 CORS 支持 +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# In-memory State +SCENARIOS: Dict[str, GraphScenario] = {} +SIMULATORS: Dict[str, ToolSimulator] = {} # case_id -> ToolSimulator +RAW_NODES_DATA: Dict[str, Dict[str, Any]] = {} # case_id -> node_id -> raw node data (for template_id) +FILE_METADATA: Dict[str, Dict[str, Any]] = {} # case_id -> metadata (for initial_values access) + +# Performance monitoring +STATS: Dict[str, Any] = { + "total_requests": 0, + "successful_requests": 0, + "failed_requests": 0, + "tool_calls": defaultdict(int), + "investigates": defaultdict(int), + "use_items": defaultdict(int), + "case_loads": 0, + "start_time": datetime.now() +} + +# Request timing middleware +@app.middleware("http") +async def add_process_time_header(request: Request, call_next): + start_time = time.time() + STATS["total_requests"] += 1 + + try: + response = await call_next(request) + STATS["successful_requests"] += 1 + process_time = time.time() - start_time + response.headers["X-Process-Time"] = str(process_time) + logger.info(f"{request.method} {request.url.path} - {response.status_code} - {process_time:.3f}s") + return response + except Exception as e: + STATS["failed_requests"] += 1 + logger.error(f"{request.method} {request.url.path} - Error: {str(e)}") + raise + +# Exception handler +@app.exception_handler(Exception) +async def global_exception_handler(request: Request, exc: Exception): + logger.error(f"Unhandled exception: {exc}", exc_info=True) + return JSONResponse( + status_code=500, + content={ + "ok": False, + "error": "Internal server error", + "detail": str(exc) if os.getenv("DEBUG") else "An error occurred" + } + ) + +# Health check endpoint +@app.get("/health") +def health_check(): + """健康检查端点""" + uptime = (datetime.now() - STATS["start_time"]).total_seconds() + return { + "status": "healthy", + "version": "1.0.0", + "uptime_seconds": uptime, + "loaded_cases": len(SCENARIOS), + "stats": { + "total_requests": STATS["total_requests"], + "successful_requests": STATS["successful_requests"], + "failed_requests": STATS["failed_requests"], + "success_rate": STATS["successful_requests"] / max(STATS["total_requests"], 1) + } + } + +# Statistics endpoint +@app.get("/stats") +def get_stats(): + """获取详细统计信息""" + return { + "stats": STATS, + "loaded_cases": list(SCENARIOS.keys()), + "uptime": str(datetime.now() - STATS["start_time"]) + } + +def _apply_progressive_reveal_at_init(scenario: GraphScenario): + """ + 在初始化时应用渐进式暴露机制(基于ITEM/HIDDEN_ITEM边) + + 新逻辑: + - 如果一个节点没有 ITEM/HIDDEN_ITEM 类型的入边,它就是初始可见的 + - 如果一个节点有 ITEM/HIDDEN_ITEM 类型的入边,它初始不可见,需要等待上游触发 + + Args: + scenario: 场景对象 + """ + # 收集所有有 ITEM/HIDDEN_ITEM 入边的节点 + nodes_with_item_edges = set() + for edge in scenario.edges: + if edge.connection_type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + nodes_with_item_edges.add(edge.target_id) + + logger.info(f"Nodes with ITEM/HIDDEN_ITEM incoming edges: {nodes_with_item_edges}") + + # 设置初始可见性:没有 ITEM/HIDDEN_ITEM 入边的节点初始可见 + initially_visible_count = 0 + for node_id, node in scenario.nodes.items(): + if node_id not in nodes_with_item_edges: + node.is_revealed = True + initially_visible_count += 1 + logger.info(f"Initial visible (no ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + else: + node.is_revealed = False + logger.debug(f"Initial hidden (has ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + + logger.info(f"Progressive reveal initialized: {initially_visible_count}/{len(scenario.nodes)} nodes initially visible") + + +def _check_inputs_match_golden(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> bool: + """ + 检查实际输入参数是否与 golden inputs 完全匹配 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + True 表示所有 golden inputs 都存在且值匹配 + """ + if not golden_inputs: + return True # 如果没有 golden inputs,认为匹配 + + for key, expected_value in golden_inputs.items(): + actual_value = arguments.get(key) + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) != str(expected_value): + logger.debug(f"Input mismatch for '{key}': expected '{expected_value}', got '{actual_value}'") + return False + + return True + + +def _get_parameter_validation_feedback(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> Dict[str, Any]: + """ + 对源头节点的参数进行详细验证,返回验证反馈 + + 注意:不返回期望值(expected),避免泄漏答案 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + 包含验证结果的字典: + - all_correct: bool - 所有参数是否正确 + - correct_params: List[str] - 正确的参数名列表 + - incorrect_params: List[str] - 错误的参数名列表(不包含期望值) + """ + if not golden_inputs: + return { + "all_correct": True, + "correct_params": [], + "incorrect_params": [] + } + + correct_params = [] + incorrect_params = [] + + for key, actual_value in arguments.items(): + # 只对用户实际提交的参数给反馈,未提交的参数不评价 + if key not in golden_inputs: + continue # 该参数不在 golden 中,跳过(如 _golden_inputs 等内部参数) + expected_value = golden_inputs[key] + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) == str(expected_value): + correct_params.append(key) + else: + # 只记录参数名,不包含期望值,避免泄漏答案 + incorrect_params.append(key) + + # all_correct:用户提交的所有参数都正确,且覆盖了全部 golden 参数 + all_provided_correct = len(incorrect_params) == 0 + all_golden_covered = all(k in arguments for k in golden_inputs) + return { + "all_correct": all_provided_correct and all_golden_covered, + "correct_params": correct_params, + "incorrect_params": incorrect_params + } + + +def _is_source_node(node_id: str, scenario: GraphScenario) -> bool: + """ + 判断节点是否是源头节点(完全没有任何入边的节点) + + 源头节点定义: + - 没有任何类型的入边(包括 DATA、ITEM、HIDDEN_ITEM) + - 即没有任何上游节点 + + Args: + node_id: 节点ID + scenario: 场景对象 + + Returns: + True 表示是源头节点 + """ + for edge in scenario.edges: + if edge.target_id == node_id: + # 只要有任何入边,就不是源头节点 + return False + + return True + + +def _check_and_reveal_ready_nodes(scenario: GraphScenario, recent_outputs: Dict[str, Any], source_node_id: str) -> List[Dict[str, Any]]: + """ + 检查并释放参数齐全的隐藏节点(渐进式暴露机制) + + 核心逻辑: + 1. 维护"可见值集合":包含所有被测模型当前可以看到的值 + - init_inputs 的值(初始可见) + - 工具执行后的实际输出值(运行时获得) + - 可见 Item 的输出值 + 2. 检查隐藏节点:该节点的所有 golden_input 值是否都在可见值集合中 + 3. 如果是,则释放该节点 + + Args: + scenario: 场景对象 + recent_outputs: 最近执行的工具的输出 + source_node_id: 刚执行的工具节点ID + + Returns: + 新释放的节点列表 + """ + newly_revealed = [] + + # 构建"可见值集合"(Set of visible values) + # 存储格式:set of values (转为字符串) + visible_values = set() + + # 1. 添加有意义的 init_inputs 值到可见值集合 + # Item 的 init_inputs 不应该加入,因为它们在密室中完全用不到 + for node_id, node in scenario.nodes.items(): + # 跳过源头 Item 节点(没有入边的 Item) + if node.type == "Item": + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,跳过其 init_inputs + continue + + # 添加其他节点的 init_inputs + for port_name, init_value in node.init_input_values.items(): + if init_value: + visible_values.add(str(init_value)) + + # 2. 添加已执行工具的所有历史输出值 + for node_id, node in scenario.nodes.items(): + if node.type == "Tool" and node.if_success and node.actual_outputs_history: + # 遍历所有历史执行记录 + for output_dict in node.actual_outputs_history: + for output_port_name, output_value in output_dict.items(): + if output_value: + visible_values.add(str(output_value)) + + # 3. 添加已被 investigate 的 Item 的 golden 输出值 + # 注意:Item 可见不等于其输出值可见,需要 investigate 后才能获得 + # 这里我们使用 actual_outputs_history 来标记 Item 是否已被 investigate + for node_id, node in scenario.nodes.items(): + if node.type == "Item" and node.is_revealed and node.actual_outputs_history: + # Item 通常只会被 investigate 一次,但为了一致性也使用历史列表 + for output_dict in node.actual_outputs_history: + for port_name, port_value in output_dict.items(): + if port_value: + visible_values.add(str(port_value)) + + # 遍历所有隐藏的节点,检查其 golden_input 是否都在可见值集合中 + for node_id, node in scenario.nodes.items(): + # 跳过已可见的节点 + if node.is_revealed: + continue + + # 只检查工具节点(物品节点由 ITEM 输出触发) + if node.type != "Tool": + continue + + # 检查该节点的所有 golden_input 值是否都在可见值集合中 + all_inputs_ready = True + missing_values = [] + + for input_port_name, golden_input_value in node.golden_input_values.items(): + # 检查这个 golden 值是否在可见值集合中 + if str(golden_input_value) not in visible_values: + all_inputs_ready = False + missing_values.append(f"{input_port_name}={golden_input_value}") + + # 如果所有 golden_input 值都在可见值集合中,释放该节点 + if all_inputs_ready and len(node.golden_input_values) > 0: + logger.info(f"All golden inputs ready for {node_id}: {list(node.golden_input_values.values())}") + + # 如果所有输入都齐全,释放该节点 + if all_inputs_ready: + node.is_revealed = True + + # 构建节点信息返回给模型 + node_info = { + "id": node.id, + "type": node.type, + "can_investigate": True, + "hint": "This tool's input parameters are now complete, you can use investigate to view detailed information" + } + + # if node.name: + # node_info["name"] = node.name + if node.description: + node_info["description"] = node.description + + newly_revealed.append(node_info) + logger.info(f"Progressive reveal: {node_id} is now ready (all inputs satisfied)") + + return newly_revealed + + +def _initialize_node_values(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]): + """ + Initialize node state and load values from port value fields. + 应用渐进式暴露机制:初始时只显示参数齐全的节点(源头节点) + + 重要区分: + 1. input_values: 只加载 metadata.initial_values 中的 init_inputs(真正的初始值) + 2. output_values: 加载 nodes[].outputs[].value(golden 输出,用于验证) + """ + # 第一步:加载所有节点的值,并将所有节点初始设为隐藏 + initial_values = metadata.get('initial_values', {}) + + for node_id, node in scenario.nodes.items(): + # 忽略 initial_visible 字段,初始全部隐藏 + # 由渐进式暴露机制根据参数齐全情况决定是否显示 + node.is_revealed = False + + if node.type == "Tool": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + elif node.type == "Item": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + + # 从 JSON 加载值 + if node_id in raw_nodes_data: + node_data = raw_nodes_data[node_id] # node_data是json文件中nodes中的字典 + + # 【重要】只加载 metadata.initial_values 中的初始输入值 + if node_id in initial_values: + init_data = initial_values[node_id] + # 加载初始输入值(用于渐进式暴露判断) + for port_name, port_value in init_data.get('init_inputs', {}).items(): + node.init_input_values[port_name] = port_value + + # 【评测用】加载 golden 输入值(用于验证模型传入的参数是否正确) + for input_port_data in node_data.get('inputs', []): + if 'value' in input_port_data: + node.golden_input_values[input_port_data['name']] = input_port_data['value'] + + # 【评测用】加载 golden 输出值(用于验证工具调用是否正确,以及 Item 节点的 content) + for output_port_data in node_data.get('outputs', []): + if 'value' in output_port_data: + node.golden_output_values[output_port_data['name']] = output_port_data['value'] + + # For Items, set content from golden_output_values + if node.type == "Item" and node.golden_output_values: + # Item 的 content 是其第一个 golden 输出值 + node.content = list(node.golden_output_values.values())[0] + + # 第二步:应用渐进式暴露机制 + # 检查所有节点,根据参数齐全情况释放源头节点(工具 + Item) + _apply_progressive_reveal_at_init(scenario) + +def _build_node_info(node: Node, raw_nodes_data: Dict[str, Any]) -> Dict[str, Any]: + """ + 构建节点信息(工具或物品) + + Args: + node: 节点对象 + raw_nodes_data: 原始节点数据(用于获取 template_id 等) + + Returns: + 节点信息字典 + """ + if node.type == "Tool": + # 过滤掉输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口) + # 这些端口仅用于控制掉落机制,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + tool_info = { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Tool", + "inputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.inputs if p.type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]], + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id(工具的标准名称) + if node.id in raw_nodes_data: + node_data = raw_nodes_data[node.id] + template_id = node_data.get('template_id') + if template_id: + tool_info['template_id'] = template_id + + return tool_info + + elif node.type == "Item": + return { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Item" + } + + else: + return { + "id": node.id, + # "name": node.name, + "type": node.type + } + +def _get_initial_observation(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]) -> Dict[str, Any]: + """ + Generate initial observation for the agent (what they see when entering the room). + + 策略: + - Tools: 只显示名称和描述,不显示接口定义。需要 investigate 才能获得详细接口信息。 + - Items: 只显示存在,不显示内容。需要 investigate 才能获得内容值。 + - init_inputs: 作为"可用信息"告诉模型,这些是可以用作工具参数的初始值。 + - init_outputs: 不告诉模型(这些是答案,需要模型通过调用工具获得)。 + """ + available_entities = [] # 统一的实体列表(Tools 和 Items) + available_information = [] # 可用的初始信息(来自 init_inputs) + + # 从 metadata.initial_values 提取 init_inputs 作为可用信息 + # 只提供值本身,不透露这些值对应哪个节点的哪个参数,让模型自己推理 + # 注意:跳过源头 Item(没有入边的 Item)的 init_inputs,因为它们在密室中完全用不到 + initial_values = metadata.get('initial_values', {}) + # initial_values字段的格式 + # "initial_values": { + # "terminal_1": { + # "init_inputs": {}, + # "init_outputs": { + # "text_output": "System initialization complete.", + # "hex_output": "48656c6c6f20576f726c64", + # "item_dispenser": "掉落了一张纸条,上面写着“请勿随意触摸终端”" + # } + # } + # } + for node_id, init_data in initial_values.items(): + # 获取节点信息,判断是否为源头 Item + node = scenario.nodes.get(node_id) + if node and node.type == "Item": + # 检查是否为源头 Item(没有入边) + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,检查是否有 init_inputs + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 有 init_inputs,需要暴露这些参数 + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + # 处理完后跳过后续的通用逻辑 + continue + + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 为每个 init_input 值创建一个信息条目(不包含 source_node 和 parameter 信息) + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + + for node in scenario.nodes.values(): + if node.is_revealed: + # Tools: 只显示基本信息,提示可以 investigate 查看详细接口 + if node.type == "Tool": + tool_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Tool", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the tool's detailed interface information for calling" + } + # 只在 name 非空时添加 + # if node.name: + # tool_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_info["description"] = node.description + + available_entities.append(tool_info) + + # Items: 只显示基本信息,提示可以 investigate 查看内容 + elif node.type == "Item": + item_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Item", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the item's content" + } + # 只在 name 非空时添加 + # if node.name: + # item_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + item_info["description"] = node.description + + available_entities.append(item_info) + + return { + "narrative": scenario.intro_narrative, + "available_entities": available_entities, # 使用统一的实体列表 + "available_information": available_information, # 可用的初始信息(只包含 init_inputs) + "win_node_id": scenario.win_node_id # 胜利节点ID,让模型知道需要关注哪个节点 + } + +@app.post("/env/reset") +def reset_case(case_id: str = None, case_file_path: str = None, session_id: str = None): + """Loads a specific case from file and resets it. + + Args: + case_id: Optional case ID for resetting an existing case + case_file_path: Path to case file for loading a new case + session_id: Optional session ID to ensure isolation between concurrent evaluations + """ + logger.info(f"Reset request - case_id: {case_id}, case_file_path: {case_file_path}, session_id: {session_id}") + STATS["case_loads"] += 1 + + if case_file_path: + if not os.path.exists(case_file_path): + logger.error(f"Case file not found: {case_file_path}") + raise HTTPException(status_code=404, detail=f"File not found: {case_file_path}") + try: + with open(case_file_path, "r", encoding="utf-8") as f: + file_data = json.load(f) + + # 转换格式:从 DAG executor 生成的格式转换为 GraphScenario 格式 + # 1. 提取 metadata + metadata = file_data.get('metadata', {}) + + # 2. 生成 case_id, title, intro_narrative + # 【修复】为每个评测会话生成唯一的 case_id,防止并发评测时状态污染 + base_name = os.path.basename(case_file_path).replace('.json', '').replace('_full', '').replace('_full2', '') + + if session_id: + # 如果提供了 session_id,使用它来确保唯一性 + case_id = f"{base_name}_{session_id}" + else: + # 否则使用时间戳和随机数确保唯一性 + unique_suffix = f"{int(time.time() * 1000)}_{random.randint(1000, 9999)}" + case_id = f"{base_name}_{unique_suffix}" + + file_data['case_id'] = case_id + logger.info(f"Generated unique case_id: {case_id} (base: {base_name}, session: {session_id})") + + if 'title' not in file_data: + file_data['title'] = f"Escape Room: {file_data['case_id']}" + + if 'intro_narrative' not in file_data: # 目前的json文件中已经有了intro_narrative字段,不会使用下面一行的内容,而是使用每个评测问题的json文件中的对应字段 + 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]".' + + # 3. 转换 nodes 列表为字典(DAG executor 生成的文件中 nodes 是列表格式) + nodes_dict = {} + for node_data in file_data['nodes']: + nodes_dict[node_data['id']] = node_data # 这里的id是template_id之后可能添加一个后缀 + file_data['nodes'] = nodes_dict # 把列表转成一个字典 + + # 4. 添加缺失的字段 + if 'difficulty' not in file_data: + file_data['difficulty'] = metadata.get('total_nodes', 5) + + if 'win_node_id' not in file_data: + file_data['win_node_id'] = metadata.get('win_node_id', '') + + scenario = GraphScenario(**file_data) + + # Extract raw nodes data for template_id access + # nodes 已经在上面转换为字典格式 + raw_nodes_data = file_data.get('nodes', {}) + RAW_NODES_DATA[scenario.case_id] = raw_nodes_data + + # Store metadata for initial values access + FILE_METADATA[scenario.case_id] = metadata + + logger.info(f"Successfully parsed case file: {scenario.case_id}, nodes: {len(scenario.nodes)}, edges: {len(scenario.edges)}") + except Exception as e: + logger.error(f"Failed to load case file: {str(e)}", exc_info=True) + raise HTTPException(status_code=500, detail=f"Failed to load case file: {str(e)}") + + # Initialize node state and load values + _initialize_node_values(scenario, raw_nodes_data, metadata) + + SCENARIOS[scenario.case_id] = scenario + simulator = ToolSimulator() + SIMULATORS[scenario.case_id] = simulator + + 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'])}") + + # 生成初始观察信息(进入密室后看到的环境) + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + ''' + initial_observation的格式: + { + "narrative": scenario.intro_narrative, + "available_entities": available_entities # 使用统一的实体列表 + "available_information": available_information # 可用的初始信息(只包含 init_inputs) + } + ''' + + return { + "ok": True, + "message": f"Case loaded from {case_file_path}", + "case_id": scenario.case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果没有提供 case_file_path,但提供了 case_id,则尝试从内存重置 + if case_id and case_id in SCENARIOS: + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + metadata = FILE_METADATA.get(case_id, {}) + + # Reset dynamic fields and re-apply progressive reveal + # 重新初始化节点状态(包括渐进式暴露) + _initialize_node_values(scenario, raw_nodes_data, metadata) + + 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'])}") + + # 生成初始观察信息 + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + + return { + "ok": True, + "message": f"Case {case_id} reset.", + "case_id": case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果既没有 case_file_path,也没有在内存中找到,返回错误 + raise HTTPException( + status_code=400, + detail="Must provide case_file_path to load a new case, or use case_id to reset an existing case." + ) + +class InvestigateRequest(BaseModel): + node_id: str + +@app.post("/env/{case_id}/investigate") +def investigate(case_id: str, req: InvestigateRequest): + """ + Investigates a Tool or Item to reveal detailed information. + + - For Tools: Returns detailed interface information (inputs/outputs) needed to call the tool + - For Items: Returns content value and triggers hidden item drops + """ + logger.info(f"Investigate request - case_id: {case_id}, node_id: {req.node_id}") + STATS["investigates"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + node = scenario.nodes[req.node_id] + + if not node.is_revealed: + logger.warning(f"Attempt to investigate hidden node: {req.node_id}") + return {"ok": False, "error": "Node is not visible yet."} + + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + newly_revealed = [] + + # 处理 Tool 的 investigate + if node.type == "Tool": + logger.info(f"Investigating tool: {req.node_id}") + + # 返回工具的详细接口信息 + # id 字段使用 node.id(节点唯一标识),agent 用这个字段识别和调用具体的节点 + # template_id 是工具类型标识符,Agent 内部用于判断工具特性(如 terminal 类工具参数可选) + # 注意:只过滤输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口),这些端口仅用于控制掉落,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + # 【端口上游依赖提示 & 初始值直接给出】 + # 针对参数语义模糊(全为数字类型)的工具,在 investigate 返回信息中标注 + # 哪个输入端口来自哪个上游节点(upstream_from)。 + # 对于所有工具:若该节点不是纯源头节点(有任意数据流入边), + # 且某个端口没有上游入边(值来自初始可见参数),则直接给出该端口的 golden input 值。 + AMBIGUOUS_TOOLS = { + "num_base_convert", "calc_modexp", "calc_modexp_int", + "calc_inv_mod", "calc_inv_mod_int", "crypto_rsa_decrypt_hex", "geo_haversine" + } + # Terminal 类工具自带参数对错反馈机制,玩家/模型可自行试错, + # 无需在 investigate 时直接暴露 init_value + SELF_FEEDBACK_TOOLS = { + "terminal_1", "terminal_2", + "Logic Terminal", "Math Terminal", "Encryption Terminal", "Sequence Terminal" + } + _template_id_for_hint = raw_nodes_data.get(node.id, {}).get("template_id", "") + # 构建数据流入边映射(对所有工具):{target_port -> (source_node_id, source_port)} + _upstream_map = {} + for _edge in scenario.edges: + if (_edge.target_id == node.id + and _edge.connection_type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM] + and _edge.target_port is not None): + _upstream_map[_edge.target_port] = (_edge.source_id, _edge.source_port) + # 判断该节点是否有任意数据流入边(即不是纯源头节点) + _has_any_upstream = len(_upstream_map) > 0 + # 判断该节点是否有任意入边(包括 ITEM/HIDDEN_ITEM 掉落边) + # 有任意入边(含掉落边)但无数据流入边的节点,其输入来自初始可见参数,应直接给出 + _has_any_edge = any(_edge.target_id == node.id for _edge in scenario.edges) + # 构建 inputs 列表 + _inputs_list = [] + for p in node.inputs: + if p.type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + continue + port_dict = {"name": p.name, "type": p.type, "description": p.description} + if p.name in _upstream_map: + # 该端口有上游数据流依赖,且属于语义模糊工具 → 标注来源 + if _template_id_for_hint in AMBIGUOUS_TOOLS: + src_node_id, src_port = _upstream_map[p.name] + port_dict["upstream_from"] = f"{src_node_id}.{src_port}" if src_port else src_node_id + elif _has_any_edge and _template_id_for_hint not in SELF_FEEDBACK_TOOLS: + # 该节点有任意入边,但此端口没有数据流入边 → 值来自初始可见参数,直接给出 + # 排除自带反馈机制的 terminal 类工具(它们通过执行结果反馈对错,无需提前暴露参数值) + golden_val = node.golden_input_values.get(p.name) + if golden_val is not None: + port_dict["init_value"] = golden_val + _inputs_list.append(port_dict) + + tool_details = { + "id": node.id, # 节点 ID,用于唯一标识和调用这个具体节点 + "type": "Tool", + "inputs": _inputs_list, + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id 用于 Agent 内部判断工具类型(不会展示给被测模型) + if node.id in raw_nodes_data: + template_id = raw_nodes_data[node.id].get('template_id') + if template_id: + tool_details["_template_id"] = template_id # 使用下划线前缀标记为内部字段 + + # 只在 name 非空时添加 + # if node.name: + # tool_details["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_details["description"] = node.description + + # 添加 narrative 字段(如果存在) + if node.id in raw_nodes_data: + narrative = raw_nodes_data[node.id].get('narrative') + if narrative: + tool_details['narrative'] = narrative + + # 不再返回 init_values,避免泄漏答案 + # investigate 只应该返回工具的接口定义,不应该暴露初始值 + + # 【新增】检查该 Tool 是否有待触发的 HIDDEN_ITEM 掉落 + # 如果该工具已按照 golden_input 正确执行,且有 HIDDEN_ITEM 输出边,则触发掉落 + if node.has_hidden_item_ready: + logger.info(f"Tool has HIDDEN_ITEM ready - triggering passive drop for: {req.node_id}") + + # 遍历该工具的所有 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + # 重置标志,已经触发过了,避免重复 + node.has_hidden_item_ready = False + + logger.info(f"Tool investigation successful - node: {req.node_id}, revealed: {len(newly_revealed)}") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Tool", + "details": tool_details + } + + # 如果有新掉落的节点,添加到响应中 + if newly_revealed: + result["newly_revealed"] = newly_revealed + + return result + + # 处理 Item 的 investigate + elif node.type == "Item": + logger.info(f"Investigating item: {req.node_id}") + + # 【第一步】检查该 Item 是否有需要参数的输入端口 + # 如果有,且尚未通过 use_item 验证,则不返回内容,只返回参数要求 + required_inputs = [] + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + inputs_info = raw_node.get('inputs', []) + required_inputs = [ + { + "name": inp.get("name"), + "type": inp.get("type"), + "description": inp.get("description", "") + } + for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + # 如果有 required_inputs 且尚未通过 use_item 验证(if_success == False) + # 则不返回内容,只返回参数要求提示 + if required_inputs and not node.if_success: + logger.info(f"Item has required inputs and not yet unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "required_inputs": required_inputs + } + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + param_names = ', '.join([inp['name'] for inp in required_inputs]) + 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}" + + return result + + # 【新增】如果有 required_inputs 且已经通过 use_item 验证(if_success == True) + # 则返回提示:该节点已经被成功解决 + if required_inputs and node.if_success: + logger.info(f"Item has required inputs and already unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "message": "This item has already been successfully unlocked by you." + } + return result + + # 【第二步】该 Item 没有 required_inputs 或已通过验证,返回内容 + # 1. 返回 Item 的 golden_output_values(即 Item 的内容) + # 注意:某些 Item 仅用于触发 HIDDEN_ITEM 掉落,没有实际内容 + has_actual_content = bool(node.golden_output_values) or node.content is not None + content = node.golden_output_values if node.golden_output_values else node.content + + # 【关键】将 golden_output_values 追加到 actual_outputs_history,标记该 Item 已被 investigate + # 这样在渐进式暴露时,这些值才会被加入可见值集合 + # 即使是空字典(仅触发 HIDDEN_ITEM 的 Item),也要记录,以便渐进式暴露逻辑知道该 Item 已被调查 + if node.golden_output_values is not None: + node.actual_outputs_history.append(dict(node.golden_output_values)) + + # 2. Trigger Hidden Item Drops (Passive Drop) + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + logger.info(f"Item investigation successful - node: {req.node_id}, has_content: {has_actual_content}, revealed: {len(newly_revealed)}") + + # 【渐进式暴露】旧机制(基于 golden_input)已禁用 + # 现在完全由 ITEM/HIDDEN_ITEM 边触发控制节点可见性 + # 上面的 HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, node.golden_output_values or {}, node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # logger.info(f"Progressive reveal after Item investigate: {len(progressive_revealed)} nodes now ready") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Item" + } + + # 只在有实际内容时才添加 content 字段 + # 对于仅触发 HIDDEN_ITEM 掉落的 Item,不返回 content 字段,避免返回 None 或空字典让模型困惑 + if has_actual_content: + result["content"] = content + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型通过 investigate 获得内容后,需要自己识别这是否是胜利字符串 + + return result + + else: + logger.warning(f"Attempt to investigate unknown node type: {req.node_id} (type: {node.type})") + return {"ok": False, "error": f"Cannot investigate node type: {node.type}"} + +class ToolCallRequest(BaseModel): + node_id: str # 使用 node_id 精确指定要调用的节点 + arguments: Dict[str, Any] + +@app.post("/env/{case_id}/tool_call") +def tool_call(case_id: str, req: ToolCallRequest): + """Executes a tool and triggers item drops.""" + logger.info(f"Tool call request - case_id: {case_id}, node_id: {req.node_id}, args: {list(req.arguments.keys())}") + STATS["tool_calls"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + + # 通过 node_id 精确查找节点 + node_id = req.node_id + if node_id not in scenario.nodes: + logger.error(f"Node not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + tool_node = scenario.nodes[node_id] + + if not tool_node: + logger.error(f"Tool not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Tool not found") + + if not tool_node.is_revealed: + logger.warning(f"Attempt to call hidden tool: {node_id}") + return {"ok": False, "error": "Tool is not visible yet."} + + if tool_node.type != "Tool": + logger.warning(f"Attempt to call non-tool node: {node_id} (type: {tool_node.type})") + return {"ok": False, "error": "Only tools can be called."} + + # 1. Execute Tool (Real Execution via Simulator) + simulator = SIMULATORS[case_id] + + # Get tool name from template_id if available, otherwise use node name + tool_name = tool_node.name + if case_id in RAW_NODES_DATA and node_id in RAW_NODES_DATA[case_id]: + template_id = RAW_NODES_DATA[case_id][node_id].get('template_id') + if template_id: + tool_name = template_id + + # 文件处理工具和 Terminal 需要验证输入并返回预先计算的输出 + # 传递节点的实际输入输出值(从 DAG 执行后填充的数据) + tool_arguments = dict(req.arguments) # Make a copy + + # 传递节点的 golden values(从 JSON 的 inputs[].value 和 outputs[].value 加载) + # 用于在评测阶段验证被测模型传入的参数是否正确 + if tool_node.golden_input_values: + tool_arguments['_golden_inputs'] = tool_node.golden_input_values + if tool_node.golden_output_values: + tool_arguments['_golden_outputs'] = tool_node.golden_output_values + + logger.debug(f"Executing tool {tool_name} (node: {tool_node.name}) with args {tool_arguments}") + + try: + output_values = simulator.execute(tool_name, tool_arguments) + logger.info(f"Tool invoked - {tool_name}: {list(output_values.keys())}") + except Exception as e: + logger.error(f"Tool execution failed - {tool_name}: {str(e)}", exc_info=True) + return {"ok": False, "error": f"Tool execution failed: {str(e)}"} + + # 检查验证结果(精细化错误反馈) + validation = output_values.pop("_validation", {"valid": True}) + + if not validation["valid"]: + # 根据错误类型构造友好的错误消息 + error_type = validation.get("error_type") + + if error_type == "missing_required": + missing = validation.get("missing_params", []) + error_msg = f"Error: Missing required parameters {', '.join(missing)}" + + elif error_type == "type_error": + param = validation.get("param_name") + message = validation.get("message", "Parameter type error") + error_msg = f"Error: {message}" + + elif error_type == "incomplete_optional": + provided = validation.get("provided_params", []) + missing = validation.get("missing_params", []) + error_msg = ( + f"Hint: You provided some parameters ({', '.join(provided)}), " + f"but may also need: {', '.join(missing)}.\n" + f"Trying to provide these parameters together might yield better results." + ) + + elif error_type == "value_mismatch": + param = validation.get("param_name") + hint = validation.get("hint", "Parameter value may be incorrect") + error_msg = f"Hint: {hint}.\nPlease check if this parameter value meets the requirements." + + else: + error_msg = validation.get("hint") or validation.get("message", "Parameter validation failed") + + logger.info(f"Tool validation failed - {tool_name}: {error_type}") + return { + "ok": False, + "error": error_msg, + "error_type": error_type + } + + # Simulate success + tool_node.if_success = True + + # 【关键】将本次执行的输出值追加到历史列表(用于渐进式暴露判断) + # 每次调用都会记录,不会覆盖之前的执行结果 + tool_node.actual_outputs_history.append(dict(output_values)) + + # 2. 检查是否应该触发掉落(只有输入参数正确时才掉落) + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, tool_node.golden_input_values) + + newly_revealed = [] + investigate_hints = [] # 提示模型哪些节点可以 investigate 来发现隐藏内容 + + if inputs_match_golden: + logger.info(f"✓ Tool inputs match golden - node: {node_id}, triggering drops") + + # 检查该工具是否有 ITEM 或 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == tool_node.id: + target_node = scenario.nodes[edge.target_id] + + # ITEM 边:立即掉落(主动掉落) + if edge.connection_type == InterfaceType.ITEM: + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from {node_id})") + + # HIDDEN_ITEM 边:不立即掉落,标记并提示(被动掉落) + elif edge.connection_type == InterfaceType.HIDDEN_ITEM: + # 标记该工具有待触发的 HIDDEN_ITEM 掉落 + tool_node.has_hidden_item_ready = True + + # 提示模型可以 investigate 这个工具来发现隐藏内容 + hint_info = { + "tool_id": tool_node.id, + "hint": f"Tool '{tool_node.id}' seems to hide something, try investigating it to discover more information" + } + # if tool_node.name: + # hint_info["tool_name"] = tool_node.name + + investigate_hints.append(hint_info) + logger.info(f"HIDDEN_ITEM ready: {tool_node.id} -> {target_node.id} (will drop on investigate)") + else: + logger.info(f"✗ Tool inputs do NOT match golden - node: {node_id}, no drops triggered") + + response = { + "ok": True, + "message": "Tool invoked", + "output_values": output_values # Return raw outputs to Agent + } + + # 【新增】对源头节点进行参数验证反馈 + # 源头节点:没有数据流入边的节点,这些节点的参数需要模型自己推理 + # 验证模型使用的参数是否正确,并提供明确的反馈 + if _is_source_node(node_id, scenario) and tool_node.golden_input_values: + validation_feedback = _get_parameter_validation_feedback(req.arguments, tool_node.golden_input_values) + + if validation_feedback["all_correct"]: + # 用户提交了全部 golden 参数且全部正确 + response["parameter_feedback"] = { + "status": "correct", + "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." + } + logger.info(f"✓ Source node parameters all correct - node: {node_id}") + elif validation_feedback["incorrect_params"]: + # 有提交了但值错误的参数,只对这些参数给出反馈 + incorrect_list = [] + for param_name in validation_feedback["incorrect_params"]: + incorrect_list.append(f" - Parameter '{param_name}' is incorrect") + + correct_info = "" + if validation_feedback["correct_params"]: + correct_info = f"\n✓ Correct parameters: {', '.join(validation_feedback['correct_params'])}" + + response["parameter_feedback"] = { + "status": "incorrect", + "message": ( + f"⚠️ Some parameters are incorrect:\n" + + "\n".join(incorrect_list) + + correct_info + + 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." + ), + "incorrect_params": validation_feedback["incorrect_params"], + "correct_params": validation_feedback["correct_params"] + } + logger.info(f"✗ Source node parameters incorrect - node: {node_id}, incorrect: {validation_feedback['incorrect_params']}") + # else: 部分提交且全部正确 → 不给任何 parameter_feedback,避免对未提交的参数发表意见 + + # 检查工具调用是否完全正确(输出与 golden outputs 匹配) + # 用于给模型正向反馈,让它知道这个工具已经正确调用过,避免重复调用 + # 注意:只有当输出完全匹配时才标记为 correct,不会在错误时提供具体错误信息 + # if tool_node.golden_output_values and output_values: + # is_correct = True + # for port_name, expected_value in tool_node.golden_output_values.items(): + # actual_value = output_values.get(port_name) + # if str(actual_value) != str(expected_value): + # is_correct = False + # break + + # if is_correct: + # response["tool_call_correct"] = True + # logger.info(f"✓ Tool called with correct result - node: {node_id}") + + # 只在有新内容掉落时才返回 newly_revealed + if newly_revealed: + response["newly_revealed"] = newly_revealed + + # 添加 investigate 提示(对于有待触发 HIDDEN_ITEM 掉落的工具) + if investigate_hints: + response["investigate_hints"] = investigate_hints + + # 3. 渐进式暴露机制 - 现在完全由 ITEM/HIDDEN_ITEM 边控制 + # 旧机制(基于 golden_input 检查)已被禁用 + # 新机制中,节点的可见性只由 ITEM/HIDDEN_ITEM 边触发决定 + # 上面的 ITEM/HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, output_values, tool_node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # response["newly_revealed"] = newly_revealed + # logger.info(f"Progressive reveal: {len(progressive_revealed)} nodes now ready") + + # Check if this is the win node + if node_id == scenario.win_node_id: + # 验证输出值是否等于预期的胜利值 + # 从节点的 golden_output_values 中获取预期值(在 _initialize_node_values 时从 JSON 加载) + expected_outputs = tool_node.golden_output_values + + # 检查实际输出是否与预期输出匹配 + is_correct = False + victory_string = None + mismatch_info = [] + + if expected_outputs and output_values: + # 检查每个预期输出端口的值是否匹配 + is_correct = True + for port_name, expected_value in expected_outputs.items(): + actual_value = output_values.get(port_name) + if actual_value != expected_value: + is_correct = False + mismatch_info.append(f"Port '{port_name}': expected '{expected_value}', actual '{actual_value}'") + logger.warning(f"Win node output mismatch - port: {port_name}, expected: {expected_value}, actual: {actual_value}") + + # 如果所有输出都匹配,使用第一个输出作为胜利字符串 + if is_correct and output_values: + victory_string = list(output_values.values())[0] + else: + logger.warning(f"Win node called but missing output values - expected: {expected_outputs}, actual: {output_values}") + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型调用工具获得输出后,需要自己识别这是否是胜利字符串并提交 + if is_correct: + logger.info(f"🎯 Win node called with correct output - case: {case_id}, node: {node_id}, victory: {victory_string}") + else: + logger.info(f"❌ Win node called with incorrect output - case: {case_id}, node: {node_id}") + + return response + +class UseItemRequest(BaseModel): + node_id: str = Field(..., description="The ID of the Item node to use (must be Item type)") + arguments: Dict[str, Any] = Field(default_factory=dict, description="Input arguments to provide to the item") + +@app.post("/env/{case_id}/use_item") +def use_item(case_id: str, req: UseItemRequest): + """ + Use an Item node by providing input arguments. + + This is specifically for Item nodes that require parameters to be "unlocked" or "activated", + such as containers that need a password/fingerprint. + + - Validates that the node is of type Item + - Checks if provided arguments match the item's golden_input_values + - If match: triggers ITEM-type edge drops and returns the item's content + - If not match: returns error message + """ + logger.info(f"Use item request - case_id: {case_id}, node_id: {req.node_id}, args: {req.arguments}") + STATS["use_items"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + item_node = scenario.nodes[req.node_id] + + if not item_node.is_revealed: + logger.warning(f"Attempt to use hidden item: {req.node_id}") + return {"ok": False, "error": "Item is not visible yet."} + + if item_node.type != "Item": + logger.warning(f"Attempt to use non-item node: {req.node_id} (type: {item_node.type})") + return {"ok": False, "error": "Only Item nodes can be used with use_item. Tools should be called with tool_call."} + + # 【新增】检查该 Item 是否已经被成功解锁 + # 如果已经被正确使用过,直接返回成功提示 + if item_node.if_success: + logger.info(f"Item already unlocked, returning success message: {req.node_id}") + return { + "ok": True, + "message": "This item has already been successfully unlocked by you." + } + + # 检查该 Item 是否真的需要通过 use_item 提供参数 + # 只有当 Item 有非 Item/Hidden_Item 类型的输入时,才应该使用 use_item + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + non_hidden_inputs = [ + inp for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + if not non_hidden_inputs: + # 该 Item 不需要参数,应该只使用 investigate + logger.warning(f"Attempt to use_item on a node that doesn't require parameters: {req.node_id}") + return { + "ok": False, + "error": "This item does not require parameters. Please use investigate to examine the item directly." + } + + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, item_node.golden_input_values) + + if not inputs_match_golden: + logger.info(f"✗ Item inputs do NOT match golden - node: {req.node_id}") + # 提供更详细的错误信息,帮助 Agent 理解问题 + # 只显示非 Item/Hidden_Item 类型的参数(Hidden_Item 由系统自动处理) + expected_params = [] + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + expected_params = [ + inp.get("name") for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + provided_params = list(req.arguments.keys()) if req.arguments else [] + + # 检查参数名是否匹配 + if set(expected_params) == set(provided_params): + # 参数名正确但值不匹配 - 不泄漏正确的值 + error_msg = f"Parameter names are correct, but the parameter values are incorrect. Please try using different parameter values." + else: + error_msg = f"Parameter names do not match. Expected parameter names: {expected_params}, you provided: {provided_params}." + + return { + "ok": False, + "error": error_msg + } + + logger.info(f"✓ Item inputs match golden - node: {req.node_id}, activating item") + + # 标记该 Item 已被正确使用 + item_node.if_success = True + + # 将 golden_output_values 追加到 actual_outputs_history + if item_node.golden_output_values: + item_node.actual_outputs_history.append(dict(item_node.golden_output_values)) + + # 触发 ITEM 类型边的掉落 + newly_revealed = [] + for edge in scenario.edges: + if edge.source_id == item_node.id and edge.connection_type == InterfaceType.ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from use_item on {req.node_id})") + + # 检查是否为 Win Node + win_node_id = scenario.win_node_id + is_win_node = (req.node_id == win_node_id) + + # 构建返回结果 + result = { + "ok": True, + "message": "Item used successfully.", + "content": item_node.golden_output_values if item_node.golden_output_values else None + } + + # 获取 narrative(如果存在) + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + narrative = raw_nodes_data[req.node_id].get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 如果是 Win Node,只记录日志 + if is_win_node: + logger.info(f"Win node (Item) unlocked via use_item - case: {case_id}, node: {req.node_id}") + + return result + + +class SubmitAnswerRequest(BaseModel): + answer: str = Field(..., description="The victory string to submit") + +@app.post("/env/{case_id}/submit_answer") +def submit_answer(case_id: str, req: SubmitAnswerRequest): + """ + 提交答案接口 + 被测模型在获得胜利字符串提示后,需要调用此接口提交答案 + """ + logger.info(f"Submit answer request - case_id: {case_id}, answer: {req.answer}") + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + + # 获取 win_node 的 golden_output_values + if not scenario.win_node_id: + logger.error(f"No win node defined for case: {case_id}") + return { + "ok": False, + "error": "This case has no victory node defined" + } + + win_node = scenario.nodes.get(scenario.win_node_id) + if not win_node: + logger.error(f"Win node not found: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node does not exist" + } + + # 获取正确的胜利字符串(取第一个 golden_output_value) + if win_node.golden_output_values: + correct_answer = list(win_node.golden_output_values.values())[0] + else: + logger.error(f"Win node has no golden_output_values: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node has no correct answer" + } + + # 验证提交的答案 + if req.answer == correct_answer: + logger.info(f"🎉 CORRECT ANSWER SUBMITTED - case: {case_id}, answer: {req.answer}") + return { + "ok": True, + "is_win": True, + "victory_message": f"🎉 Congratulations on successfully escaping the room! Your answer is correct: {req.answer}" + } + else: + logger.info(f"❌ INCORRECT ANSWER SUBMITTED - case: {case_id}, submitted: {req.answer}, correct: {correct_answer}") + return { + "ok": True, + "is_win": False, + "error": f"The submitted answer is incorrect. You submitted: {req.answer}" + } + +if __name__ == "__main__": + + uvicorn.run(app, host="0.0.0.0", port=8000) \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-5d659179/environment/puzzle/upstream/simulator.py b/tasks/agentescape-25-skeleton-5d659179/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-25-skeleton-5d659179/environment/puzzle/upstream/simulator.py @@ -0,0 +1,2911 @@ +import hashlib +import hmac +import base64 +import binascii +import zlib +import json +import uuid +import math +import re +from typing import Dict, Any, List + +class ToolSimulator: + def __init__(self): + """工具模拟器 + + 文件处理工具(zip_unzip, zip_unzip_file, zip_unzip_item, json_get, csv_query, + regex_search, graph_shortest_path)不需要真实文件系统。 + 这些工具只验证输入参数,然后返回预先初始化好的 golden_outputs。 + """ + self.tool_map = { + # 数论 + "calc_bigmul": self.calc_bigmul, + "calc_modexp": self.calc_modexp, + "calc_modexp_int": self.calc_modexp_int, + "calc_gcd": self.calc_gcd, + "calc_gcd_int": self.calc_gcd_int, + "calc_inv_mod": self.calc_inv_mod, + "calc_inv_mod_int": self.calc_inv_mod_int, + + # 哈希 + "hash_sha256": self.hash_sha256, + "hash_md5": self.hash_md5, + "hmac_sha256": self.hmac_sha256, + + # 编码 + "base64_decode": self.base64_decode, + "base64_encode": self.base64_encode, + "hex_decode": self.hex_decode, + "hex_encode": self.hex_encode, + "zlib_inflate": self.zlib_inflate, + "zlib_deflate": self.zlib_deflate, + + # 文件 + "zip_unzip": self.zip_unzip, + "zip_unzip_file": self.zip_unzip_file, + "zip_unzip_item": self.zip_unzip_item, + "regex_search": self.regex_search, + "json_get": self.json_get, + "csv_query": self.csv_query, + "code_py_exec": self.code_py_exec, + + # 图 + "graph_shortest_path": self.graph_shortest_path, + + # 加解密 (简化模拟) + "crypto_aes_cbc_decrypt": self.crypto_aes_cbc_decrypt, + "crypto_rsa_decrypt_hex": self.crypto_rsa_decrypt_hex, + + # 其他 + "num_base_convert": self.num_base_convert, + "time_convert": self.time_convert, + "checksum_crc32": self.checksum_crc32, + "geo_haversine": self.geo_haversine, + "otp_totp_generate": self.otp_totp_generate, + "unicode_norm": self.unicode_norm, + "text_bidi_sanitize": self.text_bidi_sanitize, + "text_xor_hex": self.text_xor_hex, + "text_rotN": self.text_rotN, + "luhn_check": self.luhn_check, + "iban_validate": self.iban_validate, + + # 物理 + "matter_synthesizer": self.matter_synthesizer, + + # 终端机 + "terminal_1": self.terminal_1, + "terminal_2": self.terminal_2, + "Logic Terminal": self.logic_terminal, + "Math Terminal": self.math_terminal, + "Encryption Terminal": self.crypt_terminal, + "Sequence Terminal": self.sequence_terminal + } + + def execute(self, tool_name: str, inputs: Dict[str, Any]) -> Dict[str, Any]: + if tool_name not in self.tool_map: + # Fallback for unknown tools: return dummy outputs based on expected output types + # This should ideally not happen if all tools are implemented + return {} + + try: + return self.tool_map[tool_name](inputs) + except Exception as e: + print(f"Error executing {tool_name}: {e}") + # Return empty or error indication? For generation, we might want to fail hard or return dummy. + # For now, return dummy to keep flow going, but log error. + return {} + + # --- Implementations --- + + def calc_bigmul(self, inputs): + # Check if required parameters are present + if "a" not in inputs or "b" not in inputs: + raise ValueError("Missing required parameters 'a' and/or 'b'") + + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + return {"product": str(a * b)} + except (ValueError, TypeError) as e: + raise ValueError(f"Failed to convert parameters to integers: {str(e)}") + + def calc_modexp(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + try: + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if isinstance(base, str): + base = int(base) + elif not isinstance(base, int): + raise ValueError("Parameter 'base' must be a string or integer") + + if isinstance(exp, str): + exp = int(exp) + elif not isinstance(exp, int): + raise ValueError("Parameter 'exp' must be a string or integer") + + if isinstance(mod, str): + mod = int(mod) + elif not isinstance(mod, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": str(pow(base, exp, mod))} + + def calc_modexp_int(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["base"], int): + raise ValueError("Parameter 'base' must be an integer") + if not isinstance(inputs["exp"], int): + raise ValueError("Parameter 'exp' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": pow(base, exp, mod)} + + def calc_gcd(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + # 计算 GCD 并返回字符串格式(符合 Big_Int 输出类型) + result = math.gcd(a, b) + return {"gcd": str(result)} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def calc_gcd_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["b"], int): + raise ValueError("Parameter 'b' must be an integer") + + # 获取参数 + a = inputs["a"] + b = inputs["b"] + + return {"gcd": math.gcd(a, b)} + + def calc_inv_mod(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + m = inputs["mod"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(m, str): + m = int(m) + elif not isinstance(m, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": str(pow(a, -1, m))} + except ValueError as e: + # 模逆不存在时,返回一个特殊值(用于数据传递) + # 在 DAG 生成阶段,这允许数据流继续 + return {"inv": str(a)} + + def calc_inv_mod_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + a = inputs["a"] + m = inputs["mod"] + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": pow(a, -1, m)} + except ValueError as e: + raise ValueError(f"Modular inverse does not exist: {str(e)}") + + def hash_sha256(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.sha256(text.encode()).hexdigest()} + + def hash_md5(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.md5(text.encode()).hexdigest()} + + def hmac_sha256(self, inputs): + # 参数检查 + if "hex_key" not in inputs: + raise ValueError("Missing required parameter: hex_key") + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["hex_key"], str): + raise ValueError("Parameter 'hex_key' must be a string") + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + try: + key = bytes.fromhex(inputs["hex_key"]) + text = inputs["text"].encode() + return {"hex": hmac.new(key, text, hashlib.sha256).hexdigest()} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def base64_decode(self, inputs): + # 参数检查 + if "data" not in inputs: + raise ValueError("Missing required parameter: data") + + # 类型检查 + if not isinstance(inputs["data"], str): + raise ValueError("Parameter 'data' must be a string") + + data = inputs["data"] + try: + return {"bytes_hex": binascii.hexlify(base64.b64decode(data)).decode()} + except Exception as e: + raise ValueError(f"Base64 decode error: {str(e)}") + + def base64_encode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"b64": base64.b64encode(bytes.fromhex(hex_data)).decode()} + except Exception as e: + raise ValueError(f"Base64 encode error: {str(e)}") + + def hex_decode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"text": bytes.fromhex(hex_data).decode('utf-8', errors='ignore')} + except Exception as e: + raise ValueError(f"Hex decode error: {str(e)}") + + def hex_encode(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + try: + return {"hex": text.encode().hex()} + except Exception as e: + raise ValueError(f"Hex encode error: {str(e)}") + + + # 到此处实现已经更新 + + def zlib_inflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("Parameter 'hex' must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("Missing required parameter: hex") + + try: + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空字符串 + if not hex_data: + raise ValueError("Empty hex string provided") + + # 检查十六进制字符串的有效性 + if len(hex_data) % 2 != 0: + raise ValueError("Hex string must have even length") + + # 检查是否只包含有效的十六进制字符 + if not all(c in '0123456789abcdefABCDEF' for c in hex_data): + raise ValueError("Invalid hex string provided") + + # 尝试解压缩 + return {"text": zlib.decompress(bytes.fromhex(hex_data)).decode('utf-8')} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hex string provided") from e + raise ValueError(f"Invalid zlib data: {e}") from e + except Exception as e: + raise RuntimeError(f"Failed to inflate data: {e}") from e + + def zlib_deflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("Parameter 'text' must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("Missing required parameter: text") + + try: + # 压缩文本 + return {"hex": zlib.compress(text.encode('utf-8')).hex()} + except Exception as e: + raise RuntimeError(f"Failed to deflate data: {e}") from e + + # --- File Operations --- + + def zip_unzip(self, inputs): + """ZIP 解压工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"files": golden_outputs.get("files", "")} + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return {"files": golden_outputs.get("files", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "files" in golden_outputs: + # 验证必需参数 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 检查类型 + if has_zip_id and not isinstance(zip_id, str): + return {"error": "Parameter 'zip_id' must be a string type"} + if has_password and not isinstance(password, str): + return {"error": "Parameter 'password' must be a string type"} + + # 验证输入是否与预期匹配 + if golden_inputs: + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return {"files": golden_outputs["files"]} + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + # 没有golden_inputs但有golden_outputs,直接返回输出 + return {"files": golden_outputs["files"]} + + # 如果没有预期输出,返回空结果 + return {"files": ""} + + def regex_search(self, inputs): + """正则搜索工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"matches": golden_outputs.get("matches", "[]")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "matches" in golden_outputs: + # 提取实际参数 + pattern = inputs.get("pattern") + file_id = inputs.get("file_id") + text = inputs.get("text") + + # 1. 检查必需参数 + if pattern is None: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["pattern"], + "message": "Missing required parameter 'pattern'" + } + } + + # 类型检查 + if not isinstance(pattern, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "pattern", + "message": "Parameter 'pattern' must be a string type" + } + } + if file_id is not None and not isinstance(file_id, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if text is not None and not isinstance(text, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "text", + "message": "Parameter 'text' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合 + provided_params = {} + if pattern is not None: + provided_params["pattern"] = pattern + if file_id is not None: + provided_params["file_id"] = file_id + if text is not None: + provided_params["text"] = text + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数(关键改进) + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_pattern = golden_inputs.get("pattern") + expected_file_id = golden_inputs.get("file_id") + expected_text = golden_inputs.get("text") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_pattern is not None: + if str(pattern) != str(expected_pattern): + incorrect_params.append("pattern") + else: + correct_params.append("pattern") + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_text is not None: + if str(text) != str(expected_text): + incorrect_params.append("text") + else: + correct_params.append("text") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "matches": "[]", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "matches": golden_outputs["matches"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空列表 + return {"matches": "[]"} + + def json_get(self, inputs): + """JSON 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"values": golden_outputs.get("values", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "values" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + jsonpath = inputs.get("jsonpath", "") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if jsonpath is not None and not isinstance(jsonpath, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "jsonpath", + "message": "Parameter 'jsonpath' must be a string type" + } + } + + # 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:jsonpath有默认值"") + provided_params = {} + if file_id is not None: + provided_params["file_id"] = file_id + if jsonpath != "": + provided_params["jsonpath"] = jsonpath + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_jsonpath = golden_inputs.get("jsonpath") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_jsonpath is not None: + if str(jsonpath) != str(expected_jsonpath): + incorrect_params.append("jsonpath") + else: + correct_params.append("jsonpath") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "values": "", + "_validation": validation_info + } + + # 所有验证通过,返回正确输出 + return { + "values": golden_outputs["values"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"values": ""} + + def csv_query(self, inputs): + """CSV 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"rows": golden_outputs.get("rows", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "rows" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + select_columns = inputs.get("select", "") + where_clause = inputs.get("where", "") + + # 1. 检查必需参数 + if file_id is None: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["file_id"], + "message": "Missing required parameter 'file_id'" + } + } + + # 类型检查 + if not isinstance(file_id, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if not isinstance(select_columns, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "select", + "message": "Parameter 'select' must be a string type" + } + } + if not isinstance(where_clause, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "where", + "message": "Parameter 'where' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:select和where有默认值"") + provided_params = {"file_id": file_id} + if select_columns != "": + provided_params["select"] = select_columns + if where_clause != "": + provided_params["where"] = where_clause + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_select = golden_inputs.get("select") + expected_where = golden_inputs.get("where") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_select is not None: + if str(select_columns) != str(expected_select): + incorrect_params.append("select") + else: + correct_params.append("select") + + if expected_where is not None: + if str(where_clause) != str(expected_where): + incorrect_params.append("where") + else: + correct_params.append("where") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "rows": "", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "rows": golden_outputs["rows"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"rows": ""} + + def graph_shortest_path(self, inputs): + """图最短路径工具 + + 如果有 _golden_outputs 或 _init_outputs,验证输入并返回预设输出。 + 否则执行真实的 Dijkstra 算法。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 检查是否在预设模式中(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + if golden_outputs and "path" in golden_outputs: + # 评测阶段但没有 golden_inputs,直接返回 outputs + if not golden_inputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 评测模式:验证输入参数是否匹配 golden 值 + src = inputs.get("src") + dst = inputs.get("dst") + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + + has_src = src is not None and src != "" + has_dst = dst is not None and dst != "" + + # 验证必需参数 + if not has_src or not has_dst: + missing = [] + if not has_src: + missing.append("src") + if not has_dst: + missing.append("dst") + return {"error": "Missing required parameters: " + ", ".join(missing)} + + # 类型检查 + if not isinstance(src, str): + return {"error": "Parameter 'src' must be a string"} + if not isinstance(dst, str): + return {"error": "Parameter 'dst' must be a string"} + + # 验证输入是否匹配期望值 + if golden_inputs: + expected_src = golden_inputs.get("src") + expected_dst = golden_inputs.get("dst") + expected_file_id = golden_inputs.get("file_id") + expected_graph_data = golden_inputs.get("graph_data") + + # 收集验证结果 + incorrect_params = [] + correct_params = [] + + # 检查必需参数是否匹配 + if expected_src is not None: + if str(src) != str(expected_src): + incorrect_params.append("src") + else: + correct_params.append("src") + + if expected_dst is not None: + if str(dst) != str(expected_dst): + incorrect_params.append("dst") + else: + correct_params.append("dst") + + # 检查可选参数(如果在 expected_inputs 中定义了) + if expected_file_id is not None: + if file_id != expected_file_id: + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_graph_data is not None: + if graph_data != expected_graph_data: + incorrect_params.append("graph_data") + else: + correct_params.append("graph_data") + + # 如果有参数不正确,返回详细的反馈 + if incorrect_params: + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 验证通过,返回预设的输出 + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 获取参数(真实执行路径) + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + # Support both src/dst (interface definition) and start/end (original implementation) + start = inputs.get("src") + end = inputs.get("dst") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + raise TypeError("file_id must be a string") + + if graph_data is not None and not isinstance(graph_data, str): + raise TypeError("graph_data must be a string") + + if start is not None and not isinstance(start, str): + raise TypeError("src/start must be a string") + + if end is not None and not isinstance(end, str): + raise TypeError("dst/end must be a string") + + # 检查必需参数 + if file_id is None and graph_data is None: + raise ValueError("Either file_id or graph_data must be provided") + + if start is None: + raise ValueError("src/start parameter is required") + + if end is None: + raise ValueError("dst/end parameter is required") + + # Get graph content + content = None + if file_id is not None: + # 尝试从 VFS 获取(如果存在) + if hasattr(self, 'vfs') and file_id in self.vfs: + content = self.vfs[file_id] + else: + # VFS 不存在或文件不在 VFS 中 + # 返回一个默认的空图结果,或者抛出错误提示需要 init_outputs + raise ValueError( + f"File '{file_id}' not found. For tools that require files, " + f"please provide init_outputs in the initial_values." + ) + elif graph_data is not None: + content = graph_data + + if content is None: + content = "{}" + + try: + # Parse graph data + graph = json.loads(content) + + # 类型检查 + if not isinstance(graph, dict): + raise TypeError("Graph data must be a dictionary") + + # If graph is not in the expected format, try to extract adjacency list + if "nodes" in graph and "edges" in graph: + # 验证nodes和edges的类型 + if not isinstance(graph["nodes"], list): + raise TypeError("Nodes must be a list") + + if not isinstance(graph["edges"], list): + raise TypeError("Edges must be a list") + + # Convert from nodes/edges format to adjacency list + adjacency_list = {} + for node in graph["nodes"]: + # 验证node类型 + if not isinstance(node, dict): + raise TypeError("Each node must be a dictionary") + + # Use node ID as key, not the entire node dictionary + node_id = node.get("id", "") + if node_id: + adjacency_list[node_id] = {} + + for edge in graph["edges"]: + # 验证edge类型 + if not isinstance(edge, dict): + raise TypeError("Each edge must be a dictionary") + + u = edge["from"] + v = edge["to"] + weight = edge.get("weight", 1) # Default to unweighted + + # 类型检查 + if not isinstance(u, str): + raise TypeError("Edge 'from' must be a string") + + if not isinstance(v, str): + raise TypeError("Edge 'to' must be a string") + + if not isinstance(weight, (int, float)): + raise TypeError("Edge weight must be a number") + + if u not in adjacency_list: + adjacency_list[u] = {} + if v not in adjacency_list: + adjacency_list[v] = {} + + adjacency_list[u][v] = weight + # If undirected, add reverse edge + if not edge.get("directed", False): + adjacency_list[v][u] = weight + elif isinstance(graph, dict): + # Already in adjacency list format + adjacency_list = graph + + # 验证邻接表结构 + for node, neighbors in adjacency_list.items(): + if not isinstance(neighbors, dict): + raise TypeError("Adjacency list must be a dictionary of dictionaries") + + for neighbor, weight in neighbors.items(): + if not isinstance(weight, (int, float)): + raise TypeError("Edge weights must be numbers") + else: + raise TypeError("Graph data must be a dictionary") + + # 检查起点和终点是否为空 + if not start: + raise ValueError("Start node cannot be empty") + + if not end: + raise ValueError("End node cannot be empty") + + # 检查起点和终点是否在图中 + if start not in adjacency_list: + raise ValueError(f"Start node '{start}' not found in graph") + + if end not in adjacency_list: + raise ValueError(f"End node '{end}' not found in graph") + + # Dijkstra's algorithm implementation + import heapq + + # Initialize distances and previous nodes + distances = {node: float('infinity') for node in adjacency_list} + previous = {node: None for node in adjacency_list} + distances[start] = 0 + + # Priority queue + pq = [(0, start)] + heapq.heapify(pq) + + while pq: + current_dist, current_node = heapq.heappop(pq) + + # If we've reached the end node, we can break early + if current_node == end: + break + + # Nodes can be added multiple times to the priority queue, but we only process them once + if current_dist > distances[current_node]: + continue + + # Explore neighbors + for neighbor, weight in adjacency_list[current_node].items(): + distance = current_dist + weight + + # If a shorter path is found + if distance < distances[neighbor]: + distances[neighbor] = distance + previous[neighbor] = current_node + heapq.heappush(pq, (distance, neighbor)) + + # Reconstruct the shortest path + path = [] + current = end + while current is not None: + path.append(current) + current = previous[current] + path.reverse() # Reverse to get from start to end + + # Check if path exists + if not path or path[0] != start: + return {"path": "[]", "cost": 0} + + return { + "path": json.dumps(path), + "cost": distances[end] + } + except json.JSONDecodeError as e: + raise ValueError(f"Invalid JSON in graph data: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in graph_shortest_path: {str(e)}") + + # --- Crypto (Simplified) --- + def crypto_aes_cbc_decrypt(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 (使用模板中定义的参数名) + hex_cipher = inputs.get("hex_cipher") + hex_key = inputs.get("hex_key") + hex_iv = inputs.get("hex_iv") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + + if hex_key is not None and not isinstance(hex_key, str): + raise TypeError("hex_key must be a string") + + if hex_iv is not None and not isinstance(hex_iv, str): + raise TypeError("hex_iv must be a string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + + if hex_key is None: + raise ValueError("hex_key parameter is required") + + if hex_iv is None: + raise ValueError("hex_iv parameter is required") + + from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes + from cryptography.hazmat.backends import default_backend + from cryptography.hazmat.primitives import padding + + try: + # Convert hex strings to bytes + ciphertext = bytes.fromhex(hex_cipher) + key = bytes.fromhex(hex_key) + iv = bytes.fromhex(hex_iv) + + # Validate key length (AES-128, AES-192, AES-256) + if len(key) not in [16, 24, 32]: + raise ValueError("Invalid key length. Must be 16, 24, or 32 bytes.") + + if len(iv) != 16: + raise ValueError("Invalid IV length. Must be 16 bytes.") + + # Create cipher object + cipher = Cipher( + algorithms.AES(key), + modes.CBC(iv), + backend=default_backend() + ) + + decryptor = cipher.decryptor() + + # Decrypt the ciphertext + padded_plaintext = decryptor.update(ciphertext) + decryptor.finalize() + + # Remove PKCS7 padding + unpadder = padding.PKCS7(128).unpadder() + plaintext = unpadder.update(padded_plaintext) + unpadder.finalize() + + # Return decrypted text + return {"text": plaintext.decode('utf-8', errors='ignore')} + except ValueError as e: + if "non-hexadecimal number found in fromhex()" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher, hex_key, or hex_iv") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in crypto_aes_cbc_decrypt: {str(e)}") + + def crypto_rsa_decrypt_hex(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_cipher = inputs.get("hex_cipher") + n = inputs.get("n") + d = inputs.get("d") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + if n is not None and not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + if d is not None and not isinstance(d, (int, str)): + raise TypeError("d must be an integer or string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + if n is None: + raise ValueError("n parameter is required") + if d is None: + raise ValueError("d parameter is required") + + try: + # Convert parameters to appropriate types + cipher_int = int(hex_cipher, 16) + n_int = int(n) if isinstance(n, str) else n + d_int = int(d) if isinstance(d, str) else d + + # RSA decryption: plaintext = ciphertext^d mod n + plaintext_int = pow(cipher_int, d_int, n_int) + + # Convert result to hex and then to text + plaintext_hex = hex(plaintext_int)[2:] + + # Pad with leading zero if odd length + if len(plaintext_hex) % 2 != 0: + plaintext_hex = '0' + plaintext_hex + + # Convert hex to bytes and then to text + try: + plaintext_bytes = bytes.fromhex(plaintext_hex) + plaintext_text = plaintext_bytes.decode('utf-8', errors='ignore') + except: + # If decoding fails, return hex representation + plaintext_text = plaintext_hex + + return {"text": plaintext_text} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in crypto_rsa_decrypt_hex: {str(e)}") + + # --- Others --- + def num_base_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + s = inputs.get("s") + from_base = inputs.get("from_base") + to_base = inputs.get("to_base") + + # 类型检查 - 接受 str 或 int + if s is not None and not isinstance(s, (str, int)): + raise TypeError("s must be a string or integer") + + if from_base is not None and not isinstance(from_base, (int, str)): + raise TypeError("from_base must be an integer") + + if to_base is not None and not isinstance(to_base, (int, str)): + raise TypeError("to_base must be an integer") + + # 检查必需参数 + if s is None: + raise ValueError("s parameter is required") + + if from_base is None: + raise ValueError("from_base parameter is required") + + if to_base is None: + raise ValueError("to_base parameter is required") + + try: + # Convert to int if needed + from_base = int(from_base) if isinstance(from_base, str) else from_base + to_base = int(to_base) if isinstance(to_base, str) else to_base + s_str = str(s) + + # 验证基数范围 + if from_base < 2 or from_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + if to_base < 2 or to_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + # Convert from source base to decimal + val = int(s_str, from_base) + + # Convert from decimal to target base + if to_base == 10: + result = str(val) + elif to_base == 16: + result = hex(val)[2:] + elif to_base == 8: + result = oct(val)[2:] + elif to_base == 2: + result = bin(val)[2:] + else: + # Generic base conversion for other bases + if val == 0: + result = "0" + else: + digits = "0123456789abcdefghijklmnopqrstuvwxyz" + result = "" + n = abs(val) + while n: + result = digits[n % to_base] + result + n //= to_base + if val < 0: + result = "-" + result + + return {"str": result} + except ValueError as e: + raise ValueError(f"Invalid number format: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in num_base_convert: {str(e)}") + + def time_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iso = inputs.get("iso") + timestamp = inputs.get("timestamp") + datetime_str = inputs.get("datetime") + from_tz = inputs.get("from_tz") + to_tz = inputs.get("to_tz") + format_str = inputs.get("format") + + # 类型检查 + if iso is not None and not isinstance(iso, str): + raise TypeError("iso must be a string") + + if timestamp is not None and not isinstance(timestamp, (str, int, float)): + raise TypeError("timestamp must be a string, integer, or float") + + if datetime_str is not None and not isinstance(datetime_str, str): + raise TypeError("datetime must be a string") + + if from_tz is not None and not isinstance(from_tz, str): + raise TypeError("from_tz must be a string") + + if to_tz is not None and not isinstance(to_tz, str): + raise TypeError("to_tz must be a string") + + if format_str is not None and not isinstance(format_str, str): + raise TypeError("format must be a string") + + # 设置默认值 + if from_tz is None: + from_tz = "UTC" + + if to_tz is None: + to_tz = "UTC" + + import datetime + import pytz + + # 验证时区参数 + try: + if from_tz: + pytz.timezone(from_tz) + if to_tz: + pytz.timezone(to_tz) + except Exception: + raise ValueError("Invalid timezone provided") + + try: + # Parse input time + dt = None + + if iso is not None: + # Parse ISO 8601 format + dt = datetime.datetime.fromisoformat(iso.replace('Z', '+00:00')) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=pytz.UTC) + elif timestamp is not None: + # Parse Unix timestamp + timestamp = float(timestamp) + dt = datetime.datetime.fromtimestamp(timestamp, pytz.UTC) + elif datetime_str is not None: + # Parse datetime string + # Try common formats + formats_to_try = [ + "%Y-%m-%d %H:%M:%S", + "%Y-%m-%d %H:%M:%S.%f", + "%Y-%m-%d", + "%m/%d/%Y %H:%M:%S", + "%m/%d/%Y" + ] + + parse_success = False + for fmt in formats_to_try: + try: + dt = datetime.datetime.strptime(datetime_str, fmt) + dt = pytz.timezone(from_tz).localize(dt) + parse_success = True + break + except ValueError: + continue + + if not parse_success: + raise ValueError("Unable to parse datetime string with common formats") + else: + # 如果没有提供任何时间参数,则使用当前时间 + dt = datetime.datetime.now(pytz.UTC) + except ValueError as e: + raise ValueError(f"Error parsing time input: {str(e)}") + except Exception as e: + raise RuntimeError(f"Unexpected error parsing time input: {str(e)}") + + try: + # Convert timezone + if from_tz != to_tz: + dt = dt.astimezone(pytz.timezone(to_tz)) + + # Format outputs + result = { + "iso": dt.isoformat(), + "timestamp": str(dt.timestamp()), + "datetime": dt.strftime("%Y-%m-%d %H:%M:%S"), + "date": dt.strftime("%Y-%m-%d"), + "time": dt.strftime("%H:%M:%S"), + "timezone": to_tz + } + + # Add custom format if requested + if format_str: + try: + result["formatted"] = dt.strftime(format_str) + except ValueError as e: + raise ValueError(f"Invalid format string: {str(e)}") + + return result + except Exception as e: + raise RuntimeError(f"Error in time_convert: {str(e)}") + + def checksum_crc32(self, inputs): + import zlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("hex must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("hex parameter is required") + + try: + # 验证十六进制字符串 + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空 + if not hex_data: + raise ValueError("hex data cannot be empty") + + # 检查是否为有效的十六进制字符串 + if not all(c in "0123456789abcdefABCDEF" for c in hex_data): + raise ValueError("hex must be a valid hexadecimal string") + + # 检查长度是否为偶数 + if len(hex_data) % 2 != 0: + raise ValueError("hex must have even number of characters") + + val = zlib.crc32(bytes.fromhex(hex_data)) + # 确保 hex 输出是 8 位,前导补 0 + return {"hex": f"{val:08x}", "int": val} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in checksum_crc32: {str(e)}") + + def geo_haversine(self, inputs): + import math + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + lat1 = inputs.get("lat1") + lon1 = inputs.get("lon1") + lat2 = inputs.get("lat2") + lon2 = inputs.get("lon2") + + # 类型检查 + if lat1 is not None and not isinstance(lat1, (int, float, str)): + raise TypeError("lat1 must be a number or string") + if lon1 is not None and not isinstance(lon1, (int, float, str)): + raise TypeError("lon1 must be a number or string") + if lat2 is not None and not isinstance(lat2, (int, float, str)): + raise TypeError("lat2 must be a number or string") + if lon2 is not None and not isinstance(lon2, (int, float, str)): + raise TypeError("lon2 must be a number or string") + + # 检查必需参数 + if lat1 is None: + raise ValueError("lat1 parameter is required") + if lon1 is None: + raise ValueError("lon1 parameter is required") + if lat2 is None: + raise ValueError("lat2 parameter is required") + if lon2 is None: + raise ValueError("lon2 parameter is required") + + try: + # 转换为浮点数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(lat1, str): + lat1 = float(lat1) + elif not isinstance(lat1, (int, float)): + raise TypeError("lat1 must be a number or string") + else: + lat1 = float(lat1) + + if isinstance(lon1, str): + lon1 = float(lon1) + elif not isinstance(lon1, (int, float)): + raise TypeError("lon1 must be a number or string") + else: + lon1 = float(lon1) + + if isinstance(lat2, str): + lat2 = float(lat2) + elif not isinstance(lat2, (int, float)): + raise TypeError("lat2 must be a number or string") + else: + lat2 = float(lat2) + + if isinstance(lon2, str): + lon2 = float(lon2) + elif not isinstance(lon2, (int, float)): + raise TypeError("lon2 must be a number or string") + else: + lon2 = float(lon2) + + # Validate coordinates (approximate range check) + if not (-90 <= lat1 <= 90): + raise ValueError("lat1 must be between -90 and 90") + if not (-90 <= lat2 <= 90): + raise ValueError("lat2 must be between -90 and 90") + if not (-180 <= lon1 <= 180): + raise ValueError("lon1 must be between -180 and 180") + if not (-180 <= lon2 <= 180): + raise ValueError("lon2 must be between -180 and 180") + + # Earth radius in meters + R = 6371000 # Approximate radius of Earth + + # Convert degrees to radians + lat1_rad = math.radians(lat1) + lon1_rad = math.radians(lon1) + lat2_rad = math.radians(lat2) + lon2_rad = math.radians(lon2) + + # Calculate differences + delta_lat = lat2_rad - lat1_rad + delta_lon = lon2_rad - lon1_rad + + # Haversine formula + a = math.sin(delta_lat / 2) ** 2 + \ + math.cos(lat1_rad) * math.cos(lat2_rad) * \ + math.sin(delta_lon / 2) ** 2 + c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) + distance_m = R * c + + # Return distance in meters + return {"meters": round(distance_m, 2)} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in geo_haversine: {str(e)}") + + def otp_totp_generate(self, inputs): + import hmac + import hashlib + import base64 + import time + import struct + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + base32_secret = inputs.get("base32_secret") + step = inputs.get("step", 30) # Default to 30 seconds + digits = inputs.get("digits", 6) # Default to 6 digits + timestamp_iso = inputs.get("timestamp_iso", "") + algo = inputs.get("algo", "sha1") # Default to sha1 as current implementation only supports this + + # 类型检查 + if base32_secret is not None and not isinstance(base32_secret, str): + raise TypeError("base32_secret must be a string") + if not isinstance(step, (int, str)): + raise TypeError("step must be an integer or string") + if not isinstance(digits, (int, str)): + raise TypeError("digits must be an integer or string") + if not isinstance(timestamp_iso, str): + raise TypeError("timestamp_iso must be a string") + if not isinstance(algo, str): + raise TypeError("algo must be a string") + + # 检查必需参数 + if base32_secret is None: + raise ValueError("base32_secret parameter is required") + + try: + # Convert step and digits to appropriate types + step = int(step) + digits = int(digits) + if digits < 6 or digits > 8: + raise ValueError("Digits must be between 6 and 8") + + # Convert timestamp_iso to integer timestamp + if timestamp_iso: + import datetime + dt = datetime.datetime.fromisoformat(timestamp_iso.replace('Z', '+00:00')) + timestamp = int(dt.timestamp()) + else: + timestamp = int(time.time()) + + # Calculate counter value (T = floor(timestamp / step)) + counter = timestamp // step + + # Decode the base32 secret + # Add padding if necessary (base64 requires padding to be multiple of 8) + base32_secret = base32_secret.upper().replace(' ', '') + if len(base32_secret) % 8 != 0: + base32_secret += '=' * (8 - (len(base32_secret) % 8)) + key = base64.b32decode(base32_secret, casefold=True) + + # Calculate HMAC-SHA1 + counter_bytes = struct.pack('>Q', counter) # Big-endian 8-byte integer + hmac_hash = hmac.new(key, counter_bytes, hashlib.sha1).digest() + + # Dynamic truncation + offset = hmac_hash[-1] & 0xF + code = struct.unpack('>I', hmac_hash[offset:offset+4])[0] & 0x7FFFFFFF + + # Generate the OTP + otp = str(code % (10 ** digits)).zfill(digits) + + # Calculate remaining time until next OTP change + remaining_time = step - (timestamp % step) + + return {"totp": otp, "remaining_time": remaining_time, "time_step": step} + except ValueError as e: + if "invalid literal for int()" in str(e): + raise ValueError("step and digits must be valid integers") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in otp_totp_generate: {str(e)}") + + def unicode_norm(self, inputs): + import unicodedata + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + form = inputs.get("form", "NFC") # Default to NFC + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if form is not None and not isinstance(form, str): + raise TypeError("form must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Normalize form (NFC, NFD, NFKC, NFKD) + form = form.upper().strip() + + if form not in ['NFC', 'NFD', 'NFKC', 'NFKD']: + raise ValueError(f"Invalid normalization form: {form}. Must be one of: NFC, NFD, NFKC, NFKD") + + # Apply Unicode normalization + normalized_text = unicodedata.normalize(form, text) + + return {"text": normalized_text} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in unicode_norm: {str(e)}") + + def text_bidi_sanitize(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Bidi control characters to remove + bidi_controls = [ + '\u200E', # LEFT-TO-RIGHT MARK + '\u200F', # RIGHT-TO-LEFT MARK + '\u202A', # LEFT-TO-RIGHT EMBEDDING + '\u202B', # RIGHT-TO-LEFT EMBEDDING + '\u202C', # POP DIRECTIONAL FORMATTING + '\u202D', # LEFT-TO-RIGHT OVERRIDE + '\u202E', # RIGHT-TO-LEFT OVERRIDE + '\u2066', # LEFT-TO-RIGHT ISOLATE + '\u2067', # RIGHT-TO-LEFT ISOLATE + '\u2068', # FIRST STRONG ISOLATE + '\u2069', # POP DIRECTIONAL ISOLATE + ] + + # Remove all Bidi control characters + sanitized_text = text + for control_char in bidi_controls: + sanitized_text = sanitized_text.replace(control_char, '') + + return {"text": sanitized_text} + except Exception as e: + raise RuntimeError(f"Error in text_bidi_sanitize: {str(e)}") + + def text_xor_hex(self, inputs): + import binascii + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_a = inputs.get("hex_a") + hex_b = inputs.get("hex_b") + + # 类型检查 + if hex_a is not None and not isinstance(hex_a, str): + raise TypeError("hex_a must be a string") + if hex_b is not None and not isinstance(hex_b, str): + raise TypeError("hex_b must be a string") + + # 检查必需参数 + if hex_a is None: + raise ValueError("hex_a parameter is required") + if hex_b is None: + raise ValueError("hex_b parameter is required") + + try: + # Remove any whitespace + hex_a = hex_a.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + hex_b = hex_b.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + + # Validate hex strings + if not (all(c in "0123456789abcdefABCDEF" for c in hex_a) and len(hex_a) % 2 == 0): + raise ValueError("hex_a must be a valid hexadecimal string with even length") + if not (all(c in "0123456789abcdefABCDEF" for c in hex_b) and len(hex_b) % 2 == 0): + raise ValueError("hex_b must be a valid hexadecimal string with even length") + + # Convert hex strings to bytes + bytes_a = binascii.unhexlify(hex_a) + bytes_b = binascii.unhexlify(hex_b) + + # Make the byte arrays the same length by padding the shorter one with zeros + max_len = max(len(bytes_a), len(bytes_b)) + bytes_a = bytes_a.ljust(max_len, b'\x00') + bytes_b = bytes_b.ljust(max_len, b'\x00') + + # Perform XOR operation + result_bytes = bytes(a ^ b for a, b in zip(bytes_a, bytes_b)) + + # Convert result back to hex + result_hex = binascii.hexlify(result_bytes).decode('utf-8') + + return {"hex": result_hex} + except ValueError as e: + if "Non-hexadecimal digit found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in text_xor_hex: {str(e)}") + + def text_rotN(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + n = inputs.get("n", 0) + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + n = int(n) + except ValueError: + raise ValueError("n must be a valid integer") + + result = [] + for char in text: + if char.isupper(): + # Rotate uppercase letters + result_char = chr((ord(char) - ord('A') + n) % 26 + ord('A')) + result.append(result_char) + elif char.islower(): + # Rotate lowercase letters + result_char = chr((ord(char) - ord('a') + n) % 26 + ord('a')) + result.append(result_char) + else: + # Keep non-alphabetic characters unchanged + result.append(char) + + return {"text": ''.join(result)} + + def luhn_check(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数(支持 card_number 和 number 两个参数名) + card_number = inputs.get("number") or inputs.get("card_number") + + # 类型检查 + if card_number is not None and not isinstance(card_number, str): + raise TypeError("number must be a string") + + # 检查必需参数 + if card_number is None: + raise ValueError("number parameter is required") + + try: + # 如果输入是JSON数组或其他非数字字符串,返回该字符串本身(用于数据传递) + # 这种情况发生在DAG设计中类型不匹配时 + if card_number.startswith('[') or card_number.startswith('{'): + # 输入是JSON,直接返回原值(用于传递) + return {"valid": card_number} + + # Remove whitespace from card number + card_number = card_number.replace(" ", "").replace("-", "") + + # Check if card number is all digits + if not card_number.isdigit() or len(card_number) < 13: + return {"valid": "false"} + + # Implement Luhn algorithm + total = 0 + reverse_digits = card_number[::-1] # Reverse the number for easier processing + + for i, digit in enumerate(reverse_digits): + num = int(digit) + if i % 2 == 1: # Every second digit starting from the right (which is first in reversed string) + num *= 2 + if num > 9: + num -= 9 # Equivalent to sum of digits for 2-digit numbers + total += num + + # Check if total is divisible by 10 + is_valid = total % 10 == 0 + return {"valid": "true" if is_valid else "false"} + except Exception as e: + raise RuntimeError(f"Error in luhn_check: {str(e)}") + + def iban_validate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iban = inputs.get("iban") + + # 类型检查 + if iban is not None and not isinstance(iban, str): + raise TypeError("iban must be a string") + + # 检查必需参数 + if iban is None: + raise ValueError("iban parameter is required") + + try: + # Remove whitespace from IBAN + iban = iban.replace(" ", "") + + # Basic length and format check + if not (len(iban) >= 15 and len(iban) <= 34): + return {"valid": "False"} + + if not (iban[:2].isalpha() and iban[2:].isdigit()): + return {"valid": "False"} + + # Move first four characters to the end + rearranged = iban[4:] + iban[:4] + + # Replace letters with numbers (A=10, B=11, ..., Z=35) + numeric_iban = '' + for char in rearranged: + if char.isdigit(): + numeric_iban += char + else: + numeric_iban += str(ord(char.upper()) - ord('A') + 10) + + # Perform modulo 97 check + # Use step-by-step approach for very large numbers + remainder = 0 + for char in numeric_iban: + remainder = (remainder * 10 + int(char)) % 97 + + is_valid = remainder == 1 + return {"valid": "True" if is_valid else "False"} + except Exception as e: + raise RuntimeError(f"Error in iban_validate: {str(e)}") + + def matter_synthesizer(self, inputs): + import hashlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + blueprint = inputs.get("blueprint") + + # 类型检查 + if blueprint is not None and not isinstance(blueprint, str): + raise TypeError("blueprint must be a string") + + try: + # Get blueprint parameter as defined in interface + if blueprint is None: + blueprint = "" + + # Generate a unique item ID based on the blueprint + # This ensures the same blueprint always produces the same item + blueprint_hash = hashlib.sha256(blueprint.encode()).hexdigest()[:16] + + # Create a synthesized item with a deterministic ID based on blueprint + synthesized_item = f"synthesized_item_{blueprint_hash}" + + return {"output_slot": synthesized_item} + except Exception as e: + raise RuntimeError(f"Error in matter_synthesizer: {str(e)}") + + # --- Terminal Implementations --- + def terminal_1(self, inputs): + """ + terminal_1: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 只返回 text_output + - 只输入正确的 slot_b → 只返回 hex_output + - 同时输入正确的 slot_a 和 slot_b → 返回 item_dispenser(物品掉落) + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + # 检查哪些输入被提供了 + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值是否正确(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + expected_a = golden_inputs["slot_a"] + a_valid = str(slot_a) == str(expected_a) + + if has_b and "slot_b" in golden_inputs: + expected_b = golden_inputs["slot_b"] + b_valid = str(slot_b) == str(expected_b) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 item_dispenser + if has_a and has_b: + if a_valid and b_valid: + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 text_output + if has_a and not has_b: + if a_valid: + if "text_output" in golden_outputs: + result["text_output"] = golden_outputs["text_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 hex_output + if has_b and not has_a: + if b_valid: + if "hex_output" in golden_outputs: + result["hex_output"] = golden_outputs["hex_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def terminal_2(self, inputs): + """ + terminal_2: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 text_result + - 同时输入正确的 num1 和 num2 → 返回 hex_result 和 math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + # 检查哪些输入被提供了 + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值是否正确(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + expected_num1 = golden_inputs["num1"] + num1_valid = str(num1) == str(expected_num1) + + if has_num2 and "num2" in golden_inputs: + expected_num2 = golden_inputs["num2"] + num2_valid = str(num2) == str(expected_num2) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 hex_result 和 math_token + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 text_result + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "text_result" in golden_outputs: + result["text_result"] = golden_outputs["text_result"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def logic_terminal(self, inputs): + """ + Logic Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 返回 screen(部分输出) + - 只输入正确的 slot_b → 返回 screen 和 secondary_output + - 同时输入正确的 slot_a 和 slot_b → 返回 screen, secondary_output, item_dispenser + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + a_valid = str(slot_a) == str(golden_inputs["slot_a"]) + + if has_b and "slot_b" in golden_inputs: + b_valid = str(slot_b) == str(golden_inputs["slot_b"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出(包括 item_dispenser) + if has_a and has_b: + if a_valid and b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 screen(部分输出) + if has_a and not has_b: + if a_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 screen 和 secondary_output + if has_b and not has_a: + if b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def math_terminal(self, inputs): + """ + Math Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 result_display + - 同时输入正确的 num1 和 num2 → 返回 result_display, hex_result, math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + num1_valid = str(num1) == str(golden_inputs["num1"]) + + if has_num2 and "num2" in golden_inputs: + num2_valid = str(num2) == str(golden_inputs["num2"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 result_display + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def crypt_terminal(self, inputs): + """ + Encryption Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 plaintext → 返回 status(部分输出) + - 同时输入正确的 plaintext 和 key → 返回 status, encrypted_hex, encryption_chip + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + plaintext = inputs.get("plaintext") + key = inputs.get("key") + + has_plaintext = plaintext is not None and plaintext != "" + has_key = key is not None and key != "" + + # 验证输入值(与 golden values 比较) + plaintext_valid = False + key_valid = False + + if has_plaintext and "plaintext" in golden_inputs: + plaintext_valid = str(plaintext) == str(golden_inputs["plaintext"]) + + if has_key and "key" in golden_inputs: + key_valid = str(key) == str(golden_inputs["key"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_plaintext and has_key: + if plaintext_valid and key_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + if "encrypted_hex" in golden_outputs: + result["encrypted_hex"] = golden_outputs["encrypted_hex"] + if "encryption_chip" in golden_outputs: + result["encryption_chip"] = golden_outputs["encryption_chip"] + return result + else: + incorrect_params = [] + correct_params = [] + if not plaintext_valid: + incorrect_params.append("plaintext") + else: + correct_params.append("plaintext") + if not key_valid: + incorrect_params.append("key") + else: + correct_params.append("key") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 plaintext 且正确 → 返回 status(部分输出) + if has_plaintext and not has_key: + if plaintext_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: plaintext"} + + # 只提供 key 但没有 plaintext + if has_key and not has_plaintext: + return {"error": "plaintext required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + def sequence_terminal(self, inputs): + """ + Sequence Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 sequence → 返回 verification(部分输出) + - 同时输入正确的 sequence 和 checksum → 返回 verification, auth_code, access_card + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + sequence = inputs.get("sequence") + checksum = inputs.get("checksum") + + has_sequence = sequence is not None and sequence != "" + has_checksum = checksum is not None and checksum != "" + + # 验证输入值(与 golden values 比较) + sequence_valid = False + checksum_valid = False + + if has_sequence and "sequence" in golden_inputs: + sequence_valid = str(sequence) == str(golden_inputs["sequence"]) + + if has_checksum and "checksum" in golden_inputs: + checksum_valid = str(checksum) == str(golden_inputs["checksum"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_sequence and has_checksum: + if sequence_valid and checksum_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + if "auth_code" in golden_outputs: + result["auth_code"] = golden_outputs["auth_code"] + if "access_card" in golden_outputs: + result["access_card"] = golden_outputs["access_card"] + return result + else: + incorrect_params = [] + correct_params = [] + if not sequence_valid: + incorrect_params.append("sequence") + else: + correct_params.append("sequence") + if not checksum_valid: + incorrect_params.append("checksum") + else: + correct_params.append("checksum") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 sequence 且正确 → 返回 verification(部分输出) + if has_sequence and not has_checksum: + if sequence_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: sequence"} + + # 只提供 checksum 但没有 sequence + if has_checksum and not has_sequence: + return {"error": "sequence required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + # --- Additional File Tools --- + + def zip_unzip_file(self, inputs): + """ZIP 解压文件工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def zip_unzip_item(self, inputs): + """ZIP 解压道具工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def code_py_exec(self, inputs): + """Python 代码执行工具 + + 这是一个真实执行的工具,在 DAG 生成阶段和运行时评测阶段都会执行代码。 + 输入: code (Python 代码字符串) + 输出: stdout (标准输出,包含执行结果和错误信息) + + 特殊行为: + - 如果代码定义了 main() 函数,会自动调用它 + - 如果执行出错,错误信息会包含在 stdout 中 + """ + code = inputs.get("code", "") + + if not code: + return {"stdout": "Error: No code provided"} + + try: + # 创建一个受限的执行环境 + import io + import sys + + # 捕获标准输出和标准错误 + old_stdout = sys.stdout + old_stderr = sys.stderr + sys.stdout = io.StringIO() + sys.stderr = io.StringIO() + + # 执行代码 + exec_globals = {"__builtins__": __builtins__} + exec_locals = {} + exec(code, exec_globals, exec_locals) + + # 如果定义了 main() 函数,自动调用它 + if 'main' in exec_locals and callable(exec_locals['main']): + exec_locals['main']() + + # 获取输出 + stdout_value = sys.stdout.getvalue() + stderr_value = sys.stderr.getvalue() + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 合并 stdout 和 stderr + output = stdout_value + if stderr_value: + output += ("\n" if output else "") + f"[stderr] {stderr_value}" + + # 如果没有任何输出,尝试返回 result 变量的值 + if not output: + result = exec_locals.get("_result") or exec_locals.get("result") + if result is not None: + output = str(result) + + return {"stdout": output if output else "(no output)"} + + except Exception as e: + # 恢复标准输出和错误输出 + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 返回错误信息 + return {"stdout": f"Error: {type(e).__name__}: {str(e)}"} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-5d659179/environment/puzzle/worker.Dockerfile b/tasks/agentescape-25-skeleton-5d659179/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-25-skeleton-5d659179/environment/puzzle/worker.Dockerfile @@ -0,0 +1,8 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends libseccomp2 && rm -rf /var/lib/apt/lists/* +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY worker.py child.py /app/ +COPY upstream/simulator.py /app/simulator.py +CMD ["uvicorn", "worker:app", "--host", "0.0.0.0", "--port", "8001", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-25-skeleton-5d659179/environment/puzzle/worker.py b/tasks/agentescape-25-skeleton-5d659179/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-25-skeleton-5d659179/environment/puzzle/worker.py @@ -0,0 +1,73 @@ +"""Stateless Python tool worker. Never receives a scenario or reference values.""" + +import json +import os +import signal +import subprocess +import sys +import tempfile +import threading + +from fastapi import FastAPI +from pydantic import BaseModel, ConfigDict + +app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) +lock = threading.Lock() + + +class Execution(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + code: str + + +@app.get("/health") +def health(): + return {"ok": True} + + +@app.post("/execute") +def execute(request: Execution): + if len(request.code.encode()) > 65536: + return {"stdout": "Error: code exceeds 64 KiB limit"} + with lock, tempfile.TemporaryDirectory(prefix="escape-code-") as directory: + os.chown(directory, 65534, 65534) + with tempfile.TemporaryFile() as output: + process = subprocess.Popen( + [sys.executable, "-I", "/app/child.py"], + stdin=subprocess.PIPE, + stdout=output, + stderr=subprocess.DEVNULL, + cwd=directory, + user=65534, + group=65534, + extra_groups=[], + start_new_session=True, + env={"PATH": "/usr/local/bin:/usr/bin:/bin"}, + ) + try: + process.communicate( + json.dumps({"code": request.code}).encode(), timeout=5 + ) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + return {"stdout": "Error: Python execution timed out"} + finally: + # Also remove children still in the process group after normal exit. + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + output.seek(0) + value = output.read(65537) + if len(value) > 65536 or process.returncode != 0: + return { + "stdout": "Error: Python execution exceeded a resource limit or failed" + } + try: + result = json.loads(value) + if not isinstance(result.get("stdout"), str): + raise ValueError("Invalid worker response") + return result + except (ValueError, AttributeError): + return {"stdout": "Error: Python execution returned invalid output"} diff --git a/tasks/agentescape-25-skeleton-5d659179/instruction.md b/tasks/agentescape-25-skeleton-5d659179/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-25-skeleton-5d659179/instruction.md @@ -0,0 +1,18 @@ +# Escape the room + +Discover the victory string and submit it with `escape submit-answer`. +Start with `escape observe`. This returns the room, available information, visible entities, and victory node ID. + +Use these commands (JSON responses): + +```sh +escape investigate NODE_ID +escape tool-call NODE_ID --arguments-json '{"parameter": "value"}' +escape use-item NODE_ID --arguments-json '{"parameter": "value"}' +escape submit-answer 'exact victory string' +escape state +``` + +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. + +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. diff --git a/tasks/agentescape-25-skeleton-5d659179/solution/oracle.py b/tasks/agentescape-25-skeleton-5d659179/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-25-skeleton-5d659179/solution/oracle.py @@ -0,0 +1,133 @@ +"""Reference solver: use trusted inputs, but obtain the answer through public actions.""" + +import json +import urllib.request +from pathlib import Path + + +def http_action(base_url, payload): + request = urllib.request.Request( + base_url + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(request, timeout=30) as response: + return json.load(response) + + +def solve(scenario, act, observe): + nodes = {node["id"]: node for node in scenario["nodes"]} + visible = {entity["id"] for entity in observe["available_entities"]} + solved = set() + seen_outputs = {} + action_count = 0 + + def call(payload): + nonlocal action_count + action_count += 1 + response = act(payload) + visible.update(entity["id"] for entity in response.get("newly_revealed", [])) + if ( + response.get("episode", {}).get("termination_reason") + == "infrastructure_error" + ): + raise RuntimeError("Infrastructure failure") + return response + + for _round in range(len(nodes) + 2): + progress = False + for node_id, node in nodes.items(): + if node_id not in visible or node_id in solved: + continue + # Preserve graph order for data inputs; trigger/drop edges express visibility. + predecessors = [ + edge["source_id"] + for edge in scenario["edges"] + if edge["target_id"] == node_id + and edge["connection_type"] not in ("Item", "Hidden_Item") + ] + if any(pred not in solved for pred in predecessors): + continue + info = call({"action": "investigate", "node_id": node_id}) + if not info.get("ok"): + raise RuntimeError(f"Investigation failed: {node_id}: {info}") + inputs = { + port["name"]: port["value"] + for port in node.get("inputs", []) + if "value" in port + } + if node["type"] == "Tool": + result = call( + {"action": "tool_call", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok") or result.get("output_values", {}).get("error"): + raise RuntimeError(f"Tool failed: {node_id}: {result}") + output = result.get("output_values", {}) + if node.get("template_id") in ("terminal_1", "terminal_2"): + slots = { + port["name"]: inputs[port["name"]] + for port in node["inputs"] + if port["type"] not in ("Item", "Hidden_Item") + and port["name"] in inputs + } + triggers = { + key: value for key, value in inputs.items() if key not in slots + } + for key, value in slots.items(): + partial = call( + { + "action": "tool_call", + "node_id": node_id, + "arguments": {**triggers, key: value}, + } + ) + if partial.get("ok"): + output.update(partial.get("output_values", {})) + # HIDDEN_ITEM tool drops only occur on subsequent investigation. + call({"action": "investigate", "node_id": node_id}) + elif info.get("required_inputs"): + result = call( + {"action": "use_item", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok"): + raise RuntimeError(f"Item failed: {node_id}: {result}") + output = result.get("content") + else: + output = info.get("content") + seen_outputs[node_id] = output + solved.add(node_id) + progress = True + win_id = scenario["metadata"]["win_node_id"] + if win_id in solved and (len(solved) == len(nodes) or not progress): + outputs = seen_outputs[win_id] + if not outputs: + raise RuntimeError(f"Victory node returned no output: {win_id}") + # Upstream grades its first stored output port, independent of response order. + victory_port = next( + port["name"] for port in nodes[win_id]["outputs"] if "value" in port + ) + answer = outputs[victory_port] if isinstance(outputs, dict) else outputs + result = call({"action": "submit_answer", "answer": answer}) + if not result.get("is_win"): + raise RuntimeError(f"Victory submission failed: {result}") + return {"won": True, "actions": action_count, "visited_nodes": len(solved)} + if not progress: + raise RuntimeError(f"No progress: visible={visible}, solved={solved}") + raise RuntimeError("Reference solver exceeded graph traversal limit") + + +if __name__ == "__main__": + import os + + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000") + with urllib.request.urlopen(base + "/observation", timeout=20) as response: + observation = json.load(response) + print( + json.dumps( + solve( + json.loads(Path("/solution/scenario.json").read_text()), + lambda payload: http_action(base, payload), + observation, + ) + ) + ) diff --git a/tasks/agentescape-25-skeleton-5d659179/solution/scenario.json b/tasks/agentescape-25-skeleton-5d659179/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..27dc4c20033f5b07f5bc3e01ea93cc644b90113c --- /dev/null +++ b/tasks/agentescape-25-skeleton-5d659179/solution/scenario.json @@ -0,0 +1,1344 @@ +{ + "metadata": { + "total_nodes": 25, + "total_edges": 29, + "win_node_id": "item_5", + "win_condition": { + "type": "item_content", + "node_id": "item_5", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_5", + "terminal_2", + "num_base_convert", + "calc_bigmul_e997", + "terminal_2_df1b", + "terminal_2_b20d", + "calc_gcd", + "zip_unzip_item", + "item_10", + "text_xor_hex" + ], + "by_node": { + "item_5": { + "node_name": "", + "node_type": "Item", + "template_id": "item_5", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Hex_String_Key_AES", + "description": "AES Key" + } + } + }, + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": {}, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + } + } + }, + "num_base_convert": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "s": { + "type": "Big_Int", + "description": "Input integer value" + }, + "from_base": { + "type": "Big_Int", + "description": "From base" + }, + "to_base": { + "type": "Big_Int", + "description": "To base" + } + }, + "init_outputs": {} + }, + "calc_bigmul_e997": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First large integer" + }, + "b": { + "type": "Big_Int", + "description": "Second large integer" + } + }, + "init_outputs": {} + }, + "terminal_2_df1b": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": { + "num2": { + "type": "Big_Int", + "description": "Second Number" + } + }, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + }, + "math_token": { + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + } + }, + "terminal_2_b20d": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": { + "num1": { + "type": "Big_Int", + "description": "First Number" + } + }, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + } + } + }, + "calc_gcd": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First integer" + }, + "b": { + "type": "Big_Int", + "description": "Second integer" + } + }, + "init_outputs": {} + }, + "zip_unzip_item": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_item", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + }, + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": {} + }, + "item_10": { + "node_name": "", + "node_type": "Item", + "template_id": "item_10", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Big_Int", + "description": "The number" + } + } + }, + "text_xor_hex": { + "node_name": "Hex XOR", + "node_type": "Tool", + "template_id": "text_xor_hex", + "init_inputs": { + "hex_a": { + "type": "Hex_String", + "description": "Hex A" + }, + "hex_b": { + "type": "Hex_String", + "description": "Hex B" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "item_5": { + "init_inputs": {}, + "init_outputs": { + "content": "8d4f6a1e3b2c9d7a5f0e4b8c1a2d3e4f" + } + }, + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Initial computation resulted in this text.", + "hex_result": "0a1b2c3d4e5f" + } + }, + "num_base_convert": { + "init_inputs": { + "s": "5738291029384756382910", + "from_base": "16", + "to_base": "10" + }, + "init_outputs": {} + }, + "calc_bigmul_e997": { + "init_inputs": { + "a": "1122334455667788990011", + "b": "9988776655443322110099" + }, + "init_outputs": {} + }, + "terminal_2_df1b": { + "init_inputs": { + "num2": "3141592653589793238462" + }, + "init_outputs": { + "text_result": "The terminal has partially computed the task.", + "hex_result": "1a2b3c4d5e6f", + "math_token": "A completely useless piece of math token." + } + }, + "terminal_2_b20d": { + "init_inputs": { + "num1": "2718281828459045235360" + }, + "init_outputs": { + "text_result": "Terminal b20d output completed.", + "hex_result": "2a3b4c5d6e7f", + "math_token": "Yet another useless object for inventory." + } + }, + "calc_gcd": { + "init_inputs": { + "a": "1234567890123456789012", + "b": "9876543210987654321098" + }, + "init_outputs": {} + }, + "zip_unzip_item": { + "init_inputs": { + "zip_id": "data_package_1.zip", + "password": "password_qweasd123" + }, + "init_outputs": {} + }, + "item_10": { + "init_inputs": {}, + "init_outputs": { + "content": "5555566666777778888899" + } + }, + "text_xor_hex": { + "init_inputs": { + "hex_a": "1234567890abcdef", + "hex_b": "fedcba0987654321" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You awaken in the hidden sanctuary of the Grand Wizard Aldous, a master of dimensional magic who has mysteriously vanished. The room is filled with esoteric artifacts, glowing crystals, and strange mechanical devices pulsing with magical energy. A central pedestal displays a message etched in glowing runes: 'Only those who can harmonize the celestial energies and decode the arcane secrets may unlock the ultimate treasure chest and inherit my legacy.' You must carefully study the ancient tools, magical terminals, and celestial sundials scattered around the room to find the correct path of activation. Your final objective is to obtain the master key hidden deep within the ultimate treasure chest. The secrets of the universe await.", + "narrative_style": "fantasy" + }, + "nodes": [ + { + "id": "item_5", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_5", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hex_String_Key_AES", + "description": "AES Key", + "value": "8d4f6a1e3b2c9d7a5f0e4b8c1a2d3e4f" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "8d4f6a1e3b2c9d7a5f0e4b8c1a2d3e4f" + } + }, + "narrative": "The ultimate treasure chest." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A mystical scroll." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "An ancient sundial." + }, + { + "id": "terminal_2", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "11117963973852212532249898887473187004922609035256064" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "11117963973852212532249898887473187004922609035256064" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Initial computation resulted in this text." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "0a1b2c3d4e5f" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "Initial computation resulted in this text.", + "hex_result": "0a1b2c3d4e5f" + } + }, + "narrative": "This is the grand wizard's terminal. It requires inputs from the astral inverter and the celestial inverter." + }, + { + "id": "calc_inv_mod", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "11117963973852212532249898887473187004922609035256064" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "123609122923875681191513219127763133199780146827391935564497792119308993534565038025920637144942048772096" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "11117963973852212532249898887473187004922609035256064" + } + ], + "narrative": "This is the astral inverter. It requires inputs from the celestial inverter and the cosmos multiplier." + }, + { + "id": "calc_inv_mod_1726", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "11117963973852212532249898887473187004922609035256064" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "11210748210374098778011361778402556553221089" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "11117963973852212532249898887473187004922609035256064" + } + ], + "narrative": "This is the celestial inverter. It requires inputs from the aether multiplier and the void multiplier." + }, + { + "id": "calc_bigmul", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "11117963973852212532249898887473187004922609035256064" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "11117963973852212532249898887473187004922609035256064" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "123609122923875681191513219127763133199780146827391935564497792119308993534565038025920637144942048772096" + } + ], + "narrative": "This is the cosmos multiplier. It requires inputs from the celestial inverter and the aether multiplier." + }, + { + "id": "item_16_31d8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A cosmic sundial." + }, + { + "id": "container_4", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_4", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Text_Generic", + "description": "Fingerprint Hash", + "value": "7OjscRfOjs4=" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is the sealed reliquary. It requires input from the runic transcriber." + }, + { + "id": "calc_bigmul_22cd", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "105441756310544318115358992" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "105441756310544318115358992" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "11117963973852212532249898887473187004922609035256064" + } + ], + "narrative": "This is the aether multiplier. It requires inputs from the stellar inverter and the elemental converter." + }, + { + "id": "item_16_4bb3", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "An ethereal sundial." + }, + { + "id": "item_8_e9e7", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A forgotten scroll." + }, + { + "id": "item_16_0568", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A mysterious shadow sundial." + }, + { + "id": "container_1", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_1", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + }, + { + "name": "fingerprint_input", + "type": "Hex_String", + "description": "Fingerprint Hash", + "value": "1a2b3c4d5e6f" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is the starlight chest. It requires input from the oracle's terminal." + }, + { + "id": "base64_encode", + "name": "Base64 Encoder", + "description": "Encode hex bytes to base64.", + "type": "Tool", + "template_id": "base64_encode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex bytes", + "value": "ece8ec7117ce8ece" + } + ], + "outputs": [ + { + "name": "b64", + "type": "Text_Generic", + "description": "Base64 string", + "value": "7OjscRfOjs4=" + } + ], + "narrative": "This is the runic transcriber. It requires input from the arcane weaver." + }, + { + "id": "calc_inv_mod_30b5", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "105441756310544318115358992" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "11210748210374098778011361778402556553221089" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "105441756310544318115358992" + } + ], + "narrative": "This is the stellar inverter. It requires inputs from the elemental converter and the void multiplier." + }, + { + "id": "num_base_convert", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "5738291029384756382910" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "16" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "10" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "105441756310544318115358992" + } + ], + "init": { + "inputs": { + "s": "5738291029384756382910", + "from_base": "16", + "to_base": "10" + }, + "outputs": {} + }, + "narrative": "An ancient elemental converter." + }, + { + "id": "calc_bigmul_e997", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "1122334455667788990011" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "9988776655443322110099" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "11210748210374098778011361778402556553221089" + } + ], + "init": { + "inputs": { + "a": "1122334455667788990011", + "b": "9988776655443322110099" + }, + "outputs": {} + }, + "narrative": "A magical void multiplier." + }, + { + "id": "terminal_2_df1b", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this terminal" + }, + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "5555566666777778888899" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "3141592653589793238462" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "The terminal has partially computed the task." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "1a2b3c4d5e6f" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "A completely useless piece of math token." + } + ], + "init": { + "inputs": { + "num2": "3141592653589793238462" + }, + "outputs": { + "text_result": "The terminal has partially computed the task.", + "hex_result": "1a2b3c4d5e6f", + "math_token": "A completely useless piece of math token." + } + }, + "narrative": "This is the oracle's terminal. It requires input from the crystal sphere." + }, + { + "id": "terminal_2_b20d", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "2718281828459045235360" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "2" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Terminal b20d output completed." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "2a3b4c5d6e7f" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "Yet another useless object for inventory." + } + ], + "init": { + "inputs": { + "num1": "2718281828459045235360" + }, + "outputs": { + "text_result": "Terminal b20d output completed.", + "hex_result": "2a3b4c5d6e7f", + "math_token": "Yet another useless object for inventory." + } + }, + "narrative": "This is the apprentice's terminal. It requires input from the harmonic aligner." + }, + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "1234567890123456789012" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "9876543210987654321098" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "2" + } + ], + "init": { + "inputs": { + "a": "1234567890123456789012", + "b": "9876543210987654321098" + }, + "outputs": {} + }, + "narrative": "An ancient harmonic aligner." + }, + { + "id": "zip_unzip_item", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_item", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "data_package_1.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "password_qweasd123" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip" + } + ], + "init": { + "inputs": { + "zip_id": "data_package_1.zip", + "password": "password_qweasd123" + }, + "outputs": {} + }, + "narrative": "A mystical spell unweaver." + }, + { + "id": "item_10", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_10", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Big_Int", + "description": "The number", + "value": "5555566666777778888899" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "5555566666777778888899" + } + }, + "narrative": "A glowing crystal sphere." + }, + { + "id": "text_xor_hex", + "name": "Hex XOR", + "description": "XOR two hex strings.", + "type": "Tool", + "template_id": "text_xor_hex", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex_a", + "type": "Hex_String", + "description": "Hex A", + "value": "1234567890abcdef" + }, + { + "name": "hex_b", + "type": "Hex_String", + "description": "Hex B", + "value": "fedcba0987654321" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "XOR Result Hex", + "value": "ece8ec7117ce8ece" + } + ], + "init": { + "inputs": { + "hex_a": "1234567890abcdef", + "hex_b": "fedcba0987654321" + }, + "outputs": {} + }, + "narrative": "An arcane weaver." + }, + { + "id": "item_8_d0cf", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "An elemental scroll." + } + ], + "edges": [ + { + "source_id": "item_8", + "target_id": "item_5", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "item_16", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "terminal_2", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "source_tool" + }, + { + "source_id": "calc_inv_mod", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "num2" + }, + { + "source_id": "calc_inv_mod_1726", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "num1" + }, + { + "source_id": "calc_inv_mod_1726", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "a" + }, + { + "source_id": "calc_bigmul", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "mod" + }, + { + "source_id": "item_16_31d8", + "target_id": "calc_bigmul", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "container_4", + "target_id": "item_16_31d8", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "calc_inv_mod_1726", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "a" + }, + { + "source_id": "calc_bigmul_22cd", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "b" + }, + { + "source_id": "item_16_4bb3", + "target_id": "container_4", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "item_8_e9e7", + "target_id": "calc_bigmul_22cd", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "calc_bigmul_22cd", + "target_id": "calc_inv_mod_1726", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "a" + }, + { + "source_id": "item_16_0568", + "target_id": "item_8_e9e7", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "container_1", + "target_id": "item_16_0568", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "base64_encode", + "target_id": "container_4", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "fingerprint_input" + }, + { + "source_id": "calc_inv_mod_30b5", + "target_id": "calc_bigmul_22cd", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "a" + }, + { + "source_id": "num_base_convert", + "target_id": "calc_inv_mod_30b5", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "a" + }, + { + "source_id": "num_base_convert", + "target_id": "calc_bigmul_22cd", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "b" + }, + { + "source_id": "calc_bigmul_e997", + "target_id": "calc_inv_mod_1726", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "mod" + }, + { + "source_id": "calc_bigmul_e997", + "target_id": "calc_inv_mod_30b5", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "mod" + }, + { + "source_id": "terminal_2_df1b", + "target_id": "container_1", + "connection_type": "Hex_String", + "source_port": "hex_result", + "target_port": "fingerprint_input" + }, + { + "source_id": "terminal_2_b20d", + "target_id": "container_1", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "source_tool" + }, + { + "source_id": "calc_gcd", + "target_id": "terminal_2_b20d", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "num2" + }, + { + "source_id": "zip_unzip_item", + "target_id": "item_16_4bb3", + "connection_type": "Item", + "source_port": "item", + "target_port": "source_tool" + }, + { + "source_id": "item_10", + "target_id": "terminal_2_df1b", + "connection_type": "Big_Int", + "source_port": "content", + "target_port": "num1" + }, + { + "source_id": "text_xor_hex", + "target_id": "base64_encode", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "item_8_d0cf", + "target_id": "calc_gcd", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-5d659179/solution/solve.sh b/tasks/agentescape-25-skeleton-5d659179/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-25-skeleton-5d659179/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-25-skeleton-5d659179/task.toml b/tasks/agentescape-25-skeleton-5d659179/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..af804ae8bd562715722c81f487bcec0f50ff4038 --- /dev/null +++ b/tasks/agentescape-25-skeleton-5d659179/task.toml @@ -0,0 +1,38 @@ +schema_version = "1.4" +source = "https://github.com/AGI-Eval-Official/Repo-of-AgentEscapeBench" + +[[artifacts]] +source = "/evidence/final.json" +service = "puzzle" + +[[artifacts]] +source = "/evidence/trace.jsonl" +service = "puzzle" + +[task] +name = "edbeeching/agentescape-25-skeleton-5d659179" +version = "0.1.0" + +[metadata] +difficulty = 25 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "0abf9f18116b838e831edf418c708985fe4ec6a630ec5a15a1e36eede42721cf" +protocol = "harbor-cli-action-budget-v1" +max_actions = 500 + +[agent] +timeout_sec = 1200 + +[environment] +build_timeout_sec = 900 +cpus = 1 +memory_mb = 1024 + +[verifier] +environment_mode = "separate" +timeout_sec = 60 + +[[verifier.collect]] +service = "puzzle" +command = "python -I /app/export.py" +timeout_sec = 15 diff --git a/tasks/agentescape-25-skeleton-5d659179/tests/Dockerfile b/tasks/agentescape-25-skeleton-5d659179/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-25-skeleton-5d659179/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-25-skeleton-5d659179/tests/expected.json b/tasks/agentescape-25-skeleton-5d659179/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..039131d29e0a44ccc283ac2c941eac90abf2ce72 --- /dev/null +++ b/tasks/agentescape-25-skeleton-5d659179/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "0abf9f18116b838e831edf418c708985fe4ec6a630ec5a15a1e36eede42721cf", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-5d659179/tests/grade.py b/tasks/agentescape-25-skeleton-5d659179/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-25-skeleton-5d659179/tests/grade.py @@ -0,0 +1,21 @@ +"""Grade only Harbor-collected sidecar evidence in a fresh verifier container.""" + +import json +from pathlib import Path + +expected = json.loads(Path("/tests/expected.json").read_text()) +state = json.loads(Path("/evidence/final.json").read_text()) +assert state["collected_from_live_service"] is True, "Missing trusted service export" +assert state["scenario_sha256"] == expected["scenario_sha256"], ( + "Wrong scenario evidence" +) +assert state["max_actions"] == expected["max_actions"], "Wrong budget" +assert type(state["won"]) is bool +assert 0 <= state["action_count"] <= state["max_actions"] +assert state["termination_reason"] != "infrastructure_error", ( + "Infrastructure failure is not a puzzle failure" +) +assert not state["won"] or state["termination_reason"] == "success" +Path("/logs/verifier").mkdir(parents=True, exist_ok=True) +Path("/logs/verifier/state.json").write_text(json.dumps(state, indent=2)) +Path("/logs/verifier/reward.txt").write_text("1.0\n" if state["won"] else "0.0\n") diff --git a/tasks/agentescape-25-skeleton-5d659179/tests/test.sh b/tasks/agentescape-25-skeleton-5d659179/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-25-skeleton-5d659179/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-25-skeleton-5eefda51/environment/Dockerfile b/tasks/agentescape-25-skeleton-5eefda51/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-25-skeleton-5eefda51/environment/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-25-skeleton-5eefda51/environment/agent/Dockerfile b/tasks/agentescape-25-skeleton-5eefda51/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-25-skeleton-5eefda51/environment/agent/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-25-skeleton-5eefda51/environment/agent/cli.py b/tasks/agentescape-25-skeleton-5eefda51/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-25-skeleton-5eefda51/environment/agent/cli.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Public agent client; depends only on the Python standard library.""" + +import argparse +import json +import os +import sys +import urllib.error +import urllib.request + + +def main(): + parser = argparse.ArgumentParser(description="Interact with the escape room") + parser.add_argument( + "action", + choices=[ + "observe", + "state", + "investigate", + "tool-call", + "use-item", + "submit-answer", + ], + ) + parser.add_argument("value", nargs="?") + parser.add_argument("--arguments-json", default="{}") + args = parser.parse_args() + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000").rstrip("/") + if args.action in ("observe", "state"): + request = urllib.request.Request( + base + ("/observation" if args.action == "observe" else "/state") + ) + else: + if args.value is None: + parser.error("node ID or answer is required") + payload = {"action": args.action.replace("-", "_")} + if args.action == "submit-answer": + payload["answer"] = args.value + else: + payload["node_id"] = args.value + if args.action in ("tool-call", "use-item"): + payload["arguments"] = json.loads(args.arguments_json) + request = urllib.request.Request( + base + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=30) as response: + print(json.dumps(json.load(response), ensure_ascii=False)) + except (urllib.error.URLError, ValueError) as exc: + print(json.dumps({"ok": False, "error": str(exc)})) + sys.exit(2) + + +if __name__ == "__main__": + main() diff --git a/tasks/agentescape-25-skeleton-5eefda51/environment/docker-compose.yaml b/tasks/agentescape-25-skeleton-5eefda51/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6ddf6c66c9d3d4673627af045e9c2851fc427fc3 --- /dev/null +++ b/tasks/agentescape-25-skeleton-5eefda51/environment/docker-compose.yaml @@ -0,0 +1,50 @@ +services: + main: + image: agentescapebench-agent:aab05a0a9ddb + build: + context: ./agent + networks: [default, puzzle] + security_opt: [no-new-privileges:true] + depends_on: + puzzle: + condition: service_healthy + puzzle: + image: agentescapebench-puzzle:agentescape-25-skeleton-5eefda51-aab05a0a9ddb + build: + context: ./puzzle + networks: [puzzle, execution] + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 512m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"] + interval: 1s + timeout: 3s + retries: 30 + depends_on: + worker: + condition: service_healthy + worker: + image: agentescapebench-worker:aab05a0a9ddb + build: + context: ./puzzle + dockerfile: worker.Dockerfile + networks: [execution] + read_only: true + tmpfs: ["/tmp:size=64m,mode=1777"] + cap_drop: [ALL] + cap_add: [SETUID, SETGID, KILL, CHOWN, DAC_OVERRIDE] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 384m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8001/health')"] + interval: 1s + timeout: 3s + retries: 30 +networks: + puzzle: + internal: true + execution: + internal: true diff --git a/tasks/agentescape-25-skeleton-5eefda51/environment/puzzle/Dockerfile b/tasks/agentescape-25-skeleton-5eefda51/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-25-skeleton-5eefda51/environment/puzzle/Dockerfile @@ -0,0 +1,9 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY upstream /app/upstream +COPY service.py export.py /app/ +COPY scenario.json /private/scenario.json +ENV SCENARIO_PATH=/private/scenario.json EVIDENCE_DIR=/evidence WORKER_URL=http://worker:8001 MAX_ACTIONS=500 +CMD ["uvicorn", "service:create_app", "--factory", "--host", "0.0.0.0", "--port", "8000", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-25-skeleton-5eefda51/environment/puzzle/child.py b/tasks/agentescape-25-skeleton-5eefda51/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-25-skeleton-5eefda51/environment/puzzle/child.py @@ -0,0 +1,59 @@ +"""Run the original Python tool after reducing privileges and blocking networking.""" + +import ctypes +import errno +import json +import resource +import sys + +resource.setrlimit(resource.RLIMIT_CPU, (3, 3)) +resource.setrlimit(resource.RLIMIT_AS, (256 * 1024 * 1024, 256 * 1024 * 1024)) +resource.setrlimit(resource.RLIMIT_FSIZE, (65536, 65536)) +resource.setrlimit(resource.RLIMIT_NOFILE, (32, 32)) +resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + +# Filters survive fork/exec. Fail closed if seccomp cannot be loaded. +lib = ctypes.CDLL("libseccomp.so.2", use_errno=True) +lib.seccomp_init.argtypes = [ctypes.c_uint32] +lib.seccomp_init.restype = ctypes.c_void_p +lib.seccomp_rule_add.argtypes = [ + ctypes.c_void_p, + ctypes.c_uint32, + ctypes.c_int, + ctypes.c_uint, +] +lib.seccomp_syscall_resolve_name.argtypes = [ctypes.c_char_p] +lib.seccomp_load.argtypes = [ctypes.c_void_p] +lib.seccomp_release.argtypes = [ctypes.c_void_p] +ctx = lib.seccomp_init(0x7FFF0000) # SCMP_ACT_ALLOW +if not ctx: + raise RuntimeError("Cannot initialize execution isolation") +try: + for name in ( + "socket", + "socketpair", + "connect", + "ptrace", + "process_vm_readv", + "process_vm_writev", + "mount", + "unshare", + "setns", + "bpf", + ): + number = lib.seccomp_syscall_resolve_name(name.encode()) + if ( + number >= 0 + and lib.seccomp_rule_add(ctx, 0x00050000 | errno.EPERM, number, 0) != 0 + ): + raise RuntimeError("Cannot install execution isolation rule") + if lib.seccomp_load(ctx) != 0: + raise RuntimeError("Cannot activate execution isolation") +finally: + lib.seccomp_release(ctx) + +sys.path.insert(0, "/app") +from simulator import ToolSimulator # noqa: E402 + +request = json.load(sys.stdin) +json.dump(ToolSimulator().code_py_exec(request), sys.stdout) diff --git a/tasks/agentescape-25-skeleton-5eefda51/environment/puzzle/export.py b/tasks/agentescape-25-skeleton-5eefda51/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-25-skeleton-5eefda51/environment/puzzle/export.py @@ -0,0 +1,13 @@ +"""Harbor invokes this inside the puzzle service after stopping the agent.""" + +import json +import pathlib +import urllib.request + +with urllib.request.urlopen("http://127.0.0.1:8000/state", timeout=10) as response: + state = json.load(response) +state["collected_from_live_service"] = True +target = pathlib.Path("/evidence/final.json") +temp = target.with_suffix(".tmp") +temp.write_text(json.dumps(state)) +temp.replace(target) diff --git a/tasks/agentescape-25-skeleton-5eefda51/environment/puzzle/requirements.txt b/tasks/agentescape-25-skeleton-5eefda51/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-25-skeleton-5eefda51/environment/puzzle/requirements.txt @@ -0,0 +1,57 @@ +annotated-doc==0.0.5 + # via fastapi +annotated-types==0.8.0 + # via pydantic +anyio==4.16.0 + # via starlette +certifi==2026.10.23 + # via requests +cffi==2.1.1 ; platform_python_implementation != 'PyPy' + # via cryptography +charset-normalizer==3.5.2 + # via requests +click==8.5.0 + # via uvicorn +cryptography==50.0.2 + # via agentescapebench-harbor +fastapi==0.162.0 + # via agentescapebench-harbor +h11==0.16.0 + # via uvicorn +idna==3.20 + # via + # anyio + # requests +opentelemetry-api==1.45.2 + # via fastapi +pycparser==3.12 ; implementation_name != 'PyPy' and platform_python_implementation != 'PyPy' + # via cffi +pydantic==2.14.2 + # via + # agentescapebench-harbor + # fastapi +pydantic-core==2.50.2 + # via pydantic +pytz==2025.2 + # via agentescapebench-harbor +requests==2.34.2 + # via agentescapebench-harbor +starlette==1.10.0 + # via fastapi +typing-extensions==4.16.0 + # via + # anyio + # fastapi + # opentelemetry-api + # pydantic + # pydantic-core + # starlette + # typing-inspection +typing-inspection==0.4.4 + # via + # fastapi + # pydantic +urllib3==2.8.0 + # via requests +uvicorn==0.54.0 + # via agentescapebench-harbor diff --git a/tasks/agentescape-25-skeleton-5eefda51/environment/puzzle/scenario.json b/tasks/agentescape-25-skeleton-5eefda51/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..f4f6af63c85055a05f86cc6151c445552519243a --- /dev/null +++ b/tasks/agentescape-25-skeleton-5eefda51/environment/puzzle/scenario.json @@ -0,0 +1,1702 @@ +{ + "metadata": { + "total_nodes": 25, + "total_edges": 32, + "win_node_id": "container_1", + "win_condition": { + "type": "item_content", + "node_id": "container_1", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "container_1", + "terminal_2", + "calc_inv_mod", + "num_base_convert", + "terminal_2_b8dc", + "graph_shortest_path", + "zip_unzip_file", + "zip_unzip_file_4d95", + "iban_validate", + "calc_bigmul_1802", + "calc_gcd", + "zip_unzip_file_a5c9", + "graph_shortest_path_6573", + "zip_unzip_file_92f4", + "terminal_2_089e", + "num_base_convert_ab18", + "calc_modexp", + "item_9", + "calc_gcd_6f18" + ], + "by_node": { + "container_1": { + "node_name": "", + "node_type": "Item", + "template_id": "container_1", + "init_inputs": {}, + "init_outputs": { + "inner_space": { + "type": "Item", + "description": "Contents" + } + } + }, + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": {}, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + }, + "math_token": { + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + } + }, + "calc_inv_mod": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "Integer a" + } + }, + "init_outputs": {} + }, + "num_base_convert": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "from_base": { + "type": "Big_Int", + "description": "From base" + } + }, + "init_outputs": {} + }, + "terminal_2_b8dc": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": {}, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + }, + "math_token": { + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + } + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": {}, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "zip_unzip_file_4d95": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "iban_validate": { + "node_name": "IBAN Validator", + "node_type": "Tool", + "template_id": "iban_validate", + "init_inputs": { + "iban": { + "type": "Text_Generic", + "description": "IBAN string" + } + }, + "init_outputs": {} + }, + "calc_bigmul_1802": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First large integer" + } + }, + "init_outputs": {} + }, + "calc_gcd": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First integer" + } + }, + "init_outputs": {} + }, + "zip_unzip_file_a5c9": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "graph_shortest_path_6573": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "Graph JSON file ID" + }, + "src": { + "type": "Text_Generic", + "description": "Source node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "zip_unzip_file_92f4": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "terminal_2_089e": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": {}, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + } + } + }, + "num_base_convert_ab18": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "from_base": { + "type": "Big_Int", + "description": "From base" + }, + "to_base": { + "type": "Big_Int", + "description": "To base" + } + }, + "init_outputs": {} + }, + "calc_modexp": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "base": { + "type": "Big_Int", + "description": "Base" + }, + "exp": { + "type": "Big_Int", + "description": "Exponent" + }, + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "item_9": { + "node_name": "", + "node_type": "Item", + "template_id": "item_9", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "File_Id", + "description": "JSON file path" + } + } + }, + "calc_gcd_6f18": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First integer" + }, + "b": { + "type": "Big_Int", + "description": "Second integer" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "container_1": { + "init_inputs": {}, + "init_outputs": { + "inner_space": "FDR: 2026-04-27 13:42:19 UTC, Heading 276°, Alt 3512m" + } + }, + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Terminal 2 initialization completed with partial output.", + "hex_result": "a1b2c3d4e5f67890a1b2c3d4e5f67890", + "math_token": "A dusty old token from a forgotten math class." + } + }, + "calc_inv_mod": { + "init_inputs": { + "a": "98765432109876543210123" + }, + "init_outputs": {} + }, + "num_base_convert": { + "init_inputs": { + "from_base": "10" + }, + "init_outputs": {} + }, + "terminal_2_b8dc": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Secret blueprint data loaded into the central memory block.", + "hex_result": "112233445566778899aabbccddeeff00", + "math_token": "A mysterious token that seems entirely pointless." + } + }, + "graph_shortest_path": { + "init_inputs": {}, + "init_outputs": { + "path": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Omega\"]", + "cost": "394851" + } + }, + "zip_unzip_file": { + "init_inputs": { + "password": "GlobalAdminPassword123!" + }, + "init_outputs": { + "files": "graph_data.json" + } + }, + "zip_unzip_file_4d95": { + "init_inputs": { + "password": "SecureArchivePass_4d95" + }, + "init_outputs": { + "files": "intermediate_layer2.zip" + } + }, + "iban_validate": { + "init_inputs": { + "iban": "DE89370400440532013000" + }, + "init_outputs": {} + }, + "calc_bigmul_1802": { + "init_inputs": { + "a": "12345678901234567890123" + }, + "init_outputs": {} + }, + "calc_gcd": { + "init_inputs": { + "a": "5647382910564738291045" + }, + "init_outputs": {} + }, + "zip_unzip_file_a5c9": { + "init_inputs": { + "password": "DecryptKey_A5C9_!" + }, + "init_outputs": { + "files": "extracted_bundle_a5c9.zip" + } + }, + "graph_shortest_path_6573": { + "init_inputs": { + "file_id": "network_map_6573.json", + "src": "Node_Start_6573" + }, + "init_outputs": { + "path": "[\"Node_Start_6573\", \"Node_Mid_1\", \"Node_Mid_2\", \"Node_Mid_3\", \"Node_Target\"]", + "cost": "837492" + } + }, + "zip_unzip_file_92f4": { + "init_inputs": { + "password": "Op3nS3sam3_92f4" + }, + "init_outputs": { + "files": "compressed_core_92f4.zip" + } + }, + "terminal_2_089e": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Terminal 089e executed its final command sequence successfully.", + "hex_result": "deadbeef1234567890abcdef12345678" + } + }, + "num_base_convert_ab18": { + "init_inputs": { + "from_base": "10", + "to_base": "10" + }, + "init_outputs": {} + }, + "calc_modexp": { + "init_inputs": { + "base": "17", + "exp": "9988776655443322110055", + "mod": "104729" + }, + "init_outputs": {} + }, + "item_9": { + "init_inputs": {}, + "init_outputs": { + "content": "target_payload_9.zip" + } + }, + "calc_gcd_6f18": { + "init_inputs": { + "a": "8877665544332211009988", + "b": "1122334455667788990011" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You've successfully infiltrated the underground data fortress of the Nexus Syndicate, a high-tech labyrinth of servers and reinforced steel. Your objective is the Central Vault, which holds damning evidence of their illegal operations. Suddenly, the facility's automated systems lock down. The main servers have fragmented their authentication protocols, scattering them across different subsystems. You must logically manipulate the severed network modules and decrypt the layered security archives before the Syndicate's strike team arrives. The clock is ticking as you delve deeper into the mainframe.", + "narrative_style": "techno_thriller" + }, + "nodes": [ + { + "id": "container_1", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + }, + { + "name": "fingerprint_input", + "type": "Hex_String", + "description": "Fingerprint Hash", + "value": "a1b2c3d4e5f67890a1b2c3d4e5f67890" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents", + "value": "FDR: 2026-04-27 13:42:19 UTC, Heading 276°, Alt 3512m" + } + ], + "init": { + "inputs": {}, + "outputs": { + "inner_space": "FDR: 2026-04-27 13:42:19 UTC, Heading 276°, Alt 3512m" + } + }, + "narrative": "The Central Vault is a reinforced titanium safe containing the core evidence. It requires input from the Master Override Terminal to release its primary locks." + }, + { + "id": "terminal_2", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "95214" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "9403851852909785185208651322" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Terminal 2 initialization completed with partial output." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "a1b2c3d4e5f67890a1b2c3d4e5f67890" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "A dusty old token from a forgotten math class." + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "Terminal 2 initialization completed with partial output.", + "hex_result": "a1b2c3d4e5f67890a1b2c3d4e5f67890", + "math_token": "A dusty old token from a forgotten math class." + } + }, + "narrative": "This is the Master Override Terminal, the final checkpoint in the network. It requires inputs from the Primary Processor and the Logic Decoder." + }, + { + "id": "calc_bigmul", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "98765432109876543210123" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "95214" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "9403851852909785185208651322" + } + ], + "narrative": "The Primary Processor hums with immense computing power. It requires inputs from the Phase Inverter and the Signal Translator." + }, + { + "id": "zip_unzip_item", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_item", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "extracted_bundle_a5c9.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Secret blueprint data loaded into the central memory block." + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip" + } + ], + "narrative": "The Encrypted Blueprint Archive contains classified digital schematics. It requires inputs from the Security Sub-Terminal and the Delta Sector Archive." + }, + { + "id": "calc_inv_mod", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "98765432109876543210123" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "37037036703703703670369" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "98765432109876543210123" + } + ], + "init": { + "inputs": { + "a": "98765432109876543210123" + }, + "outputs": {} + }, + "narrative": "The Phase Inverter is a specialized data-flipping mechanism. It requires input from the Secondary Processor." + }, + { + "id": "num_base_convert", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool", + "value": "synthesized_item_378af87cf6fd7f95" + }, + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "95214" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "10" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "37037036703703703670369" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "95214" + } + ], + "init": { + "inputs": { + "from_base": "10" + }, + "outputs": {} + }, + "narrative": "The Logic Decoder translates raw machine logic into readable formats. It requires inputs from the Secondary Processor and the Signal Translator." + }, + { + "id": "terminal_2_b8dc", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "11" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "394851" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Secret blueprint data loaded into the central memory block." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "112233445566778899aabbccddeeff00" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "A mysterious token that seems entirely pointless." + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "Secret blueprint data loaded into the central memory block.", + "hex_result": "112233445566778899aabbccddeeff00", + "math_token": "A mysterious token that seems entirely pointless." + } + }, + "narrative": "The Security Sub-Terminal manages auxiliary defense protocols. It requires inputs from the Main Routing Node and the Pulse Generator." + }, + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "graph_data.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "false" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Terminal 089e executed its final command sequence successfully." + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Omega\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "394851" + } + ], + "init": { + "inputs": {}, + "outputs": { + "path": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Omega\"]", + "cost": "394851" + } + }, + "narrative": "The Main Routing Node coordinates data packets across the facility. It requires inputs from the Integrity Checker, the Beta Core Archive, and the Logistics Terminal." + }, + { + "id": "luhn_check", + "name": "Luhn Checker", + "description": "Luhn validity of number string.", + "type": "Tool", + "template_id": "luhn_check", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "number", + "type": "Text_Generic", + "description": "Number string", + "value": "True" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "false" + } + ], + "narrative": "The Integrity Checker validates incoming data authenticity. It requires input from the Identity Validator." + }, + { + "id": "matter_synthesizer", + "name": "Matter Synthesizer", + "description": "Synthesizes physical objects from data blueprints.", + "type": "Tool", + "template_id": "matter_synthesizer", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "blueprint", + "type": "Text_Generic", + "description": "Object Blueprint", + "value": "Secret blueprint data loaded into the central memory block." + } + ], + "outputs": [ + { + "name": "output_slot", + "type": "Item", + "description": "Synthesized Object", + "value": "synthesized_item_378af87cf6fd7f95" + } + ], + "narrative": "The Molecular Printer is capable of rapid 3D printing from digital data. It requires input from the Security Sub-Terminal." + }, + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "intermediate_layer2.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "GlobalAdminPassword123!" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "graph_data.json" + } + ], + "init": { + "inputs": { + "password": "GlobalAdminPassword123!" + }, + "outputs": { + "files": "graph_data.json" + } + }, + "narrative": "The Beta Core Archive is a highly compressed data repository. It requires input from the Gamma Sector Archive." + }, + { + "id": "zip_unzip_file_4d95", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "extracted_bundle_a5c9.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "SecureArchivePass_4d95" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "intermediate_layer2.zip" + } + ], + "init": { + "inputs": { + "password": "SecureArchivePass_4d95" + }, + "outputs": { + "files": "intermediate_layer2.zip" + } + }, + "narrative": "The Gamma Sector Archive holds heavily encrypted files. It requires input from the Delta Sector Archive." + }, + { + "id": "iban_validate", + "name": "IBAN Validator", + "description": "IBAN checksum validation.", + "type": "Tool", + "template_id": "iban_validate", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "iban", + "type": "Text_Generic", + "description": "IBAN string", + "value": "DE89370400440532013000" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "True" + } + ], + "init": { + "inputs": { + "iban": "DE89370400440532013000" + }, + "outputs": {} + }, + "narrative": "An Identity Validator module." + }, + { + "id": "calc_bigmul_1802", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "12345678901234567890123" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "3" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "37037036703703703670369" + } + ], + "init": { + "inputs": { + "a": "12345678901234567890123" + }, + "outputs": {} + }, + "narrative": "The Secondary Processor handles complex backend computations. It requires input from the Resonance Calibrator." + }, + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "5647382910564738291045" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "837492" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "3" + } + ], + "init": { + "inputs": { + "a": "5647382910564738291045" + }, + "outputs": {} + }, + "narrative": "The Resonance Calibrator aligns frequency harmonics. It requires input from the Traffic Analyzer." + }, + { + "id": "zip_unzip_file_a5c9", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "compressed_core_92f4.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "DecryptKey_A5C9_!" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_bundle_a5c9.zip" + } + ], + "init": { + "inputs": { + "password": "DecryptKey_A5C9_!" + }, + "outputs": { + "files": "extracted_bundle_a5c9.zip" + } + }, + "narrative": "The Delta Sector Archive contains deeper layers of system data. It requires input from the Alpha Sector Archive." + }, + { + "id": "graph_shortest_path_6573", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "network_map_6573.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Node_Start_6573" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "True" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Node_Start_6573\", \"Node_Mid_1\", \"Node_Mid_2\", \"Node_Mid_3\", \"Node_Target\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "837492" + } + ], + "init": { + "inputs": { + "file_id": "network_map_6573.json", + "src": "Node_Start_6573" + }, + "outputs": { + "path": "[\"Node_Start_6573\", \"Node_Mid_1\", \"Node_Mid_2\", \"Node_Mid_3\", \"Node_Target\"]", + "cost": "837492" + } + }, + "narrative": "The Traffic Analyzer monitors data flow bottlenecks. It requires input from the Identity Validator." + }, + { + "id": "zip_unzip_file_92f4", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "target_payload_9.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Op3nS3sam3_92f4" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "compressed_core_92f4.zip" + } + ], + "init": { + "inputs": { + "password": "Op3nS3sam3_92f4" + }, + "outputs": { + "files": "compressed_core_92f4.zip" + } + }, + "narrative": "The Alpha Sector Archive stores root-level information. It requires input from the Encrypted Datapad." + }, + { + "id": "terminal_2_089e", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this terminal" + }, + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "98765432109876543210123" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "95214" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Terminal 089e executed its final command sequence successfully." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "deadbeef1234567890abcdef12345678" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "Terminal 089e executed its final command sequence successfully.", + "hex_result": "deadbeef1234567890abcdef12345678" + } + }, + "narrative": "The Logistics Terminal manages material transport logic. It requires inputs from the Signal Translator and the Phase Inverter." + }, + { + "id": "num_base_convert_ab18", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "95214" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "10" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "10" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "95214" + } + ], + "init": { + "inputs": { + "from_base": "10", + "to_base": "10" + }, + "outputs": {} + }, + "narrative": "The Signal Translator decodes proprietary syntax. It requires input from the Cryptographic Core." + }, + { + "id": "calc_modexp", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "17" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "9988776655443322110055" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "104729" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "95214" + } + ], + "init": { + "inputs": { + "base": "17", + "exp": "9988776655443322110055", + "mod": "104729" + }, + "outputs": {} + }, + "narrative": "A heavy-duty Cryptographic Core engine." + }, + { + "id": "item_9", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_9", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "File_Id", + "description": "JSON file path", + "value": "target_payload_9.zip" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "target_payload_9.zip" + } + }, + "narrative": "An Encrypted Datapad." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A Stealth Keycard." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A Temporal Chip." + }, + { + "id": "calc_gcd_6f18", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "8877665544332211009988" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "1122334455667788990011" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "11" + } + ], + "init": { + "inputs": { + "a": "8877665544332211009988", + "b": "1122334455667788990011" + }, + "outputs": {} + }, + "narrative": "A Pulse Generator." + } + ], + "edges": [ + { + "source_id": "terminal_2", + "target_id": "container_1", + "connection_type": "Hex_String", + "source_port": "hex_result", + "target_port": "fingerprint_input" + }, + { + "source_id": "calc_bigmul", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "num2" + }, + { + "source_id": "zip_unzip_item", + "target_id": "calc_bigmul", + "connection_type": "Item", + "source_port": "item", + "target_port": "trigger_item" + }, + { + "source_id": "calc_inv_mod", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "a" + }, + { + "source_id": "num_base_convert", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "num1" + }, + { + "source_id": "terminal_2_b8dc", + "target_id": "zip_unzip_item", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "password" + }, + { + "source_id": "graph_shortest_path", + "target_id": "terminal_2_b8dc", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "num2" + }, + { + "source_id": "luhn_check", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "src" + }, + { + "source_id": "matter_synthesizer", + "target_id": "num_base_convert", + "connection_type": "Item", + "source_port": "output_slot", + "target_port": "trigger_item" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "zip_unzip_file_4d95", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "iban_validate", + "target_id": "luhn_check", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "number" + }, + { + "source_id": "calc_bigmul_1802", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "to_base" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_bigmul_1802", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "b" + }, + { + "source_id": "zip_unzip_file_a5c9", + "target_id": "zip_unzip_file_4d95", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "terminal_2_b8dc", + "target_id": "matter_synthesizer", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "blueprint" + }, + { + "source_id": "zip_unzip_file_a5c9", + "target_id": "zip_unzip_item", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "graph_shortest_path_6573", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "b" + }, + { + "source_id": "zip_unzip_file_92f4", + "target_id": "zip_unzip_file_a5c9", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "terminal_2_089e", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "dst" + }, + { + "source_id": "num_base_convert_ab18", + "target_id": "terminal_2_089e", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "num2" + }, + { + "source_id": "calc_bigmul_1802", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "mod" + }, + { + "source_id": "iban_validate", + "target_id": "graph_shortest_path_6573", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "dst" + }, + { + "source_id": "num_base_convert_ab18", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "b" + }, + { + "source_id": "calc_inv_mod", + "target_id": "terminal_2_089e", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "num1" + }, + { + "source_id": "calc_modexp", + "target_id": "num_base_convert_ab18", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "s" + }, + { + "source_id": "item_9", + "target_id": "zip_unzip_file_92f4", + "connection_type": "File_Id", + "source_port": "content", + "target_port": "zip_id" + }, + { + "source_id": "terminal_2_089e", + "target_id": "item_9", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "container" + }, + { + "source_id": "num_base_convert_ab18", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "s" + }, + { + "source_id": "item_8", + "target_id": "terminal_2_089e", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "item_16", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "calc_gcd_6f18", + "target_id": "terminal_2_b8dc", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "num1" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-5eefda51/environment/puzzle/service.py b/tasks/agentescape-25-skeleton-5eefda51/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-25-skeleton-5eefda51/environment/puzzle/service.py @@ -0,0 +1,212 @@ +"""Restricted facade over the unchanged, pinned upstream puzzle handlers.""" + +import hashlib +import json +import logging +import os +import sys +import threading +import urllib.request +import uuid +from pathlib import Path + +from fastapi import FastAPI, HTTPException +from fastapi.responses import JSONResponse +from pydantic import BaseModel, ConfigDict + +sys.path.insert(0, str(Path(__file__).parent / "upstream")) +import server as upstream # noqa: E402 + +log = logging.getLogger(__name__) + + +def public(value): + """Keep upstream agent-internal template hints out of the public response.""" + if isinstance(value, dict): + return {k: public(v) for k, v in value.items() if not k.startswith("_")} + if isinstance(value, list): + return [public(v) for v in value] + return value + + +class Action(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + action: str + node_id: str | None = None + arguments: dict | None = None + answer: str | None = None + + +class Episode: + def __init__( + self, scenario_path, max_actions=500, evidence_dir=None, worker_url=None + ): + if max_actions < 1: + raise ValueError("max_actions must be positive") + self.lock = threading.Lock() + self.max_actions = max_actions + self.count = 0 + self.won = False + self.reason = None + self.evidence_dir = Path(evidence_dir) if evidence_dir else None + self.scenario_hash = hashlib.sha256( + Path(scenario_path).read_bytes() + ).hexdigest() + self.initial = upstream.reset_case( + case_file_path=str(scenario_path), session_id=uuid.uuid4().hex + ) + self.case_id = self.initial["case_id"] + # Hide source file paths; no upstream reset/stats/routes are mounted. + self.initial.pop("message", None) + simulator = upstream.SIMULATORS[self.case_id] + if worker_url is None: + + def no_worker(_inputs): + self.reason = "infrastructure_error" + raise RuntimeError("isolated Python worker is not configured") + + simulator.tool_map["code_py_exec"] = no_worker + else: + + def execute_python(inputs): + request = urllib.request.Request( + worker_url + "/execute", + data=json.dumps({"code": inputs.get("code", "")}).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=12) as response: + result = json.load(response) + if not isinstance(result.get("stdout"), str): + raise RuntimeError("Invalid Python worker response") + return result + except Exception: + self.reason = "infrastructure_error" + raise + + simulator.tool_map["code_py_exec"] = execute_python + self.save() + if self.evidence_dir is not None: + (self.evidence_dir / "trace.jsonl").touch() + + def state(self): + return { + "scenario_sha256": self.scenario_hash, + "action_count": self.count, + "max_actions": self.max_actions, + "won": self.won, + "termination_reason": self.reason, + } + + def save(self, action=None, result=None): + if self.evidence_dir is None: + return + self.evidence_dir.mkdir(parents=True, exist_ok=True) + target = self.evidence_dir / "outcome.json" + temp = target.with_suffix(".tmp") + temp.write_text(json.dumps(self.state())) + temp.replace(target) + if action is not None: + with (self.evidence_dir / "trace.jsonl").open("a") as handle: + handle.write( + json.dumps( + {"index": self.count, "action": action, "result": result} + ) + + "\n" + ) + + def dispatch(self, payload): + with self.lock: + if self.reason is not None: + return { + "ok": False, + "error": "Episode has ended", + "episode": self.state(), + } + self.count += 1 + try: + action = Action.model_validate(payload) + if action.action == "submit_answer" and action.answer is not None: + result = upstream.submit_answer( + self.case_id, upstream.SubmitAnswerRequest(answer=action.answer) + ) + if result.get("is_win"): + self.won = True + self.reason = "success" + elif action.action == "investigate" and action.node_id is not None: + result = upstream.investigate( + self.case_id, + upstream.InvestigateRequest(node_id=action.node_id), + ) + elif ( + action.action in ("tool_call", "use_item") + and action.node_id is not None + ): + request_type, handler = ( + (upstream.ToolCallRequest, upstream.tool_call) + if action.action == "tool_call" + else (upstream.UseItemRequest, upstream.use_item) + ) + result = handler( + self.case_id, + request_type( + node_id=action.node_id, arguments=action.arguments or {} + ), + ) + else: + result = { + "ok": False, + "error": "Unknown action or missing action parameter", + } + except HTTPException as exc: + result = {"ok": False, "error": exc.detail} + except ValueError: + result = {"ok": False, "error": "Malformed action"} + except Exception: + log.exception("Puzzle service failure") + self.reason = "infrastructure_error" + self.save() + raise + if self.reason is None and self.count >= self.max_actions: + self.reason = "action_budget_exhausted" + result = public(result) + result["episode"] = self.state() + self.save(payload, result) + return result + + +def create_app( + scenario_path=None, max_actions=None, evidence_dir=None, worker_url=None +): + episode = Episode( + scenario_path or os.environ["SCENARIO_PATH"], + max_actions or int(os.environ.get("MAX_ACTIONS", "500")), + evidence_dir if evidence_dir is not None else os.environ.get("EVIDENCE_DIR"), + worker_url if worker_url is not None else os.environ.get("WORKER_URL"), + ) + app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) + app.state.episode = episode + + @app.get("/health") + def health(): + return {"ok": True} + + @app.get("/observation") + def observation(): + return {**public(episode.initial), "episode": episode.state()} + + @app.get("/state") + def state(): + return episode.state() + + @app.post("/action") + def action(payload: dict): + try: + return episode.dispatch(payload) + except Exception: + return JSONResponse( + status_code=503, + content={"ok": False, "error": "Puzzle infrastructure failure"}, + ) + + return app diff --git a/tasks/agentescape-25-skeleton-5eefda51/environment/puzzle/upstream/models.py b/tasks/agentescape-25-skeleton-5eefda51/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-25-skeleton-5eefda51/environment/puzzle/upstream/models.py @@ -0,0 +1,108 @@ +from enum import Enum +from typing import List, Dict, Any, Optional +from pydantic import BaseModel, Field + +# 1. 细粒度接口类型定义 +class InterfaceType(str, Enum): + ''' + BIG_INT + TEXT_GENERIC + HEX_STRING + FILE_ID + HEX_STRING_KEY_AES + HEX_STRING_IV_AES + CODE_PYTHON + HIDDEN_ITEM + ITEM + ''' + # --- 基础类型 --- + TEXT_GENERIC = "Text_Generic" + BIG_INT = "Big_Int" + + # --- 编码/格式化字符串 --- + HEX_STRING = "Hex_String" # 通用 Hex + + # --- 特定用途的 Hex 字符串 (用于精确匹配) --- + HEX_STRING_KEY_AES = "Hex_String_Key_AES" + HEX_STRING_IV_AES = "Hex_String_IV_AES" + + # --- 文件类型 --- + FILE_ID = "File_Id" + + # --- 代码/脚本 --- + CODE_PYTHON = "Code_Python" + + # --- 实体交互类型 (严格命名) --- + ITEM = "Item" # 主动掉落接口 (Tool -> Item) + HIDDEN_ITEM = "Hidden_Item" # 被动掉落接口 (Item -> Item) + +# 3. 端口定义 +class Port(BaseModel): + name: str + type: InterfaceType + description: str + +# 4. 统一节点定义 (融合工具和物品) +class Node(BaseModel): + id: str + name: str + description: str + type: str # "Tool" or "Item" + + # 接口定义 + inputs: List[Port] = [] + outputs: List[Port] = [] + + # 状态字段 + content: Optional[Any] = None # 物品有内容,工具为None + if_success: Optional[bool] = None # 工具初始为False,物品为None + initial_visible: bool = False + + # 运行时状态 (Server维护) + is_revealed: bool = False + + # 标记该 Tool 节点是否有待触发的 HIDDEN_ITEM 掉落 + # 当 Tool 按照 golden_input 正确执行且有 HIDDEN_ITEM 输出边时设为 True + # 在 investigate 该 Tool 时触发掉落并重置为 False + has_hidden_item_ready: bool = False + + # 初始输入值 (metadata.initial_values.init_inputs,用于渐进式暴露判断) + init_input_values: Dict[str, Any] = {} + + # Golden 输入值 (nodes[].inputs[].value,用于评测验证) + golden_input_values: Dict[str, Any] = {} + + # Golden 输出值 (nodes[].outputs[].value,用于评测验证和 Item 节点的 content) + golden_output_values: Dict[str, Any] = {} + + # 实际获得的输出值历史 (工具每次执行后实际返回的输出列表,用于渐进式暴露判断) + # 格式: List[Dict[str, Any]],每个元素是一次执行的输出字典 + actual_outputs_history: List[Dict[str, Any]] = [] + + # 逻辑规则 (用于终端机等复杂物品) + logic_rules: Optional[Dict[str, Any]] = None + + def copy(self, **kwargs): + """Helper to create a copy with updated fields.""" + data = self.dict() + data.update(kwargs) + return Node(**data) + +# 5. 边定义 (拓扑结构) +class Edge(BaseModel): + source_id: str + target_id: str + connection_type: InterfaceType # 直接使用 InterfaceType + # 如果是 Data_Flow,指定端口对应关系 + source_port: Optional[str] = None + target_port: Optional[str] = None + +# 6. 完整图定义 +class GraphScenario(BaseModel): + case_id: str + title: str + intro_narrative: str + nodes: Dict[str, Node] + edges: List[Edge] + difficulty: int + win_node_id: str # 标记哪个节点是最终目标(通常是一个提交工具或最终物品) diff --git a/tasks/agentescape-25-skeleton-5eefda51/environment/puzzle/upstream/server.py b/tasks/agentescape-25-skeleton-5eefda51/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-25-skeleton-5eefda51/environment/puzzle/upstream/server.py @@ -0,0 +1,1490 @@ +import json +import os +import time +import logging +import random +from pathlib import Path +from typing import Dict, Any, List, Optional +from datetime import datetime +from collections import defaultdict +from fastapi import FastAPI, HTTPException, Request +from fastapi.responses import JSONResponse +from fastapi.middleware.cors import CORSMiddleware +from pydantic import BaseModel, Field + +from models import GraphScenario, Node, InterfaceType +# from generator import ScenarioGenerator +from simulator import ToolSimulator +import uvicorn + +# 配置日志 +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler('server.log'), + logging.StreamHandler() + ] +) +logger = logging.getLogger(__name__) + +app = FastAPI( + title="AgentEscapeBench Universal Server", + version="1.0.0", + description="Industrial-grade evaluation server for escape room AI agents" +) + +# 添加 CORS 支持 +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# In-memory State +SCENARIOS: Dict[str, GraphScenario] = {} +SIMULATORS: Dict[str, ToolSimulator] = {} # case_id -> ToolSimulator +RAW_NODES_DATA: Dict[str, Dict[str, Any]] = {} # case_id -> node_id -> raw node data (for template_id) +FILE_METADATA: Dict[str, Dict[str, Any]] = {} # case_id -> metadata (for initial_values access) + +# Performance monitoring +STATS: Dict[str, Any] = { + "total_requests": 0, + "successful_requests": 0, + "failed_requests": 0, + "tool_calls": defaultdict(int), + "investigates": defaultdict(int), + "use_items": defaultdict(int), + "case_loads": 0, + "start_time": datetime.now() +} + +# Request timing middleware +@app.middleware("http") +async def add_process_time_header(request: Request, call_next): + start_time = time.time() + STATS["total_requests"] += 1 + + try: + response = await call_next(request) + STATS["successful_requests"] += 1 + process_time = time.time() - start_time + response.headers["X-Process-Time"] = str(process_time) + logger.info(f"{request.method} {request.url.path} - {response.status_code} - {process_time:.3f}s") + return response + except Exception as e: + STATS["failed_requests"] += 1 + logger.error(f"{request.method} {request.url.path} - Error: {str(e)}") + raise + +# Exception handler +@app.exception_handler(Exception) +async def global_exception_handler(request: Request, exc: Exception): + logger.error(f"Unhandled exception: {exc}", exc_info=True) + return JSONResponse( + status_code=500, + content={ + "ok": False, + "error": "Internal server error", + "detail": str(exc) if os.getenv("DEBUG") else "An error occurred" + } + ) + +# Health check endpoint +@app.get("/health") +def health_check(): + """健康检查端点""" + uptime = (datetime.now() - STATS["start_time"]).total_seconds() + return { + "status": "healthy", + "version": "1.0.0", + "uptime_seconds": uptime, + "loaded_cases": len(SCENARIOS), + "stats": { + "total_requests": STATS["total_requests"], + "successful_requests": STATS["successful_requests"], + "failed_requests": STATS["failed_requests"], + "success_rate": STATS["successful_requests"] / max(STATS["total_requests"], 1) + } + } + +# Statistics endpoint +@app.get("/stats") +def get_stats(): + """获取详细统计信息""" + return { + "stats": STATS, + "loaded_cases": list(SCENARIOS.keys()), + "uptime": str(datetime.now() - STATS["start_time"]) + } + +def _apply_progressive_reveal_at_init(scenario: GraphScenario): + """ + 在初始化时应用渐进式暴露机制(基于ITEM/HIDDEN_ITEM边) + + 新逻辑: + - 如果一个节点没有 ITEM/HIDDEN_ITEM 类型的入边,它就是初始可见的 + - 如果一个节点有 ITEM/HIDDEN_ITEM 类型的入边,它初始不可见,需要等待上游触发 + + Args: + scenario: 场景对象 + """ + # 收集所有有 ITEM/HIDDEN_ITEM 入边的节点 + nodes_with_item_edges = set() + for edge in scenario.edges: + if edge.connection_type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + nodes_with_item_edges.add(edge.target_id) + + logger.info(f"Nodes with ITEM/HIDDEN_ITEM incoming edges: {nodes_with_item_edges}") + + # 设置初始可见性:没有 ITEM/HIDDEN_ITEM 入边的节点初始可见 + initially_visible_count = 0 + for node_id, node in scenario.nodes.items(): + if node_id not in nodes_with_item_edges: + node.is_revealed = True + initially_visible_count += 1 + logger.info(f"Initial visible (no ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + else: + node.is_revealed = False + logger.debug(f"Initial hidden (has ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + + logger.info(f"Progressive reveal initialized: {initially_visible_count}/{len(scenario.nodes)} nodes initially visible") + + +def _check_inputs_match_golden(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> bool: + """ + 检查实际输入参数是否与 golden inputs 完全匹配 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + True 表示所有 golden inputs 都存在且值匹配 + """ + if not golden_inputs: + return True # 如果没有 golden inputs,认为匹配 + + for key, expected_value in golden_inputs.items(): + actual_value = arguments.get(key) + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) != str(expected_value): + logger.debug(f"Input mismatch for '{key}': expected '{expected_value}', got '{actual_value}'") + return False + + return True + + +def _get_parameter_validation_feedback(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> Dict[str, Any]: + """ + 对源头节点的参数进行详细验证,返回验证反馈 + + 注意:不返回期望值(expected),避免泄漏答案 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + 包含验证结果的字典: + - all_correct: bool - 所有参数是否正确 + - correct_params: List[str] - 正确的参数名列表 + - incorrect_params: List[str] - 错误的参数名列表(不包含期望值) + """ + if not golden_inputs: + return { + "all_correct": True, + "correct_params": [], + "incorrect_params": [] + } + + correct_params = [] + incorrect_params = [] + + for key, actual_value in arguments.items(): + # 只对用户实际提交的参数给反馈,未提交的参数不评价 + if key not in golden_inputs: + continue # 该参数不在 golden 中,跳过(如 _golden_inputs 等内部参数) + expected_value = golden_inputs[key] + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) == str(expected_value): + correct_params.append(key) + else: + # 只记录参数名,不包含期望值,避免泄漏答案 + incorrect_params.append(key) + + # all_correct:用户提交的所有参数都正确,且覆盖了全部 golden 参数 + all_provided_correct = len(incorrect_params) == 0 + all_golden_covered = all(k in arguments for k in golden_inputs) + return { + "all_correct": all_provided_correct and all_golden_covered, + "correct_params": correct_params, + "incorrect_params": incorrect_params + } + + +def _is_source_node(node_id: str, scenario: GraphScenario) -> bool: + """ + 判断节点是否是源头节点(完全没有任何入边的节点) + + 源头节点定义: + - 没有任何类型的入边(包括 DATA、ITEM、HIDDEN_ITEM) + - 即没有任何上游节点 + + Args: + node_id: 节点ID + scenario: 场景对象 + + Returns: + True 表示是源头节点 + """ + for edge in scenario.edges: + if edge.target_id == node_id: + # 只要有任何入边,就不是源头节点 + return False + + return True + + +def _check_and_reveal_ready_nodes(scenario: GraphScenario, recent_outputs: Dict[str, Any], source_node_id: str) -> List[Dict[str, Any]]: + """ + 检查并释放参数齐全的隐藏节点(渐进式暴露机制) + + 核心逻辑: + 1. 维护"可见值集合":包含所有被测模型当前可以看到的值 + - init_inputs 的值(初始可见) + - 工具执行后的实际输出值(运行时获得) + - 可见 Item 的输出值 + 2. 检查隐藏节点:该节点的所有 golden_input 值是否都在可见值集合中 + 3. 如果是,则释放该节点 + + Args: + scenario: 场景对象 + recent_outputs: 最近执行的工具的输出 + source_node_id: 刚执行的工具节点ID + + Returns: + 新释放的节点列表 + """ + newly_revealed = [] + + # 构建"可见值集合"(Set of visible values) + # 存储格式:set of values (转为字符串) + visible_values = set() + + # 1. 添加有意义的 init_inputs 值到可见值集合 + # Item 的 init_inputs 不应该加入,因为它们在密室中完全用不到 + for node_id, node in scenario.nodes.items(): + # 跳过源头 Item 节点(没有入边的 Item) + if node.type == "Item": + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,跳过其 init_inputs + continue + + # 添加其他节点的 init_inputs + for port_name, init_value in node.init_input_values.items(): + if init_value: + visible_values.add(str(init_value)) + + # 2. 添加已执行工具的所有历史输出值 + for node_id, node in scenario.nodes.items(): + if node.type == "Tool" and node.if_success and node.actual_outputs_history: + # 遍历所有历史执行记录 + for output_dict in node.actual_outputs_history: + for output_port_name, output_value in output_dict.items(): + if output_value: + visible_values.add(str(output_value)) + + # 3. 添加已被 investigate 的 Item 的 golden 输出值 + # 注意:Item 可见不等于其输出值可见,需要 investigate 后才能获得 + # 这里我们使用 actual_outputs_history 来标记 Item 是否已被 investigate + for node_id, node in scenario.nodes.items(): + if node.type == "Item" and node.is_revealed and node.actual_outputs_history: + # Item 通常只会被 investigate 一次,但为了一致性也使用历史列表 + for output_dict in node.actual_outputs_history: + for port_name, port_value in output_dict.items(): + if port_value: + visible_values.add(str(port_value)) + + # 遍历所有隐藏的节点,检查其 golden_input 是否都在可见值集合中 + for node_id, node in scenario.nodes.items(): + # 跳过已可见的节点 + if node.is_revealed: + continue + + # 只检查工具节点(物品节点由 ITEM 输出触发) + if node.type != "Tool": + continue + + # 检查该节点的所有 golden_input 值是否都在可见值集合中 + all_inputs_ready = True + missing_values = [] + + for input_port_name, golden_input_value in node.golden_input_values.items(): + # 检查这个 golden 值是否在可见值集合中 + if str(golden_input_value) not in visible_values: + all_inputs_ready = False + missing_values.append(f"{input_port_name}={golden_input_value}") + + # 如果所有 golden_input 值都在可见值集合中,释放该节点 + if all_inputs_ready and len(node.golden_input_values) > 0: + logger.info(f"All golden inputs ready for {node_id}: {list(node.golden_input_values.values())}") + + # 如果所有输入都齐全,释放该节点 + if all_inputs_ready: + node.is_revealed = True + + # 构建节点信息返回给模型 + node_info = { + "id": node.id, + "type": node.type, + "can_investigate": True, + "hint": "This tool's input parameters are now complete, you can use investigate to view detailed information" + } + + # if node.name: + # node_info["name"] = node.name + if node.description: + node_info["description"] = node.description + + newly_revealed.append(node_info) + logger.info(f"Progressive reveal: {node_id} is now ready (all inputs satisfied)") + + return newly_revealed + + +def _initialize_node_values(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]): + """ + Initialize node state and load values from port value fields. + 应用渐进式暴露机制:初始时只显示参数齐全的节点(源头节点) + + 重要区分: + 1. input_values: 只加载 metadata.initial_values 中的 init_inputs(真正的初始值) + 2. output_values: 加载 nodes[].outputs[].value(golden 输出,用于验证) + """ + # 第一步:加载所有节点的值,并将所有节点初始设为隐藏 + initial_values = metadata.get('initial_values', {}) + + for node_id, node in scenario.nodes.items(): + # 忽略 initial_visible 字段,初始全部隐藏 + # 由渐进式暴露机制根据参数齐全情况决定是否显示 + node.is_revealed = False + + if node.type == "Tool": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + elif node.type == "Item": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + + # 从 JSON 加载值 + if node_id in raw_nodes_data: + node_data = raw_nodes_data[node_id] # node_data是json文件中nodes中的字典 + + # 【重要】只加载 metadata.initial_values 中的初始输入值 + if node_id in initial_values: + init_data = initial_values[node_id] + # 加载初始输入值(用于渐进式暴露判断) + for port_name, port_value in init_data.get('init_inputs', {}).items(): + node.init_input_values[port_name] = port_value + + # 【评测用】加载 golden 输入值(用于验证模型传入的参数是否正确) + for input_port_data in node_data.get('inputs', []): + if 'value' in input_port_data: + node.golden_input_values[input_port_data['name']] = input_port_data['value'] + + # 【评测用】加载 golden 输出值(用于验证工具调用是否正确,以及 Item 节点的 content) + for output_port_data in node_data.get('outputs', []): + if 'value' in output_port_data: + node.golden_output_values[output_port_data['name']] = output_port_data['value'] + + # For Items, set content from golden_output_values + if node.type == "Item" and node.golden_output_values: + # Item 的 content 是其第一个 golden 输出值 + node.content = list(node.golden_output_values.values())[0] + + # 第二步:应用渐进式暴露机制 + # 检查所有节点,根据参数齐全情况释放源头节点(工具 + Item) + _apply_progressive_reveal_at_init(scenario) + +def _build_node_info(node: Node, raw_nodes_data: Dict[str, Any]) -> Dict[str, Any]: + """ + 构建节点信息(工具或物品) + + Args: + node: 节点对象 + raw_nodes_data: 原始节点数据(用于获取 template_id 等) + + Returns: + 节点信息字典 + """ + if node.type == "Tool": + # 过滤掉输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口) + # 这些端口仅用于控制掉落机制,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + tool_info = { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Tool", + "inputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.inputs if p.type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]], + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id(工具的标准名称) + if node.id in raw_nodes_data: + node_data = raw_nodes_data[node.id] + template_id = node_data.get('template_id') + if template_id: + tool_info['template_id'] = template_id + + return tool_info + + elif node.type == "Item": + return { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Item" + } + + else: + return { + "id": node.id, + # "name": node.name, + "type": node.type + } + +def _get_initial_observation(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]) -> Dict[str, Any]: + """ + Generate initial observation for the agent (what they see when entering the room). + + 策略: + - Tools: 只显示名称和描述,不显示接口定义。需要 investigate 才能获得详细接口信息。 + - Items: 只显示存在,不显示内容。需要 investigate 才能获得内容值。 + - init_inputs: 作为"可用信息"告诉模型,这些是可以用作工具参数的初始值。 + - init_outputs: 不告诉模型(这些是答案,需要模型通过调用工具获得)。 + """ + available_entities = [] # 统一的实体列表(Tools 和 Items) + available_information = [] # 可用的初始信息(来自 init_inputs) + + # 从 metadata.initial_values 提取 init_inputs 作为可用信息 + # 只提供值本身,不透露这些值对应哪个节点的哪个参数,让模型自己推理 + # 注意:跳过源头 Item(没有入边的 Item)的 init_inputs,因为它们在密室中完全用不到 + initial_values = metadata.get('initial_values', {}) + # initial_values字段的格式 + # "initial_values": { + # "terminal_1": { + # "init_inputs": {}, + # "init_outputs": { + # "text_output": "System initialization complete.", + # "hex_output": "48656c6c6f20576f726c64", + # "item_dispenser": "掉落了一张纸条,上面写着“请勿随意触摸终端”" + # } + # } + # } + for node_id, init_data in initial_values.items(): + # 获取节点信息,判断是否为源头 Item + node = scenario.nodes.get(node_id) + if node and node.type == "Item": + # 检查是否为源头 Item(没有入边) + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,检查是否有 init_inputs + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 有 init_inputs,需要暴露这些参数 + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + # 处理完后跳过后续的通用逻辑 + continue + + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 为每个 init_input 值创建一个信息条目(不包含 source_node 和 parameter 信息) + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + + for node in scenario.nodes.values(): + if node.is_revealed: + # Tools: 只显示基本信息,提示可以 investigate 查看详细接口 + if node.type == "Tool": + tool_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Tool", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the tool's detailed interface information for calling" + } + # 只在 name 非空时添加 + # if node.name: + # tool_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_info["description"] = node.description + + available_entities.append(tool_info) + + # Items: 只显示基本信息,提示可以 investigate 查看内容 + elif node.type == "Item": + item_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Item", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the item's content" + } + # 只在 name 非空时添加 + # if node.name: + # item_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + item_info["description"] = node.description + + available_entities.append(item_info) + + return { + "narrative": scenario.intro_narrative, + "available_entities": available_entities, # 使用统一的实体列表 + "available_information": available_information, # 可用的初始信息(只包含 init_inputs) + "win_node_id": scenario.win_node_id # 胜利节点ID,让模型知道需要关注哪个节点 + } + +@app.post("/env/reset") +def reset_case(case_id: str = None, case_file_path: str = None, session_id: str = None): + """Loads a specific case from file and resets it. + + Args: + case_id: Optional case ID for resetting an existing case + case_file_path: Path to case file for loading a new case + session_id: Optional session ID to ensure isolation between concurrent evaluations + """ + logger.info(f"Reset request - case_id: {case_id}, case_file_path: {case_file_path}, session_id: {session_id}") + STATS["case_loads"] += 1 + + if case_file_path: + if not os.path.exists(case_file_path): + logger.error(f"Case file not found: {case_file_path}") + raise HTTPException(status_code=404, detail=f"File not found: {case_file_path}") + try: + with open(case_file_path, "r", encoding="utf-8") as f: + file_data = json.load(f) + + # 转换格式:从 DAG executor 生成的格式转换为 GraphScenario 格式 + # 1. 提取 metadata + metadata = file_data.get('metadata', {}) + + # 2. 生成 case_id, title, intro_narrative + # 【修复】为每个评测会话生成唯一的 case_id,防止并发评测时状态污染 + base_name = os.path.basename(case_file_path).replace('.json', '').replace('_full', '').replace('_full2', '') + + if session_id: + # 如果提供了 session_id,使用它来确保唯一性 + case_id = f"{base_name}_{session_id}" + else: + # 否则使用时间戳和随机数确保唯一性 + unique_suffix = f"{int(time.time() * 1000)}_{random.randint(1000, 9999)}" + case_id = f"{base_name}_{unique_suffix}" + + file_data['case_id'] = case_id + logger.info(f"Generated unique case_id: {case_id} (base: {base_name}, session: {session_id})") + + if 'title' not in file_data: + file_data['title'] = f"Escape Room: {file_data['case_id']}" + + if 'intro_narrative' not in file_data: # 目前的json文件中已经有了intro_narrative字段,不会使用下面一行的内容,而是使用每个评测问题的json文件中的对应字段 + 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]".' + + # 3. 转换 nodes 列表为字典(DAG executor 生成的文件中 nodes 是列表格式) + nodes_dict = {} + for node_data in file_data['nodes']: + nodes_dict[node_data['id']] = node_data # 这里的id是template_id之后可能添加一个后缀 + file_data['nodes'] = nodes_dict # 把列表转成一个字典 + + # 4. 添加缺失的字段 + if 'difficulty' not in file_data: + file_data['difficulty'] = metadata.get('total_nodes', 5) + + if 'win_node_id' not in file_data: + file_data['win_node_id'] = metadata.get('win_node_id', '') + + scenario = GraphScenario(**file_data) + + # Extract raw nodes data for template_id access + # nodes 已经在上面转换为字典格式 + raw_nodes_data = file_data.get('nodes', {}) + RAW_NODES_DATA[scenario.case_id] = raw_nodes_data + + # Store metadata for initial values access + FILE_METADATA[scenario.case_id] = metadata + + logger.info(f"Successfully parsed case file: {scenario.case_id}, nodes: {len(scenario.nodes)}, edges: {len(scenario.edges)}") + except Exception as e: + logger.error(f"Failed to load case file: {str(e)}", exc_info=True) + raise HTTPException(status_code=500, detail=f"Failed to load case file: {str(e)}") + + # Initialize node state and load values + _initialize_node_values(scenario, raw_nodes_data, metadata) + + SCENARIOS[scenario.case_id] = scenario + simulator = ToolSimulator() + SIMULATORS[scenario.case_id] = simulator + + 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'])}") + + # 生成初始观察信息(进入密室后看到的环境) + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + ''' + initial_observation的格式: + { + "narrative": scenario.intro_narrative, + "available_entities": available_entities # 使用统一的实体列表 + "available_information": available_information # 可用的初始信息(只包含 init_inputs) + } + ''' + + return { + "ok": True, + "message": f"Case loaded from {case_file_path}", + "case_id": scenario.case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果没有提供 case_file_path,但提供了 case_id,则尝试从内存重置 + if case_id and case_id in SCENARIOS: + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + metadata = FILE_METADATA.get(case_id, {}) + + # Reset dynamic fields and re-apply progressive reveal + # 重新初始化节点状态(包括渐进式暴露) + _initialize_node_values(scenario, raw_nodes_data, metadata) + + 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'])}") + + # 生成初始观察信息 + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + + return { + "ok": True, + "message": f"Case {case_id} reset.", + "case_id": case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果既没有 case_file_path,也没有在内存中找到,返回错误 + raise HTTPException( + status_code=400, + detail="Must provide case_file_path to load a new case, or use case_id to reset an existing case." + ) + +class InvestigateRequest(BaseModel): + node_id: str + +@app.post("/env/{case_id}/investigate") +def investigate(case_id: str, req: InvestigateRequest): + """ + Investigates a Tool or Item to reveal detailed information. + + - For Tools: Returns detailed interface information (inputs/outputs) needed to call the tool + - For Items: Returns content value and triggers hidden item drops + """ + logger.info(f"Investigate request - case_id: {case_id}, node_id: {req.node_id}") + STATS["investigates"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + node = scenario.nodes[req.node_id] + + if not node.is_revealed: + logger.warning(f"Attempt to investigate hidden node: {req.node_id}") + return {"ok": False, "error": "Node is not visible yet."} + + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + newly_revealed = [] + + # 处理 Tool 的 investigate + if node.type == "Tool": + logger.info(f"Investigating tool: {req.node_id}") + + # 返回工具的详细接口信息 + # id 字段使用 node.id(节点唯一标识),agent 用这个字段识别和调用具体的节点 + # template_id 是工具类型标识符,Agent 内部用于判断工具特性(如 terminal 类工具参数可选) + # 注意:只过滤输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口),这些端口仅用于控制掉落,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + # 【端口上游依赖提示 & 初始值直接给出】 + # 针对参数语义模糊(全为数字类型)的工具,在 investigate 返回信息中标注 + # 哪个输入端口来自哪个上游节点(upstream_from)。 + # 对于所有工具:若该节点不是纯源头节点(有任意数据流入边), + # 且某个端口没有上游入边(值来自初始可见参数),则直接给出该端口的 golden input 值。 + AMBIGUOUS_TOOLS = { + "num_base_convert", "calc_modexp", "calc_modexp_int", + "calc_inv_mod", "calc_inv_mod_int", "crypto_rsa_decrypt_hex", "geo_haversine" + } + # Terminal 类工具自带参数对错反馈机制,玩家/模型可自行试错, + # 无需在 investigate 时直接暴露 init_value + SELF_FEEDBACK_TOOLS = { + "terminal_1", "terminal_2", + "Logic Terminal", "Math Terminal", "Encryption Terminal", "Sequence Terminal" + } + _template_id_for_hint = raw_nodes_data.get(node.id, {}).get("template_id", "") + # 构建数据流入边映射(对所有工具):{target_port -> (source_node_id, source_port)} + _upstream_map = {} + for _edge in scenario.edges: + if (_edge.target_id == node.id + and _edge.connection_type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM] + and _edge.target_port is not None): + _upstream_map[_edge.target_port] = (_edge.source_id, _edge.source_port) + # 判断该节点是否有任意数据流入边(即不是纯源头节点) + _has_any_upstream = len(_upstream_map) > 0 + # 判断该节点是否有任意入边(包括 ITEM/HIDDEN_ITEM 掉落边) + # 有任意入边(含掉落边)但无数据流入边的节点,其输入来自初始可见参数,应直接给出 + _has_any_edge = any(_edge.target_id == node.id for _edge in scenario.edges) + # 构建 inputs 列表 + _inputs_list = [] + for p in node.inputs: + if p.type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + continue + port_dict = {"name": p.name, "type": p.type, "description": p.description} + if p.name in _upstream_map: + # 该端口有上游数据流依赖,且属于语义模糊工具 → 标注来源 + if _template_id_for_hint in AMBIGUOUS_TOOLS: + src_node_id, src_port = _upstream_map[p.name] + port_dict["upstream_from"] = f"{src_node_id}.{src_port}" if src_port else src_node_id + elif _has_any_edge and _template_id_for_hint not in SELF_FEEDBACK_TOOLS: + # 该节点有任意入边,但此端口没有数据流入边 → 值来自初始可见参数,直接给出 + # 排除自带反馈机制的 terminal 类工具(它们通过执行结果反馈对错,无需提前暴露参数值) + golden_val = node.golden_input_values.get(p.name) + if golden_val is not None: + port_dict["init_value"] = golden_val + _inputs_list.append(port_dict) + + tool_details = { + "id": node.id, # 节点 ID,用于唯一标识和调用这个具体节点 + "type": "Tool", + "inputs": _inputs_list, + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id 用于 Agent 内部判断工具类型(不会展示给被测模型) + if node.id in raw_nodes_data: + template_id = raw_nodes_data[node.id].get('template_id') + if template_id: + tool_details["_template_id"] = template_id # 使用下划线前缀标记为内部字段 + + # 只在 name 非空时添加 + # if node.name: + # tool_details["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_details["description"] = node.description + + # 添加 narrative 字段(如果存在) + if node.id in raw_nodes_data: + narrative = raw_nodes_data[node.id].get('narrative') + if narrative: + tool_details['narrative'] = narrative + + # 不再返回 init_values,避免泄漏答案 + # investigate 只应该返回工具的接口定义,不应该暴露初始值 + + # 【新增】检查该 Tool 是否有待触发的 HIDDEN_ITEM 掉落 + # 如果该工具已按照 golden_input 正确执行,且有 HIDDEN_ITEM 输出边,则触发掉落 + if node.has_hidden_item_ready: + logger.info(f"Tool has HIDDEN_ITEM ready - triggering passive drop for: {req.node_id}") + + # 遍历该工具的所有 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + # 重置标志,已经触发过了,避免重复 + node.has_hidden_item_ready = False + + logger.info(f"Tool investigation successful - node: {req.node_id}, revealed: {len(newly_revealed)}") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Tool", + "details": tool_details + } + + # 如果有新掉落的节点,添加到响应中 + if newly_revealed: + result["newly_revealed"] = newly_revealed + + return result + + # 处理 Item 的 investigate + elif node.type == "Item": + logger.info(f"Investigating item: {req.node_id}") + + # 【第一步】检查该 Item 是否有需要参数的输入端口 + # 如果有,且尚未通过 use_item 验证,则不返回内容,只返回参数要求 + required_inputs = [] + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + inputs_info = raw_node.get('inputs', []) + required_inputs = [ + { + "name": inp.get("name"), + "type": inp.get("type"), + "description": inp.get("description", "") + } + for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + # 如果有 required_inputs 且尚未通过 use_item 验证(if_success == False) + # 则不返回内容,只返回参数要求提示 + if required_inputs and not node.if_success: + logger.info(f"Item has required inputs and not yet unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "required_inputs": required_inputs + } + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + param_names = ', '.join([inp['name'] for inp in required_inputs]) + 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}" + + return result + + # 【新增】如果有 required_inputs 且已经通过 use_item 验证(if_success == True) + # 则返回提示:该节点已经被成功解决 + if required_inputs and node.if_success: + logger.info(f"Item has required inputs and already unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "message": "This item has already been successfully unlocked by you." + } + return result + + # 【第二步】该 Item 没有 required_inputs 或已通过验证,返回内容 + # 1. 返回 Item 的 golden_output_values(即 Item 的内容) + # 注意:某些 Item 仅用于触发 HIDDEN_ITEM 掉落,没有实际内容 + has_actual_content = bool(node.golden_output_values) or node.content is not None + content = node.golden_output_values if node.golden_output_values else node.content + + # 【关键】将 golden_output_values 追加到 actual_outputs_history,标记该 Item 已被 investigate + # 这样在渐进式暴露时,这些值才会被加入可见值集合 + # 即使是空字典(仅触发 HIDDEN_ITEM 的 Item),也要记录,以便渐进式暴露逻辑知道该 Item 已被调查 + if node.golden_output_values is not None: + node.actual_outputs_history.append(dict(node.golden_output_values)) + + # 2. Trigger Hidden Item Drops (Passive Drop) + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + logger.info(f"Item investigation successful - node: {req.node_id}, has_content: {has_actual_content}, revealed: {len(newly_revealed)}") + + # 【渐进式暴露】旧机制(基于 golden_input)已禁用 + # 现在完全由 ITEM/HIDDEN_ITEM 边触发控制节点可见性 + # 上面的 HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, node.golden_output_values or {}, node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # logger.info(f"Progressive reveal after Item investigate: {len(progressive_revealed)} nodes now ready") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Item" + } + + # 只在有实际内容时才添加 content 字段 + # 对于仅触发 HIDDEN_ITEM 掉落的 Item,不返回 content 字段,避免返回 None 或空字典让模型困惑 + if has_actual_content: + result["content"] = content + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型通过 investigate 获得内容后,需要自己识别这是否是胜利字符串 + + return result + + else: + logger.warning(f"Attempt to investigate unknown node type: {req.node_id} (type: {node.type})") + return {"ok": False, "error": f"Cannot investigate node type: {node.type}"} + +class ToolCallRequest(BaseModel): + node_id: str # 使用 node_id 精确指定要调用的节点 + arguments: Dict[str, Any] + +@app.post("/env/{case_id}/tool_call") +def tool_call(case_id: str, req: ToolCallRequest): + """Executes a tool and triggers item drops.""" + logger.info(f"Tool call request - case_id: {case_id}, node_id: {req.node_id}, args: {list(req.arguments.keys())}") + STATS["tool_calls"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + + # 通过 node_id 精确查找节点 + node_id = req.node_id + if node_id not in scenario.nodes: + logger.error(f"Node not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + tool_node = scenario.nodes[node_id] + + if not tool_node: + logger.error(f"Tool not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Tool not found") + + if not tool_node.is_revealed: + logger.warning(f"Attempt to call hidden tool: {node_id}") + return {"ok": False, "error": "Tool is not visible yet."} + + if tool_node.type != "Tool": + logger.warning(f"Attempt to call non-tool node: {node_id} (type: {tool_node.type})") + return {"ok": False, "error": "Only tools can be called."} + + # 1. Execute Tool (Real Execution via Simulator) + simulator = SIMULATORS[case_id] + + # Get tool name from template_id if available, otherwise use node name + tool_name = tool_node.name + if case_id in RAW_NODES_DATA and node_id in RAW_NODES_DATA[case_id]: + template_id = RAW_NODES_DATA[case_id][node_id].get('template_id') + if template_id: + tool_name = template_id + + # 文件处理工具和 Terminal 需要验证输入并返回预先计算的输出 + # 传递节点的实际输入输出值(从 DAG 执行后填充的数据) + tool_arguments = dict(req.arguments) # Make a copy + + # 传递节点的 golden values(从 JSON 的 inputs[].value 和 outputs[].value 加载) + # 用于在评测阶段验证被测模型传入的参数是否正确 + if tool_node.golden_input_values: + tool_arguments['_golden_inputs'] = tool_node.golden_input_values + if tool_node.golden_output_values: + tool_arguments['_golden_outputs'] = tool_node.golden_output_values + + logger.debug(f"Executing tool {tool_name} (node: {tool_node.name}) with args {tool_arguments}") + + try: + output_values = simulator.execute(tool_name, tool_arguments) + logger.info(f"Tool invoked - {tool_name}: {list(output_values.keys())}") + except Exception as e: + logger.error(f"Tool execution failed - {tool_name}: {str(e)}", exc_info=True) + return {"ok": False, "error": f"Tool execution failed: {str(e)}"} + + # 检查验证结果(精细化错误反馈) + validation = output_values.pop("_validation", {"valid": True}) + + if not validation["valid"]: + # 根据错误类型构造友好的错误消息 + error_type = validation.get("error_type") + + if error_type == "missing_required": + missing = validation.get("missing_params", []) + error_msg = f"Error: Missing required parameters {', '.join(missing)}" + + elif error_type == "type_error": + param = validation.get("param_name") + message = validation.get("message", "Parameter type error") + error_msg = f"Error: {message}" + + elif error_type == "incomplete_optional": + provided = validation.get("provided_params", []) + missing = validation.get("missing_params", []) + error_msg = ( + f"Hint: You provided some parameters ({', '.join(provided)}), " + f"but may also need: {', '.join(missing)}.\n" + f"Trying to provide these parameters together might yield better results." + ) + + elif error_type == "value_mismatch": + param = validation.get("param_name") + hint = validation.get("hint", "Parameter value may be incorrect") + error_msg = f"Hint: {hint}.\nPlease check if this parameter value meets the requirements." + + else: + error_msg = validation.get("hint") or validation.get("message", "Parameter validation failed") + + logger.info(f"Tool validation failed - {tool_name}: {error_type}") + return { + "ok": False, + "error": error_msg, + "error_type": error_type + } + + # Simulate success + tool_node.if_success = True + + # 【关键】将本次执行的输出值追加到历史列表(用于渐进式暴露判断) + # 每次调用都会记录,不会覆盖之前的执行结果 + tool_node.actual_outputs_history.append(dict(output_values)) + + # 2. 检查是否应该触发掉落(只有输入参数正确时才掉落) + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, tool_node.golden_input_values) + + newly_revealed = [] + investigate_hints = [] # 提示模型哪些节点可以 investigate 来发现隐藏内容 + + if inputs_match_golden: + logger.info(f"✓ Tool inputs match golden - node: {node_id}, triggering drops") + + # 检查该工具是否有 ITEM 或 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == tool_node.id: + target_node = scenario.nodes[edge.target_id] + + # ITEM 边:立即掉落(主动掉落) + if edge.connection_type == InterfaceType.ITEM: + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from {node_id})") + + # HIDDEN_ITEM 边:不立即掉落,标记并提示(被动掉落) + elif edge.connection_type == InterfaceType.HIDDEN_ITEM: + # 标记该工具有待触发的 HIDDEN_ITEM 掉落 + tool_node.has_hidden_item_ready = True + + # 提示模型可以 investigate 这个工具来发现隐藏内容 + hint_info = { + "tool_id": tool_node.id, + "hint": f"Tool '{tool_node.id}' seems to hide something, try investigating it to discover more information" + } + # if tool_node.name: + # hint_info["tool_name"] = tool_node.name + + investigate_hints.append(hint_info) + logger.info(f"HIDDEN_ITEM ready: {tool_node.id} -> {target_node.id} (will drop on investigate)") + else: + logger.info(f"✗ Tool inputs do NOT match golden - node: {node_id}, no drops triggered") + + response = { + "ok": True, + "message": "Tool invoked", + "output_values": output_values # Return raw outputs to Agent + } + + # 【新增】对源头节点进行参数验证反馈 + # 源头节点:没有数据流入边的节点,这些节点的参数需要模型自己推理 + # 验证模型使用的参数是否正确,并提供明确的反馈 + if _is_source_node(node_id, scenario) and tool_node.golden_input_values: + validation_feedback = _get_parameter_validation_feedback(req.arguments, tool_node.golden_input_values) + + if validation_feedback["all_correct"]: + # 用户提交了全部 golden 参数且全部正确 + response["parameter_feedback"] = { + "status": "correct", + "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." + } + logger.info(f"✓ Source node parameters all correct - node: {node_id}") + elif validation_feedback["incorrect_params"]: + # 有提交了但值错误的参数,只对这些参数给出反馈 + incorrect_list = [] + for param_name in validation_feedback["incorrect_params"]: + incorrect_list.append(f" - Parameter '{param_name}' is incorrect") + + correct_info = "" + if validation_feedback["correct_params"]: + correct_info = f"\n✓ Correct parameters: {', '.join(validation_feedback['correct_params'])}" + + response["parameter_feedback"] = { + "status": "incorrect", + "message": ( + f"⚠️ Some parameters are incorrect:\n" + + "\n".join(incorrect_list) + + correct_info + + 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." + ), + "incorrect_params": validation_feedback["incorrect_params"], + "correct_params": validation_feedback["correct_params"] + } + logger.info(f"✗ Source node parameters incorrect - node: {node_id}, incorrect: {validation_feedback['incorrect_params']}") + # else: 部分提交且全部正确 → 不给任何 parameter_feedback,避免对未提交的参数发表意见 + + # 检查工具调用是否完全正确(输出与 golden outputs 匹配) + # 用于给模型正向反馈,让它知道这个工具已经正确调用过,避免重复调用 + # 注意:只有当输出完全匹配时才标记为 correct,不会在错误时提供具体错误信息 + # if tool_node.golden_output_values and output_values: + # is_correct = True + # for port_name, expected_value in tool_node.golden_output_values.items(): + # actual_value = output_values.get(port_name) + # if str(actual_value) != str(expected_value): + # is_correct = False + # break + + # if is_correct: + # response["tool_call_correct"] = True + # logger.info(f"✓ Tool called with correct result - node: {node_id}") + + # 只在有新内容掉落时才返回 newly_revealed + if newly_revealed: + response["newly_revealed"] = newly_revealed + + # 添加 investigate 提示(对于有待触发 HIDDEN_ITEM 掉落的工具) + if investigate_hints: + response["investigate_hints"] = investigate_hints + + # 3. 渐进式暴露机制 - 现在完全由 ITEM/HIDDEN_ITEM 边控制 + # 旧机制(基于 golden_input 检查)已被禁用 + # 新机制中,节点的可见性只由 ITEM/HIDDEN_ITEM 边触发决定 + # 上面的 ITEM/HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, output_values, tool_node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # response["newly_revealed"] = newly_revealed + # logger.info(f"Progressive reveal: {len(progressive_revealed)} nodes now ready") + + # Check if this is the win node + if node_id == scenario.win_node_id: + # 验证输出值是否等于预期的胜利值 + # 从节点的 golden_output_values 中获取预期值(在 _initialize_node_values 时从 JSON 加载) + expected_outputs = tool_node.golden_output_values + + # 检查实际输出是否与预期输出匹配 + is_correct = False + victory_string = None + mismatch_info = [] + + if expected_outputs and output_values: + # 检查每个预期输出端口的值是否匹配 + is_correct = True + for port_name, expected_value in expected_outputs.items(): + actual_value = output_values.get(port_name) + if actual_value != expected_value: + is_correct = False + mismatch_info.append(f"Port '{port_name}': expected '{expected_value}', actual '{actual_value}'") + logger.warning(f"Win node output mismatch - port: {port_name}, expected: {expected_value}, actual: {actual_value}") + + # 如果所有输出都匹配,使用第一个输出作为胜利字符串 + if is_correct and output_values: + victory_string = list(output_values.values())[0] + else: + logger.warning(f"Win node called but missing output values - expected: {expected_outputs}, actual: {output_values}") + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型调用工具获得输出后,需要自己识别这是否是胜利字符串并提交 + if is_correct: + logger.info(f"🎯 Win node called with correct output - case: {case_id}, node: {node_id}, victory: {victory_string}") + else: + logger.info(f"❌ Win node called with incorrect output - case: {case_id}, node: {node_id}") + + return response + +class UseItemRequest(BaseModel): + node_id: str = Field(..., description="The ID of the Item node to use (must be Item type)") + arguments: Dict[str, Any] = Field(default_factory=dict, description="Input arguments to provide to the item") + +@app.post("/env/{case_id}/use_item") +def use_item(case_id: str, req: UseItemRequest): + """ + Use an Item node by providing input arguments. + + This is specifically for Item nodes that require parameters to be "unlocked" or "activated", + such as containers that need a password/fingerprint. + + - Validates that the node is of type Item + - Checks if provided arguments match the item's golden_input_values + - If match: triggers ITEM-type edge drops and returns the item's content + - If not match: returns error message + """ + logger.info(f"Use item request - case_id: {case_id}, node_id: {req.node_id}, args: {req.arguments}") + STATS["use_items"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + item_node = scenario.nodes[req.node_id] + + if not item_node.is_revealed: + logger.warning(f"Attempt to use hidden item: {req.node_id}") + return {"ok": False, "error": "Item is not visible yet."} + + if item_node.type != "Item": + logger.warning(f"Attempt to use non-item node: {req.node_id} (type: {item_node.type})") + return {"ok": False, "error": "Only Item nodes can be used with use_item. Tools should be called with tool_call."} + + # 【新增】检查该 Item 是否已经被成功解锁 + # 如果已经被正确使用过,直接返回成功提示 + if item_node.if_success: + logger.info(f"Item already unlocked, returning success message: {req.node_id}") + return { + "ok": True, + "message": "This item has already been successfully unlocked by you." + } + + # 检查该 Item 是否真的需要通过 use_item 提供参数 + # 只有当 Item 有非 Item/Hidden_Item 类型的输入时,才应该使用 use_item + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + non_hidden_inputs = [ + inp for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + if not non_hidden_inputs: + # 该 Item 不需要参数,应该只使用 investigate + logger.warning(f"Attempt to use_item on a node that doesn't require parameters: {req.node_id}") + return { + "ok": False, + "error": "This item does not require parameters. Please use investigate to examine the item directly." + } + + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, item_node.golden_input_values) + + if not inputs_match_golden: + logger.info(f"✗ Item inputs do NOT match golden - node: {req.node_id}") + # 提供更详细的错误信息,帮助 Agent 理解问题 + # 只显示非 Item/Hidden_Item 类型的参数(Hidden_Item 由系统自动处理) + expected_params = [] + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + expected_params = [ + inp.get("name") for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + provided_params = list(req.arguments.keys()) if req.arguments else [] + + # 检查参数名是否匹配 + if set(expected_params) == set(provided_params): + # 参数名正确但值不匹配 - 不泄漏正确的值 + error_msg = f"Parameter names are correct, but the parameter values are incorrect. Please try using different parameter values." + else: + error_msg = f"Parameter names do not match. Expected parameter names: {expected_params}, you provided: {provided_params}." + + return { + "ok": False, + "error": error_msg + } + + logger.info(f"✓ Item inputs match golden - node: {req.node_id}, activating item") + + # 标记该 Item 已被正确使用 + item_node.if_success = True + + # 将 golden_output_values 追加到 actual_outputs_history + if item_node.golden_output_values: + item_node.actual_outputs_history.append(dict(item_node.golden_output_values)) + + # 触发 ITEM 类型边的掉落 + newly_revealed = [] + for edge in scenario.edges: + if edge.source_id == item_node.id and edge.connection_type == InterfaceType.ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from use_item on {req.node_id})") + + # 检查是否为 Win Node + win_node_id = scenario.win_node_id + is_win_node = (req.node_id == win_node_id) + + # 构建返回结果 + result = { + "ok": True, + "message": "Item used successfully.", + "content": item_node.golden_output_values if item_node.golden_output_values else None + } + + # 获取 narrative(如果存在) + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + narrative = raw_nodes_data[req.node_id].get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 如果是 Win Node,只记录日志 + if is_win_node: + logger.info(f"Win node (Item) unlocked via use_item - case: {case_id}, node: {req.node_id}") + + return result + + +class SubmitAnswerRequest(BaseModel): + answer: str = Field(..., description="The victory string to submit") + +@app.post("/env/{case_id}/submit_answer") +def submit_answer(case_id: str, req: SubmitAnswerRequest): + """ + 提交答案接口 + 被测模型在获得胜利字符串提示后,需要调用此接口提交答案 + """ + logger.info(f"Submit answer request - case_id: {case_id}, answer: {req.answer}") + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + + # 获取 win_node 的 golden_output_values + if not scenario.win_node_id: + logger.error(f"No win node defined for case: {case_id}") + return { + "ok": False, + "error": "This case has no victory node defined" + } + + win_node = scenario.nodes.get(scenario.win_node_id) + if not win_node: + logger.error(f"Win node not found: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node does not exist" + } + + # 获取正确的胜利字符串(取第一个 golden_output_value) + if win_node.golden_output_values: + correct_answer = list(win_node.golden_output_values.values())[0] + else: + logger.error(f"Win node has no golden_output_values: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node has no correct answer" + } + + # 验证提交的答案 + if req.answer == correct_answer: + logger.info(f"🎉 CORRECT ANSWER SUBMITTED - case: {case_id}, answer: {req.answer}") + return { + "ok": True, + "is_win": True, + "victory_message": f"🎉 Congratulations on successfully escaping the room! Your answer is correct: {req.answer}" + } + else: + logger.info(f"❌ INCORRECT ANSWER SUBMITTED - case: {case_id}, submitted: {req.answer}, correct: {correct_answer}") + return { + "ok": True, + "is_win": False, + "error": f"The submitted answer is incorrect. You submitted: {req.answer}" + } + +if __name__ == "__main__": + + uvicorn.run(app, host="0.0.0.0", port=8000) \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-5eefda51/environment/puzzle/upstream/simulator.py b/tasks/agentescape-25-skeleton-5eefda51/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-25-skeleton-5eefda51/environment/puzzle/upstream/simulator.py @@ -0,0 +1,2911 @@ +import hashlib +import hmac +import base64 +import binascii +import zlib +import json +import uuid +import math +import re +from typing import Dict, Any, List + +class ToolSimulator: + def __init__(self): + """工具模拟器 + + 文件处理工具(zip_unzip, zip_unzip_file, zip_unzip_item, json_get, csv_query, + regex_search, graph_shortest_path)不需要真实文件系统。 + 这些工具只验证输入参数,然后返回预先初始化好的 golden_outputs。 + """ + self.tool_map = { + # 数论 + "calc_bigmul": self.calc_bigmul, + "calc_modexp": self.calc_modexp, + "calc_modexp_int": self.calc_modexp_int, + "calc_gcd": self.calc_gcd, + "calc_gcd_int": self.calc_gcd_int, + "calc_inv_mod": self.calc_inv_mod, + "calc_inv_mod_int": self.calc_inv_mod_int, + + # 哈希 + "hash_sha256": self.hash_sha256, + "hash_md5": self.hash_md5, + "hmac_sha256": self.hmac_sha256, + + # 编码 + "base64_decode": self.base64_decode, + "base64_encode": self.base64_encode, + "hex_decode": self.hex_decode, + "hex_encode": self.hex_encode, + "zlib_inflate": self.zlib_inflate, + "zlib_deflate": self.zlib_deflate, + + # 文件 + "zip_unzip": self.zip_unzip, + "zip_unzip_file": self.zip_unzip_file, + "zip_unzip_item": self.zip_unzip_item, + "regex_search": self.regex_search, + "json_get": self.json_get, + "csv_query": self.csv_query, + "code_py_exec": self.code_py_exec, + + # 图 + "graph_shortest_path": self.graph_shortest_path, + + # 加解密 (简化模拟) + "crypto_aes_cbc_decrypt": self.crypto_aes_cbc_decrypt, + "crypto_rsa_decrypt_hex": self.crypto_rsa_decrypt_hex, + + # 其他 + "num_base_convert": self.num_base_convert, + "time_convert": self.time_convert, + "checksum_crc32": self.checksum_crc32, + "geo_haversine": self.geo_haversine, + "otp_totp_generate": self.otp_totp_generate, + "unicode_norm": self.unicode_norm, + "text_bidi_sanitize": self.text_bidi_sanitize, + "text_xor_hex": self.text_xor_hex, + "text_rotN": self.text_rotN, + "luhn_check": self.luhn_check, + "iban_validate": self.iban_validate, + + # 物理 + "matter_synthesizer": self.matter_synthesizer, + + # 终端机 + "terminal_1": self.terminal_1, + "terminal_2": self.terminal_2, + "Logic Terminal": self.logic_terminal, + "Math Terminal": self.math_terminal, + "Encryption Terminal": self.crypt_terminal, + "Sequence Terminal": self.sequence_terminal + } + + def execute(self, tool_name: str, inputs: Dict[str, Any]) -> Dict[str, Any]: + if tool_name not in self.tool_map: + # Fallback for unknown tools: return dummy outputs based on expected output types + # This should ideally not happen if all tools are implemented + return {} + + try: + return self.tool_map[tool_name](inputs) + except Exception as e: + print(f"Error executing {tool_name}: {e}") + # Return empty or error indication? For generation, we might want to fail hard or return dummy. + # For now, return dummy to keep flow going, but log error. + return {} + + # --- Implementations --- + + def calc_bigmul(self, inputs): + # Check if required parameters are present + if "a" not in inputs or "b" not in inputs: + raise ValueError("Missing required parameters 'a' and/or 'b'") + + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + return {"product": str(a * b)} + except (ValueError, TypeError) as e: + raise ValueError(f"Failed to convert parameters to integers: {str(e)}") + + def calc_modexp(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + try: + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if isinstance(base, str): + base = int(base) + elif not isinstance(base, int): + raise ValueError("Parameter 'base' must be a string or integer") + + if isinstance(exp, str): + exp = int(exp) + elif not isinstance(exp, int): + raise ValueError("Parameter 'exp' must be a string or integer") + + if isinstance(mod, str): + mod = int(mod) + elif not isinstance(mod, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": str(pow(base, exp, mod))} + + def calc_modexp_int(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["base"], int): + raise ValueError("Parameter 'base' must be an integer") + if not isinstance(inputs["exp"], int): + raise ValueError("Parameter 'exp' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": pow(base, exp, mod)} + + def calc_gcd(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + # 计算 GCD 并返回字符串格式(符合 Big_Int 输出类型) + result = math.gcd(a, b) + return {"gcd": str(result)} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def calc_gcd_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["b"], int): + raise ValueError("Parameter 'b' must be an integer") + + # 获取参数 + a = inputs["a"] + b = inputs["b"] + + return {"gcd": math.gcd(a, b)} + + def calc_inv_mod(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + m = inputs["mod"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(m, str): + m = int(m) + elif not isinstance(m, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": str(pow(a, -1, m))} + except ValueError as e: + # 模逆不存在时,返回一个特殊值(用于数据传递) + # 在 DAG 生成阶段,这允许数据流继续 + return {"inv": str(a)} + + def calc_inv_mod_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + a = inputs["a"] + m = inputs["mod"] + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": pow(a, -1, m)} + except ValueError as e: + raise ValueError(f"Modular inverse does not exist: {str(e)}") + + def hash_sha256(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.sha256(text.encode()).hexdigest()} + + def hash_md5(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.md5(text.encode()).hexdigest()} + + def hmac_sha256(self, inputs): + # 参数检查 + if "hex_key" not in inputs: + raise ValueError("Missing required parameter: hex_key") + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["hex_key"], str): + raise ValueError("Parameter 'hex_key' must be a string") + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + try: + key = bytes.fromhex(inputs["hex_key"]) + text = inputs["text"].encode() + return {"hex": hmac.new(key, text, hashlib.sha256).hexdigest()} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def base64_decode(self, inputs): + # 参数检查 + if "data" not in inputs: + raise ValueError("Missing required parameter: data") + + # 类型检查 + if not isinstance(inputs["data"], str): + raise ValueError("Parameter 'data' must be a string") + + data = inputs["data"] + try: + return {"bytes_hex": binascii.hexlify(base64.b64decode(data)).decode()} + except Exception as e: + raise ValueError(f"Base64 decode error: {str(e)}") + + def base64_encode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"b64": base64.b64encode(bytes.fromhex(hex_data)).decode()} + except Exception as e: + raise ValueError(f"Base64 encode error: {str(e)}") + + def hex_decode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"text": bytes.fromhex(hex_data).decode('utf-8', errors='ignore')} + except Exception as e: + raise ValueError(f"Hex decode error: {str(e)}") + + def hex_encode(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + try: + return {"hex": text.encode().hex()} + except Exception as e: + raise ValueError(f"Hex encode error: {str(e)}") + + + # 到此处实现已经更新 + + def zlib_inflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("Parameter 'hex' must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("Missing required parameter: hex") + + try: + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空字符串 + if not hex_data: + raise ValueError("Empty hex string provided") + + # 检查十六进制字符串的有效性 + if len(hex_data) % 2 != 0: + raise ValueError("Hex string must have even length") + + # 检查是否只包含有效的十六进制字符 + if not all(c in '0123456789abcdefABCDEF' for c in hex_data): + raise ValueError("Invalid hex string provided") + + # 尝试解压缩 + return {"text": zlib.decompress(bytes.fromhex(hex_data)).decode('utf-8')} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hex string provided") from e + raise ValueError(f"Invalid zlib data: {e}") from e + except Exception as e: + raise RuntimeError(f"Failed to inflate data: {e}") from e + + def zlib_deflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("Parameter 'text' must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("Missing required parameter: text") + + try: + # 压缩文本 + return {"hex": zlib.compress(text.encode('utf-8')).hex()} + except Exception as e: + raise RuntimeError(f"Failed to deflate data: {e}") from e + + # --- File Operations --- + + def zip_unzip(self, inputs): + """ZIP 解压工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"files": golden_outputs.get("files", "")} + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return {"files": golden_outputs.get("files", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "files" in golden_outputs: + # 验证必需参数 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 检查类型 + if has_zip_id and not isinstance(zip_id, str): + return {"error": "Parameter 'zip_id' must be a string type"} + if has_password and not isinstance(password, str): + return {"error": "Parameter 'password' must be a string type"} + + # 验证输入是否与预期匹配 + if golden_inputs: + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return {"files": golden_outputs["files"]} + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + # 没有golden_inputs但有golden_outputs,直接返回输出 + return {"files": golden_outputs["files"]} + + # 如果没有预期输出,返回空结果 + return {"files": ""} + + def regex_search(self, inputs): + """正则搜索工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"matches": golden_outputs.get("matches", "[]")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "matches" in golden_outputs: + # 提取实际参数 + pattern = inputs.get("pattern") + file_id = inputs.get("file_id") + text = inputs.get("text") + + # 1. 检查必需参数 + if pattern is None: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["pattern"], + "message": "Missing required parameter 'pattern'" + } + } + + # 类型检查 + if not isinstance(pattern, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "pattern", + "message": "Parameter 'pattern' must be a string type" + } + } + if file_id is not None and not isinstance(file_id, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if text is not None and not isinstance(text, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "text", + "message": "Parameter 'text' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合 + provided_params = {} + if pattern is not None: + provided_params["pattern"] = pattern + if file_id is not None: + provided_params["file_id"] = file_id + if text is not None: + provided_params["text"] = text + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数(关键改进) + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_pattern = golden_inputs.get("pattern") + expected_file_id = golden_inputs.get("file_id") + expected_text = golden_inputs.get("text") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_pattern is not None: + if str(pattern) != str(expected_pattern): + incorrect_params.append("pattern") + else: + correct_params.append("pattern") + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_text is not None: + if str(text) != str(expected_text): + incorrect_params.append("text") + else: + correct_params.append("text") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "matches": "[]", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "matches": golden_outputs["matches"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空列表 + return {"matches": "[]"} + + def json_get(self, inputs): + """JSON 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"values": golden_outputs.get("values", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "values" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + jsonpath = inputs.get("jsonpath", "") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if jsonpath is not None and not isinstance(jsonpath, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "jsonpath", + "message": "Parameter 'jsonpath' must be a string type" + } + } + + # 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:jsonpath有默认值"") + provided_params = {} + if file_id is not None: + provided_params["file_id"] = file_id + if jsonpath != "": + provided_params["jsonpath"] = jsonpath + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_jsonpath = golden_inputs.get("jsonpath") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_jsonpath is not None: + if str(jsonpath) != str(expected_jsonpath): + incorrect_params.append("jsonpath") + else: + correct_params.append("jsonpath") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "values": "", + "_validation": validation_info + } + + # 所有验证通过,返回正确输出 + return { + "values": golden_outputs["values"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"values": ""} + + def csv_query(self, inputs): + """CSV 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"rows": golden_outputs.get("rows", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "rows" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + select_columns = inputs.get("select", "") + where_clause = inputs.get("where", "") + + # 1. 检查必需参数 + if file_id is None: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["file_id"], + "message": "Missing required parameter 'file_id'" + } + } + + # 类型检查 + if not isinstance(file_id, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if not isinstance(select_columns, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "select", + "message": "Parameter 'select' must be a string type" + } + } + if not isinstance(where_clause, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "where", + "message": "Parameter 'where' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:select和where有默认值"") + provided_params = {"file_id": file_id} + if select_columns != "": + provided_params["select"] = select_columns + if where_clause != "": + provided_params["where"] = where_clause + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_select = golden_inputs.get("select") + expected_where = golden_inputs.get("where") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_select is not None: + if str(select_columns) != str(expected_select): + incorrect_params.append("select") + else: + correct_params.append("select") + + if expected_where is not None: + if str(where_clause) != str(expected_where): + incorrect_params.append("where") + else: + correct_params.append("where") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "rows": "", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "rows": golden_outputs["rows"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"rows": ""} + + def graph_shortest_path(self, inputs): + """图最短路径工具 + + 如果有 _golden_outputs 或 _init_outputs,验证输入并返回预设输出。 + 否则执行真实的 Dijkstra 算法。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 检查是否在预设模式中(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + if golden_outputs and "path" in golden_outputs: + # 评测阶段但没有 golden_inputs,直接返回 outputs + if not golden_inputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 评测模式:验证输入参数是否匹配 golden 值 + src = inputs.get("src") + dst = inputs.get("dst") + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + + has_src = src is not None and src != "" + has_dst = dst is not None and dst != "" + + # 验证必需参数 + if not has_src or not has_dst: + missing = [] + if not has_src: + missing.append("src") + if not has_dst: + missing.append("dst") + return {"error": "Missing required parameters: " + ", ".join(missing)} + + # 类型检查 + if not isinstance(src, str): + return {"error": "Parameter 'src' must be a string"} + if not isinstance(dst, str): + return {"error": "Parameter 'dst' must be a string"} + + # 验证输入是否匹配期望值 + if golden_inputs: + expected_src = golden_inputs.get("src") + expected_dst = golden_inputs.get("dst") + expected_file_id = golden_inputs.get("file_id") + expected_graph_data = golden_inputs.get("graph_data") + + # 收集验证结果 + incorrect_params = [] + correct_params = [] + + # 检查必需参数是否匹配 + if expected_src is not None: + if str(src) != str(expected_src): + incorrect_params.append("src") + else: + correct_params.append("src") + + if expected_dst is not None: + if str(dst) != str(expected_dst): + incorrect_params.append("dst") + else: + correct_params.append("dst") + + # 检查可选参数(如果在 expected_inputs 中定义了) + if expected_file_id is not None: + if file_id != expected_file_id: + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_graph_data is not None: + if graph_data != expected_graph_data: + incorrect_params.append("graph_data") + else: + correct_params.append("graph_data") + + # 如果有参数不正确,返回详细的反馈 + if incorrect_params: + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 验证通过,返回预设的输出 + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 获取参数(真实执行路径) + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + # Support both src/dst (interface definition) and start/end (original implementation) + start = inputs.get("src") + end = inputs.get("dst") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + raise TypeError("file_id must be a string") + + if graph_data is not None and not isinstance(graph_data, str): + raise TypeError("graph_data must be a string") + + if start is not None and not isinstance(start, str): + raise TypeError("src/start must be a string") + + if end is not None and not isinstance(end, str): + raise TypeError("dst/end must be a string") + + # 检查必需参数 + if file_id is None and graph_data is None: + raise ValueError("Either file_id or graph_data must be provided") + + if start is None: + raise ValueError("src/start parameter is required") + + if end is None: + raise ValueError("dst/end parameter is required") + + # Get graph content + content = None + if file_id is not None: + # 尝试从 VFS 获取(如果存在) + if hasattr(self, 'vfs') and file_id in self.vfs: + content = self.vfs[file_id] + else: + # VFS 不存在或文件不在 VFS 中 + # 返回一个默认的空图结果,或者抛出错误提示需要 init_outputs + raise ValueError( + f"File '{file_id}' not found. For tools that require files, " + f"please provide init_outputs in the initial_values." + ) + elif graph_data is not None: + content = graph_data + + if content is None: + content = "{}" + + try: + # Parse graph data + graph = json.loads(content) + + # 类型检查 + if not isinstance(graph, dict): + raise TypeError("Graph data must be a dictionary") + + # If graph is not in the expected format, try to extract adjacency list + if "nodes" in graph and "edges" in graph: + # 验证nodes和edges的类型 + if not isinstance(graph["nodes"], list): + raise TypeError("Nodes must be a list") + + if not isinstance(graph["edges"], list): + raise TypeError("Edges must be a list") + + # Convert from nodes/edges format to adjacency list + adjacency_list = {} + for node in graph["nodes"]: + # 验证node类型 + if not isinstance(node, dict): + raise TypeError("Each node must be a dictionary") + + # Use node ID as key, not the entire node dictionary + node_id = node.get("id", "") + if node_id: + adjacency_list[node_id] = {} + + for edge in graph["edges"]: + # 验证edge类型 + if not isinstance(edge, dict): + raise TypeError("Each edge must be a dictionary") + + u = edge["from"] + v = edge["to"] + weight = edge.get("weight", 1) # Default to unweighted + + # 类型检查 + if not isinstance(u, str): + raise TypeError("Edge 'from' must be a string") + + if not isinstance(v, str): + raise TypeError("Edge 'to' must be a string") + + if not isinstance(weight, (int, float)): + raise TypeError("Edge weight must be a number") + + if u not in adjacency_list: + adjacency_list[u] = {} + if v not in adjacency_list: + adjacency_list[v] = {} + + adjacency_list[u][v] = weight + # If undirected, add reverse edge + if not edge.get("directed", False): + adjacency_list[v][u] = weight + elif isinstance(graph, dict): + # Already in adjacency list format + adjacency_list = graph + + # 验证邻接表结构 + for node, neighbors in adjacency_list.items(): + if not isinstance(neighbors, dict): + raise TypeError("Adjacency list must be a dictionary of dictionaries") + + for neighbor, weight in neighbors.items(): + if not isinstance(weight, (int, float)): + raise TypeError("Edge weights must be numbers") + else: + raise TypeError("Graph data must be a dictionary") + + # 检查起点和终点是否为空 + if not start: + raise ValueError("Start node cannot be empty") + + if not end: + raise ValueError("End node cannot be empty") + + # 检查起点和终点是否在图中 + if start not in adjacency_list: + raise ValueError(f"Start node '{start}' not found in graph") + + if end not in adjacency_list: + raise ValueError(f"End node '{end}' not found in graph") + + # Dijkstra's algorithm implementation + import heapq + + # Initialize distances and previous nodes + distances = {node: float('infinity') for node in adjacency_list} + previous = {node: None for node in adjacency_list} + distances[start] = 0 + + # Priority queue + pq = [(0, start)] + heapq.heapify(pq) + + while pq: + current_dist, current_node = heapq.heappop(pq) + + # If we've reached the end node, we can break early + if current_node == end: + break + + # Nodes can be added multiple times to the priority queue, but we only process them once + if current_dist > distances[current_node]: + continue + + # Explore neighbors + for neighbor, weight in adjacency_list[current_node].items(): + distance = current_dist + weight + + # If a shorter path is found + if distance < distances[neighbor]: + distances[neighbor] = distance + previous[neighbor] = current_node + heapq.heappush(pq, (distance, neighbor)) + + # Reconstruct the shortest path + path = [] + current = end + while current is not None: + path.append(current) + current = previous[current] + path.reverse() # Reverse to get from start to end + + # Check if path exists + if not path or path[0] != start: + return {"path": "[]", "cost": 0} + + return { + "path": json.dumps(path), + "cost": distances[end] + } + except json.JSONDecodeError as e: + raise ValueError(f"Invalid JSON in graph data: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in graph_shortest_path: {str(e)}") + + # --- Crypto (Simplified) --- + def crypto_aes_cbc_decrypt(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 (使用模板中定义的参数名) + hex_cipher = inputs.get("hex_cipher") + hex_key = inputs.get("hex_key") + hex_iv = inputs.get("hex_iv") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + + if hex_key is not None and not isinstance(hex_key, str): + raise TypeError("hex_key must be a string") + + if hex_iv is not None and not isinstance(hex_iv, str): + raise TypeError("hex_iv must be a string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + + if hex_key is None: + raise ValueError("hex_key parameter is required") + + if hex_iv is None: + raise ValueError("hex_iv parameter is required") + + from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes + from cryptography.hazmat.backends import default_backend + from cryptography.hazmat.primitives import padding + + try: + # Convert hex strings to bytes + ciphertext = bytes.fromhex(hex_cipher) + key = bytes.fromhex(hex_key) + iv = bytes.fromhex(hex_iv) + + # Validate key length (AES-128, AES-192, AES-256) + if len(key) not in [16, 24, 32]: + raise ValueError("Invalid key length. Must be 16, 24, or 32 bytes.") + + if len(iv) != 16: + raise ValueError("Invalid IV length. Must be 16 bytes.") + + # Create cipher object + cipher = Cipher( + algorithms.AES(key), + modes.CBC(iv), + backend=default_backend() + ) + + decryptor = cipher.decryptor() + + # Decrypt the ciphertext + padded_plaintext = decryptor.update(ciphertext) + decryptor.finalize() + + # Remove PKCS7 padding + unpadder = padding.PKCS7(128).unpadder() + plaintext = unpadder.update(padded_plaintext) + unpadder.finalize() + + # Return decrypted text + return {"text": plaintext.decode('utf-8', errors='ignore')} + except ValueError as e: + if "non-hexadecimal number found in fromhex()" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher, hex_key, or hex_iv") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in crypto_aes_cbc_decrypt: {str(e)}") + + def crypto_rsa_decrypt_hex(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_cipher = inputs.get("hex_cipher") + n = inputs.get("n") + d = inputs.get("d") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + if n is not None and not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + if d is not None and not isinstance(d, (int, str)): + raise TypeError("d must be an integer or string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + if n is None: + raise ValueError("n parameter is required") + if d is None: + raise ValueError("d parameter is required") + + try: + # Convert parameters to appropriate types + cipher_int = int(hex_cipher, 16) + n_int = int(n) if isinstance(n, str) else n + d_int = int(d) if isinstance(d, str) else d + + # RSA decryption: plaintext = ciphertext^d mod n + plaintext_int = pow(cipher_int, d_int, n_int) + + # Convert result to hex and then to text + plaintext_hex = hex(plaintext_int)[2:] + + # Pad with leading zero if odd length + if len(plaintext_hex) % 2 != 0: + plaintext_hex = '0' + plaintext_hex + + # Convert hex to bytes and then to text + try: + plaintext_bytes = bytes.fromhex(plaintext_hex) + plaintext_text = plaintext_bytes.decode('utf-8', errors='ignore') + except: + # If decoding fails, return hex representation + plaintext_text = plaintext_hex + + return {"text": plaintext_text} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in crypto_rsa_decrypt_hex: {str(e)}") + + # --- Others --- + def num_base_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + s = inputs.get("s") + from_base = inputs.get("from_base") + to_base = inputs.get("to_base") + + # 类型检查 - 接受 str 或 int + if s is not None and not isinstance(s, (str, int)): + raise TypeError("s must be a string or integer") + + if from_base is not None and not isinstance(from_base, (int, str)): + raise TypeError("from_base must be an integer") + + if to_base is not None and not isinstance(to_base, (int, str)): + raise TypeError("to_base must be an integer") + + # 检查必需参数 + if s is None: + raise ValueError("s parameter is required") + + if from_base is None: + raise ValueError("from_base parameter is required") + + if to_base is None: + raise ValueError("to_base parameter is required") + + try: + # Convert to int if needed + from_base = int(from_base) if isinstance(from_base, str) else from_base + to_base = int(to_base) if isinstance(to_base, str) else to_base + s_str = str(s) + + # 验证基数范围 + if from_base < 2 or from_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + if to_base < 2 or to_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + # Convert from source base to decimal + val = int(s_str, from_base) + + # Convert from decimal to target base + if to_base == 10: + result = str(val) + elif to_base == 16: + result = hex(val)[2:] + elif to_base == 8: + result = oct(val)[2:] + elif to_base == 2: + result = bin(val)[2:] + else: + # Generic base conversion for other bases + if val == 0: + result = "0" + else: + digits = "0123456789abcdefghijklmnopqrstuvwxyz" + result = "" + n = abs(val) + while n: + result = digits[n % to_base] + result + n //= to_base + if val < 0: + result = "-" + result + + return {"str": result} + except ValueError as e: + raise ValueError(f"Invalid number format: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in num_base_convert: {str(e)}") + + def time_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iso = inputs.get("iso") + timestamp = inputs.get("timestamp") + datetime_str = inputs.get("datetime") + from_tz = inputs.get("from_tz") + to_tz = inputs.get("to_tz") + format_str = inputs.get("format") + + # 类型检查 + if iso is not None and not isinstance(iso, str): + raise TypeError("iso must be a string") + + if timestamp is not None and not isinstance(timestamp, (str, int, float)): + raise TypeError("timestamp must be a string, integer, or float") + + if datetime_str is not None and not isinstance(datetime_str, str): + raise TypeError("datetime must be a string") + + if from_tz is not None and not isinstance(from_tz, str): + raise TypeError("from_tz must be a string") + + if to_tz is not None and not isinstance(to_tz, str): + raise TypeError("to_tz must be a string") + + if format_str is not None and not isinstance(format_str, str): + raise TypeError("format must be a string") + + # 设置默认值 + if from_tz is None: + from_tz = "UTC" + + if to_tz is None: + to_tz = "UTC" + + import datetime + import pytz + + # 验证时区参数 + try: + if from_tz: + pytz.timezone(from_tz) + if to_tz: + pytz.timezone(to_tz) + except Exception: + raise ValueError("Invalid timezone provided") + + try: + # Parse input time + dt = None + + if iso is not None: + # Parse ISO 8601 format + dt = datetime.datetime.fromisoformat(iso.replace('Z', '+00:00')) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=pytz.UTC) + elif timestamp is not None: + # Parse Unix timestamp + timestamp = float(timestamp) + dt = datetime.datetime.fromtimestamp(timestamp, pytz.UTC) + elif datetime_str is not None: + # Parse datetime string + # Try common formats + formats_to_try = [ + "%Y-%m-%d %H:%M:%S", + "%Y-%m-%d %H:%M:%S.%f", + "%Y-%m-%d", + "%m/%d/%Y %H:%M:%S", + "%m/%d/%Y" + ] + + parse_success = False + for fmt in formats_to_try: + try: + dt = datetime.datetime.strptime(datetime_str, fmt) + dt = pytz.timezone(from_tz).localize(dt) + parse_success = True + break + except ValueError: + continue + + if not parse_success: + raise ValueError("Unable to parse datetime string with common formats") + else: + # 如果没有提供任何时间参数,则使用当前时间 + dt = datetime.datetime.now(pytz.UTC) + except ValueError as e: + raise ValueError(f"Error parsing time input: {str(e)}") + except Exception as e: + raise RuntimeError(f"Unexpected error parsing time input: {str(e)}") + + try: + # Convert timezone + if from_tz != to_tz: + dt = dt.astimezone(pytz.timezone(to_tz)) + + # Format outputs + result = { + "iso": dt.isoformat(), + "timestamp": str(dt.timestamp()), + "datetime": dt.strftime("%Y-%m-%d %H:%M:%S"), + "date": dt.strftime("%Y-%m-%d"), + "time": dt.strftime("%H:%M:%S"), + "timezone": to_tz + } + + # Add custom format if requested + if format_str: + try: + result["formatted"] = dt.strftime(format_str) + except ValueError as e: + raise ValueError(f"Invalid format string: {str(e)}") + + return result + except Exception as e: + raise RuntimeError(f"Error in time_convert: {str(e)}") + + def checksum_crc32(self, inputs): + import zlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("hex must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("hex parameter is required") + + try: + # 验证十六进制字符串 + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空 + if not hex_data: + raise ValueError("hex data cannot be empty") + + # 检查是否为有效的十六进制字符串 + if not all(c in "0123456789abcdefABCDEF" for c in hex_data): + raise ValueError("hex must be a valid hexadecimal string") + + # 检查长度是否为偶数 + if len(hex_data) % 2 != 0: + raise ValueError("hex must have even number of characters") + + val = zlib.crc32(bytes.fromhex(hex_data)) + # 确保 hex 输出是 8 位,前导补 0 + return {"hex": f"{val:08x}", "int": val} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in checksum_crc32: {str(e)}") + + def geo_haversine(self, inputs): + import math + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + lat1 = inputs.get("lat1") + lon1 = inputs.get("lon1") + lat2 = inputs.get("lat2") + lon2 = inputs.get("lon2") + + # 类型检查 + if lat1 is not None and not isinstance(lat1, (int, float, str)): + raise TypeError("lat1 must be a number or string") + if lon1 is not None and not isinstance(lon1, (int, float, str)): + raise TypeError("lon1 must be a number or string") + if lat2 is not None and not isinstance(lat2, (int, float, str)): + raise TypeError("lat2 must be a number or string") + if lon2 is not None and not isinstance(lon2, (int, float, str)): + raise TypeError("lon2 must be a number or string") + + # 检查必需参数 + if lat1 is None: + raise ValueError("lat1 parameter is required") + if lon1 is None: + raise ValueError("lon1 parameter is required") + if lat2 is None: + raise ValueError("lat2 parameter is required") + if lon2 is None: + raise ValueError("lon2 parameter is required") + + try: + # 转换为浮点数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(lat1, str): + lat1 = float(lat1) + elif not isinstance(lat1, (int, float)): + raise TypeError("lat1 must be a number or string") + else: + lat1 = float(lat1) + + if isinstance(lon1, str): + lon1 = float(lon1) + elif not isinstance(lon1, (int, float)): + raise TypeError("lon1 must be a number or string") + else: + lon1 = float(lon1) + + if isinstance(lat2, str): + lat2 = float(lat2) + elif not isinstance(lat2, (int, float)): + raise TypeError("lat2 must be a number or string") + else: + lat2 = float(lat2) + + if isinstance(lon2, str): + lon2 = float(lon2) + elif not isinstance(lon2, (int, float)): + raise TypeError("lon2 must be a number or string") + else: + lon2 = float(lon2) + + # Validate coordinates (approximate range check) + if not (-90 <= lat1 <= 90): + raise ValueError("lat1 must be between -90 and 90") + if not (-90 <= lat2 <= 90): + raise ValueError("lat2 must be between -90 and 90") + if not (-180 <= lon1 <= 180): + raise ValueError("lon1 must be between -180 and 180") + if not (-180 <= lon2 <= 180): + raise ValueError("lon2 must be between -180 and 180") + + # Earth radius in meters + R = 6371000 # Approximate radius of Earth + + # Convert degrees to radians + lat1_rad = math.radians(lat1) + lon1_rad = math.radians(lon1) + lat2_rad = math.radians(lat2) + lon2_rad = math.radians(lon2) + + # Calculate differences + delta_lat = lat2_rad - lat1_rad + delta_lon = lon2_rad - lon1_rad + + # Haversine formula + a = math.sin(delta_lat / 2) ** 2 + \ + math.cos(lat1_rad) * math.cos(lat2_rad) * \ + math.sin(delta_lon / 2) ** 2 + c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) + distance_m = R * c + + # Return distance in meters + return {"meters": round(distance_m, 2)} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in geo_haversine: {str(e)}") + + def otp_totp_generate(self, inputs): + import hmac + import hashlib + import base64 + import time + import struct + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + base32_secret = inputs.get("base32_secret") + step = inputs.get("step", 30) # Default to 30 seconds + digits = inputs.get("digits", 6) # Default to 6 digits + timestamp_iso = inputs.get("timestamp_iso", "") + algo = inputs.get("algo", "sha1") # Default to sha1 as current implementation only supports this + + # 类型检查 + if base32_secret is not None and not isinstance(base32_secret, str): + raise TypeError("base32_secret must be a string") + if not isinstance(step, (int, str)): + raise TypeError("step must be an integer or string") + if not isinstance(digits, (int, str)): + raise TypeError("digits must be an integer or string") + if not isinstance(timestamp_iso, str): + raise TypeError("timestamp_iso must be a string") + if not isinstance(algo, str): + raise TypeError("algo must be a string") + + # 检查必需参数 + if base32_secret is None: + raise ValueError("base32_secret parameter is required") + + try: + # Convert step and digits to appropriate types + step = int(step) + digits = int(digits) + if digits < 6 or digits > 8: + raise ValueError("Digits must be between 6 and 8") + + # Convert timestamp_iso to integer timestamp + if timestamp_iso: + import datetime + dt = datetime.datetime.fromisoformat(timestamp_iso.replace('Z', '+00:00')) + timestamp = int(dt.timestamp()) + else: + timestamp = int(time.time()) + + # Calculate counter value (T = floor(timestamp / step)) + counter = timestamp // step + + # Decode the base32 secret + # Add padding if necessary (base64 requires padding to be multiple of 8) + base32_secret = base32_secret.upper().replace(' ', '') + if len(base32_secret) % 8 != 0: + base32_secret += '=' * (8 - (len(base32_secret) % 8)) + key = base64.b32decode(base32_secret, casefold=True) + + # Calculate HMAC-SHA1 + counter_bytes = struct.pack('>Q', counter) # Big-endian 8-byte integer + hmac_hash = hmac.new(key, counter_bytes, hashlib.sha1).digest() + + # Dynamic truncation + offset = hmac_hash[-1] & 0xF + code = struct.unpack('>I', hmac_hash[offset:offset+4])[0] & 0x7FFFFFFF + + # Generate the OTP + otp = str(code % (10 ** digits)).zfill(digits) + + # Calculate remaining time until next OTP change + remaining_time = step - (timestamp % step) + + return {"totp": otp, "remaining_time": remaining_time, "time_step": step} + except ValueError as e: + if "invalid literal for int()" in str(e): + raise ValueError("step and digits must be valid integers") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in otp_totp_generate: {str(e)}") + + def unicode_norm(self, inputs): + import unicodedata + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + form = inputs.get("form", "NFC") # Default to NFC + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if form is not None and not isinstance(form, str): + raise TypeError("form must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Normalize form (NFC, NFD, NFKC, NFKD) + form = form.upper().strip() + + if form not in ['NFC', 'NFD', 'NFKC', 'NFKD']: + raise ValueError(f"Invalid normalization form: {form}. Must be one of: NFC, NFD, NFKC, NFKD") + + # Apply Unicode normalization + normalized_text = unicodedata.normalize(form, text) + + return {"text": normalized_text} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in unicode_norm: {str(e)}") + + def text_bidi_sanitize(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Bidi control characters to remove + bidi_controls = [ + '\u200E', # LEFT-TO-RIGHT MARK + '\u200F', # RIGHT-TO-LEFT MARK + '\u202A', # LEFT-TO-RIGHT EMBEDDING + '\u202B', # RIGHT-TO-LEFT EMBEDDING + '\u202C', # POP DIRECTIONAL FORMATTING + '\u202D', # LEFT-TO-RIGHT OVERRIDE + '\u202E', # RIGHT-TO-LEFT OVERRIDE + '\u2066', # LEFT-TO-RIGHT ISOLATE + '\u2067', # RIGHT-TO-LEFT ISOLATE + '\u2068', # FIRST STRONG ISOLATE + '\u2069', # POP DIRECTIONAL ISOLATE + ] + + # Remove all Bidi control characters + sanitized_text = text + for control_char in bidi_controls: + sanitized_text = sanitized_text.replace(control_char, '') + + return {"text": sanitized_text} + except Exception as e: + raise RuntimeError(f"Error in text_bidi_sanitize: {str(e)}") + + def text_xor_hex(self, inputs): + import binascii + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_a = inputs.get("hex_a") + hex_b = inputs.get("hex_b") + + # 类型检查 + if hex_a is not None and not isinstance(hex_a, str): + raise TypeError("hex_a must be a string") + if hex_b is not None and not isinstance(hex_b, str): + raise TypeError("hex_b must be a string") + + # 检查必需参数 + if hex_a is None: + raise ValueError("hex_a parameter is required") + if hex_b is None: + raise ValueError("hex_b parameter is required") + + try: + # Remove any whitespace + hex_a = hex_a.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + hex_b = hex_b.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + + # Validate hex strings + if not (all(c in "0123456789abcdefABCDEF" for c in hex_a) and len(hex_a) % 2 == 0): + raise ValueError("hex_a must be a valid hexadecimal string with even length") + if not (all(c in "0123456789abcdefABCDEF" for c in hex_b) and len(hex_b) % 2 == 0): + raise ValueError("hex_b must be a valid hexadecimal string with even length") + + # Convert hex strings to bytes + bytes_a = binascii.unhexlify(hex_a) + bytes_b = binascii.unhexlify(hex_b) + + # Make the byte arrays the same length by padding the shorter one with zeros + max_len = max(len(bytes_a), len(bytes_b)) + bytes_a = bytes_a.ljust(max_len, b'\x00') + bytes_b = bytes_b.ljust(max_len, b'\x00') + + # Perform XOR operation + result_bytes = bytes(a ^ b for a, b in zip(bytes_a, bytes_b)) + + # Convert result back to hex + result_hex = binascii.hexlify(result_bytes).decode('utf-8') + + return {"hex": result_hex} + except ValueError as e: + if "Non-hexadecimal digit found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in text_xor_hex: {str(e)}") + + def text_rotN(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + n = inputs.get("n", 0) + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + n = int(n) + except ValueError: + raise ValueError("n must be a valid integer") + + result = [] + for char in text: + if char.isupper(): + # Rotate uppercase letters + result_char = chr((ord(char) - ord('A') + n) % 26 + ord('A')) + result.append(result_char) + elif char.islower(): + # Rotate lowercase letters + result_char = chr((ord(char) - ord('a') + n) % 26 + ord('a')) + result.append(result_char) + else: + # Keep non-alphabetic characters unchanged + result.append(char) + + return {"text": ''.join(result)} + + def luhn_check(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数(支持 card_number 和 number 两个参数名) + card_number = inputs.get("number") or inputs.get("card_number") + + # 类型检查 + if card_number is not None and not isinstance(card_number, str): + raise TypeError("number must be a string") + + # 检查必需参数 + if card_number is None: + raise ValueError("number parameter is required") + + try: + # 如果输入是JSON数组或其他非数字字符串,返回该字符串本身(用于数据传递) + # 这种情况发生在DAG设计中类型不匹配时 + if card_number.startswith('[') or card_number.startswith('{'): + # 输入是JSON,直接返回原值(用于传递) + return {"valid": card_number} + + # Remove whitespace from card number + card_number = card_number.replace(" ", "").replace("-", "") + + # Check if card number is all digits + if not card_number.isdigit() or len(card_number) < 13: + return {"valid": "false"} + + # Implement Luhn algorithm + total = 0 + reverse_digits = card_number[::-1] # Reverse the number for easier processing + + for i, digit in enumerate(reverse_digits): + num = int(digit) + if i % 2 == 1: # Every second digit starting from the right (which is first in reversed string) + num *= 2 + if num > 9: + num -= 9 # Equivalent to sum of digits for 2-digit numbers + total += num + + # Check if total is divisible by 10 + is_valid = total % 10 == 0 + return {"valid": "true" if is_valid else "false"} + except Exception as e: + raise RuntimeError(f"Error in luhn_check: {str(e)}") + + def iban_validate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iban = inputs.get("iban") + + # 类型检查 + if iban is not None and not isinstance(iban, str): + raise TypeError("iban must be a string") + + # 检查必需参数 + if iban is None: + raise ValueError("iban parameter is required") + + try: + # Remove whitespace from IBAN + iban = iban.replace(" ", "") + + # Basic length and format check + if not (len(iban) >= 15 and len(iban) <= 34): + return {"valid": "False"} + + if not (iban[:2].isalpha() and iban[2:].isdigit()): + return {"valid": "False"} + + # Move first four characters to the end + rearranged = iban[4:] + iban[:4] + + # Replace letters with numbers (A=10, B=11, ..., Z=35) + numeric_iban = '' + for char in rearranged: + if char.isdigit(): + numeric_iban += char + else: + numeric_iban += str(ord(char.upper()) - ord('A') + 10) + + # Perform modulo 97 check + # Use step-by-step approach for very large numbers + remainder = 0 + for char in numeric_iban: + remainder = (remainder * 10 + int(char)) % 97 + + is_valid = remainder == 1 + return {"valid": "True" if is_valid else "False"} + except Exception as e: + raise RuntimeError(f"Error in iban_validate: {str(e)}") + + def matter_synthesizer(self, inputs): + import hashlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + blueprint = inputs.get("blueprint") + + # 类型检查 + if blueprint is not None and not isinstance(blueprint, str): + raise TypeError("blueprint must be a string") + + try: + # Get blueprint parameter as defined in interface + if blueprint is None: + blueprint = "" + + # Generate a unique item ID based on the blueprint + # This ensures the same blueprint always produces the same item + blueprint_hash = hashlib.sha256(blueprint.encode()).hexdigest()[:16] + + # Create a synthesized item with a deterministic ID based on blueprint + synthesized_item = f"synthesized_item_{blueprint_hash}" + + return {"output_slot": synthesized_item} + except Exception as e: + raise RuntimeError(f"Error in matter_synthesizer: {str(e)}") + + # --- Terminal Implementations --- + def terminal_1(self, inputs): + """ + terminal_1: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 只返回 text_output + - 只输入正确的 slot_b → 只返回 hex_output + - 同时输入正确的 slot_a 和 slot_b → 返回 item_dispenser(物品掉落) + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + # 检查哪些输入被提供了 + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值是否正确(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + expected_a = golden_inputs["slot_a"] + a_valid = str(slot_a) == str(expected_a) + + if has_b and "slot_b" in golden_inputs: + expected_b = golden_inputs["slot_b"] + b_valid = str(slot_b) == str(expected_b) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 item_dispenser + if has_a and has_b: + if a_valid and b_valid: + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 text_output + if has_a and not has_b: + if a_valid: + if "text_output" in golden_outputs: + result["text_output"] = golden_outputs["text_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 hex_output + if has_b and not has_a: + if b_valid: + if "hex_output" in golden_outputs: + result["hex_output"] = golden_outputs["hex_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def terminal_2(self, inputs): + """ + terminal_2: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 text_result + - 同时输入正确的 num1 和 num2 → 返回 hex_result 和 math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + # 检查哪些输入被提供了 + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值是否正确(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + expected_num1 = golden_inputs["num1"] + num1_valid = str(num1) == str(expected_num1) + + if has_num2 and "num2" in golden_inputs: + expected_num2 = golden_inputs["num2"] + num2_valid = str(num2) == str(expected_num2) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 hex_result 和 math_token + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 text_result + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "text_result" in golden_outputs: + result["text_result"] = golden_outputs["text_result"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def logic_terminal(self, inputs): + """ + Logic Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 返回 screen(部分输出) + - 只输入正确的 slot_b → 返回 screen 和 secondary_output + - 同时输入正确的 slot_a 和 slot_b → 返回 screen, secondary_output, item_dispenser + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + a_valid = str(slot_a) == str(golden_inputs["slot_a"]) + + if has_b and "slot_b" in golden_inputs: + b_valid = str(slot_b) == str(golden_inputs["slot_b"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出(包括 item_dispenser) + if has_a and has_b: + if a_valid and b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 screen(部分输出) + if has_a and not has_b: + if a_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 screen 和 secondary_output + if has_b and not has_a: + if b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def math_terminal(self, inputs): + """ + Math Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 result_display + - 同时输入正确的 num1 和 num2 → 返回 result_display, hex_result, math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + num1_valid = str(num1) == str(golden_inputs["num1"]) + + if has_num2 and "num2" in golden_inputs: + num2_valid = str(num2) == str(golden_inputs["num2"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 result_display + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def crypt_terminal(self, inputs): + """ + Encryption Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 plaintext → 返回 status(部分输出) + - 同时输入正确的 plaintext 和 key → 返回 status, encrypted_hex, encryption_chip + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + plaintext = inputs.get("plaintext") + key = inputs.get("key") + + has_plaintext = plaintext is not None and plaintext != "" + has_key = key is not None and key != "" + + # 验证输入值(与 golden values 比较) + plaintext_valid = False + key_valid = False + + if has_plaintext and "plaintext" in golden_inputs: + plaintext_valid = str(plaintext) == str(golden_inputs["plaintext"]) + + if has_key and "key" in golden_inputs: + key_valid = str(key) == str(golden_inputs["key"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_plaintext and has_key: + if plaintext_valid and key_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + if "encrypted_hex" in golden_outputs: + result["encrypted_hex"] = golden_outputs["encrypted_hex"] + if "encryption_chip" in golden_outputs: + result["encryption_chip"] = golden_outputs["encryption_chip"] + return result + else: + incorrect_params = [] + correct_params = [] + if not plaintext_valid: + incorrect_params.append("plaintext") + else: + correct_params.append("plaintext") + if not key_valid: + incorrect_params.append("key") + else: + correct_params.append("key") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 plaintext 且正确 → 返回 status(部分输出) + if has_plaintext and not has_key: + if plaintext_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: plaintext"} + + # 只提供 key 但没有 plaintext + if has_key and not has_plaintext: + return {"error": "plaintext required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + def sequence_terminal(self, inputs): + """ + Sequence Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 sequence → 返回 verification(部分输出) + - 同时输入正确的 sequence 和 checksum → 返回 verification, auth_code, access_card + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + sequence = inputs.get("sequence") + checksum = inputs.get("checksum") + + has_sequence = sequence is not None and sequence != "" + has_checksum = checksum is not None and checksum != "" + + # 验证输入值(与 golden values 比较) + sequence_valid = False + checksum_valid = False + + if has_sequence and "sequence" in golden_inputs: + sequence_valid = str(sequence) == str(golden_inputs["sequence"]) + + if has_checksum and "checksum" in golden_inputs: + checksum_valid = str(checksum) == str(golden_inputs["checksum"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_sequence and has_checksum: + if sequence_valid and checksum_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + if "auth_code" in golden_outputs: + result["auth_code"] = golden_outputs["auth_code"] + if "access_card" in golden_outputs: + result["access_card"] = golden_outputs["access_card"] + return result + else: + incorrect_params = [] + correct_params = [] + if not sequence_valid: + incorrect_params.append("sequence") + else: + correct_params.append("sequence") + if not checksum_valid: + incorrect_params.append("checksum") + else: + correct_params.append("checksum") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 sequence 且正确 → 返回 verification(部分输出) + if has_sequence and not has_checksum: + if sequence_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: sequence"} + + # 只提供 checksum 但没有 sequence + if has_checksum and not has_sequence: + return {"error": "sequence required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + # --- Additional File Tools --- + + def zip_unzip_file(self, inputs): + """ZIP 解压文件工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def zip_unzip_item(self, inputs): + """ZIP 解压道具工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def code_py_exec(self, inputs): + """Python 代码执行工具 + + 这是一个真实执行的工具,在 DAG 生成阶段和运行时评测阶段都会执行代码。 + 输入: code (Python 代码字符串) + 输出: stdout (标准输出,包含执行结果和错误信息) + + 特殊行为: + - 如果代码定义了 main() 函数,会自动调用它 + - 如果执行出错,错误信息会包含在 stdout 中 + """ + code = inputs.get("code", "") + + if not code: + return {"stdout": "Error: No code provided"} + + try: + # 创建一个受限的执行环境 + import io + import sys + + # 捕获标准输出和标准错误 + old_stdout = sys.stdout + old_stderr = sys.stderr + sys.stdout = io.StringIO() + sys.stderr = io.StringIO() + + # 执行代码 + exec_globals = {"__builtins__": __builtins__} + exec_locals = {} + exec(code, exec_globals, exec_locals) + + # 如果定义了 main() 函数,自动调用它 + if 'main' in exec_locals and callable(exec_locals['main']): + exec_locals['main']() + + # 获取输出 + stdout_value = sys.stdout.getvalue() + stderr_value = sys.stderr.getvalue() + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 合并 stdout 和 stderr + output = stdout_value + if stderr_value: + output += ("\n" if output else "") + f"[stderr] {stderr_value}" + + # 如果没有任何输出,尝试返回 result 变量的值 + if not output: + result = exec_locals.get("_result") or exec_locals.get("result") + if result is not None: + output = str(result) + + return {"stdout": output if output else "(no output)"} + + except Exception as e: + # 恢复标准输出和错误输出 + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 返回错误信息 + return {"stdout": f"Error: {type(e).__name__}: {str(e)}"} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-5eefda51/environment/puzzle/worker.Dockerfile b/tasks/agentescape-25-skeleton-5eefda51/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-25-skeleton-5eefda51/environment/puzzle/worker.Dockerfile @@ -0,0 +1,8 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends libseccomp2 && rm -rf /var/lib/apt/lists/* +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY worker.py child.py /app/ +COPY upstream/simulator.py /app/simulator.py +CMD ["uvicorn", "worker:app", "--host", "0.0.0.0", "--port", "8001", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-25-skeleton-5eefda51/environment/puzzle/worker.py b/tasks/agentescape-25-skeleton-5eefda51/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-25-skeleton-5eefda51/environment/puzzle/worker.py @@ -0,0 +1,73 @@ +"""Stateless Python tool worker. Never receives a scenario or reference values.""" + +import json +import os +import signal +import subprocess +import sys +import tempfile +import threading + +from fastapi import FastAPI +from pydantic import BaseModel, ConfigDict + +app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) +lock = threading.Lock() + + +class Execution(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + code: str + + +@app.get("/health") +def health(): + return {"ok": True} + + +@app.post("/execute") +def execute(request: Execution): + if len(request.code.encode()) > 65536: + return {"stdout": "Error: code exceeds 64 KiB limit"} + with lock, tempfile.TemporaryDirectory(prefix="escape-code-") as directory: + os.chown(directory, 65534, 65534) + with tempfile.TemporaryFile() as output: + process = subprocess.Popen( + [sys.executable, "-I", "/app/child.py"], + stdin=subprocess.PIPE, + stdout=output, + stderr=subprocess.DEVNULL, + cwd=directory, + user=65534, + group=65534, + extra_groups=[], + start_new_session=True, + env={"PATH": "/usr/local/bin:/usr/bin:/bin"}, + ) + try: + process.communicate( + json.dumps({"code": request.code}).encode(), timeout=5 + ) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + return {"stdout": "Error: Python execution timed out"} + finally: + # Also remove children still in the process group after normal exit. + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + output.seek(0) + value = output.read(65537) + if len(value) > 65536 or process.returncode != 0: + return { + "stdout": "Error: Python execution exceeded a resource limit or failed" + } + try: + result = json.loads(value) + if not isinstance(result.get("stdout"), str): + raise ValueError("Invalid worker response") + return result + except (ValueError, AttributeError): + return {"stdout": "Error: Python execution returned invalid output"} diff --git a/tasks/agentescape-25-skeleton-5eefda51/instruction.md b/tasks/agentescape-25-skeleton-5eefda51/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-25-skeleton-5eefda51/instruction.md @@ -0,0 +1,18 @@ +# Escape the room + +Discover the victory string and submit it with `escape submit-answer`. +Start with `escape observe`. This returns the room, available information, visible entities, and victory node ID. + +Use these commands (JSON responses): + +```sh +escape investigate NODE_ID +escape tool-call NODE_ID --arguments-json '{"parameter": "value"}' +escape use-item NODE_ID --arguments-json '{"parameter": "value"}' +escape submit-answer 'exact victory string' +escape state +``` + +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. + +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. diff --git a/tasks/agentescape-25-skeleton-5eefda51/solution/oracle.py b/tasks/agentescape-25-skeleton-5eefda51/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-25-skeleton-5eefda51/solution/oracle.py @@ -0,0 +1,133 @@ +"""Reference solver: use trusted inputs, but obtain the answer through public actions.""" + +import json +import urllib.request +from pathlib import Path + + +def http_action(base_url, payload): + request = urllib.request.Request( + base_url + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(request, timeout=30) as response: + return json.load(response) + + +def solve(scenario, act, observe): + nodes = {node["id"]: node for node in scenario["nodes"]} + visible = {entity["id"] for entity in observe["available_entities"]} + solved = set() + seen_outputs = {} + action_count = 0 + + def call(payload): + nonlocal action_count + action_count += 1 + response = act(payload) + visible.update(entity["id"] for entity in response.get("newly_revealed", [])) + if ( + response.get("episode", {}).get("termination_reason") + == "infrastructure_error" + ): + raise RuntimeError("Infrastructure failure") + return response + + for _round in range(len(nodes) + 2): + progress = False + for node_id, node in nodes.items(): + if node_id not in visible or node_id in solved: + continue + # Preserve graph order for data inputs; trigger/drop edges express visibility. + predecessors = [ + edge["source_id"] + for edge in scenario["edges"] + if edge["target_id"] == node_id + and edge["connection_type"] not in ("Item", "Hidden_Item") + ] + if any(pred not in solved for pred in predecessors): + continue + info = call({"action": "investigate", "node_id": node_id}) + if not info.get("ok"): + raise RuntimeError(f"Investigation failed: {node_id}: {info}") + inputs = { + port["name"]: port["value"] + for port in node.get("inputs", []) + if "value" in port + } + if node["type"] == "Tool": + result = call( + {"action": "tool_call", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok") or result.get("output_values", {}).get("error"): + raise RuntimeError(f"Tool failed: {node_id}: {result}") + output = result.get("output_values", {}) + if node.get("template_id") in ("terminal_1", "terminal_2"): + slots = { + port["name"]: inputs[port["name"]] + for port in node["inputs"] + if port["type"] not in ("Item", "Hidden_Item") + and port["name"] in inputs + } + triggers = { + key: value for key, value in inputs.items() if key not in slots + } + for key, value in slots.items(): + partial = call( + { + "action": "tool_call", + "node_id": node_id, + "arguments": {**triggers, key: value}, + } + ) + if partial.get("ok"): + output.update(partial.get("output_values", {})) + # HIDDEN_ITEM tool drops only occur on subsequent investigation. + call({"action": "investigate", "node_id": node_id}) + elif info.get("required_inputs"): + result = call( + {"action": "use_item", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok"): + raise RuntimeError(f"Item failed: {node_id}: {result}") + output = result.get("content") + else: + output = info.get("content") + seen_outputs[node_id] = output + solved.add(node_id) + progress = True + win_id = scenario["metadata"]["win_node_id"] + if win_id in solved and (len(solved) == len(nodes) or not progress): + outputs = seen_outputs[win_id] + if not outputs: + raise RuntimeError(f"Victory node returned no output: {win_id}") + # Upstream grades its first stored output port, independent of response order. + victory_port = next( + port["name"] for port in nodes[win_id]["outputs"] if "value" in port + ) + answer = outputs[victory_port] if isinstance(outputs, dict) else outputs + result = call({"action": "submit_answer", "answer": answer}) + if not result.get("is_win"): + raise RuntimeError(f"Victory submission failed: {result}") + return {"won": True, "actions": action_count, "visited_nodes": len(solved)} + if not progress: + raise RuntimeError(f"No progress: visible={visible}, solved={solved}") + raise RuntimeError("Reference solver exceeded graph traversal limit") + + +if __name__ == "__main__": + import os + + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000") + with urllib.request.urlopen(base + "/observation", timeout=20) as response: + observation = json.load(response) + print( + json.dumps( + solve( + json.loads(Path("/solution/scenario.json").read_text()), + lambda payload: http_action(base, payload), + observation, + ) + ) + ) diff --git a/tasks/agentescape-25-skeleton-5eefda51/solution/scenario.json b/tasks/agentescape-25-skeleton-5eefda51/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..f4f6af63c85055a05f86cc6151c445552519243a --- /dev/null +++ b/tasks/agentescape-25-skeleton-5eefda51/solution/scenario.json @@ -0,0 +1,1702 @@ +{ + "metadata": { + "total_nodes": 25, + "total_edges": 32, + "win_node_id": "container_1", + "win_condition": { + "type": "item_content", + "node_id": "container_1", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "container_1", + "terminal_2", + "calc_inv_mod", + "num_base_convert", + "terminal_2_b8dc", + "graph_shortest_path", + "zip_unzip_file", + "zip_unzip_file_4d95", + "iban_validate", + "calc_bigmul_1802", + "calc_gcd", + "zip_unzip_file_a5c9", + "graph_shortest_path_6573", + "zip_unzip_file_92f4", + "terminal_2_089e", + "num_base_convert_ab18", + "calc_modexp", + "item_9", + "calc_gcd_6f18" + ], + "by_node": { + "container_1": { + "node_name": "", + "node_type": "Item", + "template_id": "container_1", + "init_inputs": {}, + "init_outputs": { + "inner_space": { + "type": "Item", + "description": "Contents" + } + } + }, + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": {}, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + }, + "math_token": { + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + } + }, + "calc_inv_mod": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "Integer a" + } + }, + "init_outputs": {} + }, + "num_base_convert": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "from_base": { + "type": "Big_Int", + "description": "From base" + } + }, + "init_outputs": {} + }, + "terminal_2_b8dc": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": {}, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + }, + "math_token": { + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + } + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": {}, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "zip_unzip_file_4d95": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "iban_validate": { + "node_name": "IBAN Validator", + "node_type": "Tool", + "template_id": "iban_validate", + "init_inputs": { + "iban": { + "type": "Text_Generic", + "description": "IBAN string" + } + }, + "init_outputs": {} + }, + "calc_bigmul_1802": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First large integer" + } + }, + "init_outputs": {} + }, + "calc_gcd": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First integer" + } + }, + "init_outputs": {} + }, + "zip_unzip_file_a5c9": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "graph_shortest_path_6573": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "Graph JSON file ID" + }, + "src": { + "type": "Text_Generic", + "description": "Source node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "zip_unzip_file_92f4": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "terminal_2_089e": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": {}, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + } + } + }, + "num_base_convert_ab18": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "from_base": { + "type": "Big_Int", + "description": "From base" + }, + "to_base": { + "type": "Big_Int", + "description": "To base" + } + }, + "init_outputs": {} + }, + "calc_modexp": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "base": { + "type": "Big_Int", + "description": "Base" + }, + "exp": { + "type": "Big_Int", + "description": "Exponent" + }, + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "item_9": { + "node_name": "", + "node_type": "Item", + "template_id": "item_9", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "File_Id", + "description": "JSON file path" + } + } + }, + "calc_gcd_6f18": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First integer" + }, + "b": { + "type": "Big_Int", + "description": "Second integer" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "container_1": { + "init_inputs": {}, + "init_outputs": { + "inner_space": "FDR: 2026-04-27 13:42:19 UTC, Heading 276°, Alt 3512m" + } + }, + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Terminal 2 initialization completed with partial output.", + "hex_result": "a1b2c3d4e5f67890a1b2c3d4e5f67890", + "math_token": "A dusty old token from a forgotten math class." + } + }, + "calc_inv_mod": { + "init_inputs": { + "a": "98765432109876543210123" + }, + "init_outputs": {} + }, + "num_base_convert": { + "init_inputs": { + "from_base": "10" + }, + "init_outputs": {} + }, + "terminal_2_b8dc": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Secret blueprint data loaded into the central memory block.", + "hex_result": "112233445566778899aabbccddeeff00", + "math_token": "A mysterious token that seems entirely pointless." + } + }, + "graph_shortest_path": { + "init_inputs": {}, + "init_outputs": { + "path": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Omega\"]", + "cost": "394851" + } + }, + "zip_unzip_file": { + "init_inputs": { + "password": "GlobalAdminPassword123!" + }, + "init_outputs": { + "files": "graph_data.json" + } + }, + "zip_unzip_file_4d95": { + "init_inputs": { + "password": "SecureArchivePass_4d95" + }, + "init_outputs": { + "files": "intermediate_layer2.zip" + } + }, + "iban_validate": { + "init_inputs": { + "iban": "DE89370400440532013000" + }, + "init_outputs": {} + }, + "calc_bigmul_1802": { + "init_inputs": { + "a": "12345678901234567890123" + }, + "init_outputs": {} + }, + "calc_gcd": { + "init_inputs": { + "a": "5647382910564738291045" + }, + "init_outputs": {} + }, + "zip_unzip_file_a5c9": { + "init_inputs": { + "password": "DecryptKey_A5C9_!" + }, + "init_outputs": { + "files": "extracted_bundle_a5c9.zip" + } + }, + "graph_shortest_path_6573": { + "init_inputs": { + "file_id": "network_map_6573.json", + "src": "Node_Start_6573" + }, + "init_outputs": { + "path": "[\"Node_Start_6573\", \"Node_Mid_1\", \"Node_Mid_2\", \"Node_Mid_3\", \"Node_Target\"]", + "cost": "837492" + } + }, + "zip_unzip_file_92f4": { + "init_inputs": { + "password": "Op3nS3sam3_92f4" + }, + "init_outputs": { + "files": "compressed_core_92f4.zip" + } + }, + "terminal_2_089e": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Terminal 089e executed its final command sequence successfully.", + "hex_result": "deadbeef1234567890abcdef12345678" + } + }, + "num_base_convert_ab18": { + "init_inputs": { + "from_base": "10", + "to_base": "10" + }, + "init_outputs": {} + }, + "calc_modexp": { + "init_inputs": { + "base": "17", + "exp": "9988776655443322110055", + "mod": "104729" + }, + "init_outputs": {} + }, + "item_9": { + "init_inputs": {}, + "init_outputs": { + "content": "target_payload_9.zip" + } + }, + "calc_gcd_6f18": { + "init_inputs": { + "a": "8877665544332211009988", + "b": "1122334455667788990011" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You've successfully infiltrated the underground data fortress of the Nexus Syndicate, a high-tech labyrinth of servers and reinforced steel. Your objective is the Central Vault, which holds damning evidence of their illegal operations. Suddenly, the facility's automated systems lock down. The main servers have fragmented their authentication protocols, scattering them across different subsystems. You must logically manipulate the severed network modules and decrypt the layered security archives before the Syndicate's strike team arrives. The clock is ticking as you delve deeper into the mainframe.", + "narrative_style": "techno_thriller" + }, + "nodes": [ + { + "id": "container_1", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + }, + { + "name": "fingerprint_input", + "type": "Hex_String", + "description": "Fingerprint Hash", + "value": "a1b2c3d4e5f67890a1b2c3d4e5f67890" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents", + "value": "FDR: 2026-04-27 13:42:19 UTC, Heading 276°, Alt 3512m" + } + ], + "init": { + "inputs": {}, + "outputs": { + "inner_space": "FDR: 2026-04-27 13:42:19 UTC, Heading 276°, Alt 3512m" + } + }, + "narrative": "The Central Vault is a reinforced titanium safe containing the core evidence. It requires input from the Master Override Terminal to release its primary locks." + }, + { + "id": "terminal_2", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "95214" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "9403851852909785185208651322" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Terminal 2 initialization completed with partial output." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "a1b2c3d4e5f67890a1b2c3d4e5f67890" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "A dusty old token from a forgotten math class." + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "Terminal 2 initialization completed with partial output.", + "hex_result": "a1b2c3d4e5f67890a1b2c3d4e5f67890", + "math_token": "A dusty old token from a forgotten math class." + } + }, + "narrative": "This is the Master Override Terminal, the final checkpoint in the network. It requires inputs from the Primary Processor and the Logic Decoder." + }, + { + "id": "calc_bigmul", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "98765432109876543210123" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "95214" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "9403851852909785185208651322" + } + ], + "narrative": "The Primary Processor hums with immense computing power. It requires inputs from the Phase Inverter and the Signal Translator." + }, + { + "id": "zip_unzip_item", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_item", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "extracted_bundle_a5c9.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Secret blueprint data loaded into the central memory block." + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip" + } + ], + "narrative": "The Encrypted Blueprint Archive contains classified digital schematics. It requires inputs from the Security Sub-Terminal and the Delta Sector Archive." + }, + { + "id": "calc_inv_mod", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "98765432109876543210123" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "37037036703703703670369" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "98765432109876543210123" + } + ], + "init": { + "inputs": { + "a": "98765432109876543210123" + }, + "outputs": {} + }, + "narrative": "The Phase Inverter is a specialized data-flipping mechanism. It requires input from the Secondary Processor." + }, + { + "id": "num_base_convert", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool", + "value": "synthesized_item_378af87cf6fd7f95" + }, + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "95214" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "10" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "37037036703703703670369" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "95214" + } + ], + "init": { + "inputs": { + "from_base": "10" + }, + "outputs": {} + }, + "narrative": "The Logic Decoder translates raw machine logic into readable formats. It requires inputs from the Secondary Processor and the Signal Translator." + }, + { + "id": "terminal_2_b8dc", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "11" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "394851" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Secret blueprint data loaded into the central memory block." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "112233445566778899aabbccddeeff00" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "A mysterious token that seems entirely pointless." + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "Secret blueprint data loaded into the central memory block.", + "hex_result": "112233445566778899aabbccddeeff00", + "math_token": "A mysterious token that seems entirely pointless." + } + }, + "narrative": "The Security Sub-Terminal manages auxiliary defense protocols. It requires inputs from the Main Routing Node and the Pulse Generator." + }, + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "graph_data.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "false" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Terminal 089e executed its final command sequence successfully." + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Omega\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "394851" + } + ], + "init": { + "inputs": {}, + "outputs": { + "path": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Omega\"]", + "cost": "394851" + } + }, + "narrative": "The Main Routing Node coordinates data packets across the facility. It requires inputs from the Integrity Checker, the Beta Core Archive, and the Logistics Terminal." + }, + { + "id": "luhn_check", + "name": "Luhn Checker", + "description": "Luhn validity of number string.", + "type": "Tool", + "template_id": "luhn_check", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "number", + "type": "Text_Generic", + "description": "Number string", + "value": "True" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "false" + } + ], + "narrative": "The Integrity Checker validates incoming data authenticity. It requires input from the Identity Validator." + }, + { + "id": "matter_synthesizer", + "name": "Matter Synthesizer", + "description": "Synthesizes physical objects from data blueprints.", + "type": "Tool", + "template_id": "matter_synthesizer", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "blueprint", + "type": "Text_Generic", + "description": "Object Blueprint", + "value": "Secret blueprint data loaded into the central memory block." + } + ], + "outputs": [ + { + "name": "output_slot", + "type": "Item", + "description": "Synthesized Object", + "value": "synthesized_item_378af87cf6fd7f95" + } + ], + "narrative": "The Molecular Printer is capable of rapid 3D printing from digital data. It requires input from the Security Sub-Terminal." + }, + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "intermediate_layer2.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "GlobalAdminPassword123!" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "graph_data.json" + } + ], + "init": { + "inputs": { + "password": "GlobalAdminPassword123!" + }, + "outputs": { + "files": "graph_data.json" + } + }, + "narrative": "The Beta Core Archive is a highly compressed data repository. It requires input from the Gamma Sector Archive." + }, + { + "id": "zip_unzip_file_4d95", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "extracted_bundle_a5c9.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "SecureArchivePass_4d95" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "intermediate_layer2.zip" + } + ], + "init": { + "inputs": { + "password": "SecureArchivePass_4d95" + }, + "outputs": { + "files": "intermediate_layer2.zip" + } + }, + "narrative": "The Gamma Sector Archive holds heavily encrypted files. It requires input from the Delta Sector Archive." + }, + { + "id": "iban_validate", + "name": "IBAN Validator", + "description": "IBAN checksum validation.", + "type": "Tool", + "template_id": "iban_validate", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "iban", + "type": "Text_Generic", + "description": "IBAN string", + "value": "DE89370400440532013000" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "True" + } + ], + "init": { + "inputs": { + "iban": "DE89370400440532013000" + }, + "outputs": {} + }, + "narrative": "An Identity Validator module." + }, + { + "id": "calc_bigmul_1802", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "12345678901234567890123" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "3" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "37037036703703703670369" + } + ], + "init": { + "inputs": { + "a": "12345678901234567890123" + }, + "outputs": {} + }, + "narrative": "The Secondary Processor handles complex backend computations. It requires input from the Resonance Calibrator." + }, + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "5647382910564738291045" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "837492" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "3" + } + ], + "init": { + "inputs": { + "a": "5647382910564738291045" + }, + "outputs": {} + }, + "narrative": "The Resonance Calibrator aligns frequency harmonics. It requires input from the Traffic Analyzer." + }, + { + "id": "zip_unzip_file_a5c9", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "compressed_core_92f4.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "DecryptKey_A5C9_!" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_bundle_a5c9.zip" + } + ], + "init": { + "inputs": { + "password": "DecryptKey_A5C9_!" + }, + "outputs": { + "files": "extracted_bundle_a5c9.zip" + } + }, + "narrative": "The Delta Sector Archive contains deeper layers of system data. It requires input from the Alpha Sector Archive." + }, + { + "id": "graph_shortest_path_6573", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "network_map_6573.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Node_Start_6573" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "True" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Node_Start_6573\", \"Node_Mid_1\", \"Node_Mid_2\", \"Node_Mid_3\", \"Node_Target\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "837492" + } + ], + "init": { + "inputs": { + "file_id": "network_map_6573.json", + "src": "Node_Start_6573" + }, + "outputs": { + "path": "[\"Node_Start_6573\", \"Node_Mid_1\", \"Node_Mid_2\", \"Node_Mid_3\", \"Node_Target\"]", + "cost": "837492" + } + }, + "narrative": "The Traffic Analyzer monitors data flow bottlenecks. It requires input from the Identity Validator." + }, + { + "id": "zip_unzip_file_92f4", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "target_payload_9.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Op3nS3sam3_92f4" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "compressed_core_92f4.zip" + } + ], + "init": { + "inputs": { + "password": "Op3nS3sam3_92f4" + }, + "outputs": { + "files": "compressed_core_92f4.zip" + } + }, + "narrative": "The Alpha Sector Archive stores root-level information. It requires input from the Encrypted Datapad." + }, + { + "id": "terminal_2_089e", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this terminal" + }, + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "98765432109876543210123" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "95214" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Terminal 089e executed its final command sequence successfully." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "deadbeef1234567890abcdef12345678" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "Terminal 089e executed its final command sequence successfully.", + "hex_result": "deadbeef1234567890abcdef12345678" + } + }, + "narrative": "The Logistics Terminal manages material transport logic. It requires inputs from the Signal Translator and the Phase Inverter." + }, + { + "id": "num_base_convert_ab18", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "95214" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "10" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "10" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "95214" + } + ], + "init": { + "inputs": { + "from_base": "10", + "to_base": "10" + }, + "outputs": {} + }, + "narrative": "The Signal Translator decodes proprietary syntax. It requires input from the Cryptographic Core." + }, + { + "id": "calc_modexp", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "17" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "9988776655443322110055" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "104729" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "95214" + } + ], + "init": { + "inputs": { + "base": "17", + "exp": "9988776655443322110055", + "mod": "104729" + }, + "outputs": {} + }, + "narrative": "A heavy-duty Cryptographic Core engine." + }, + { + "id": "item_9", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_9", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "File_Id", + "description": "JSON file path", + "value": "target_payload_9.zip" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "target_payload_9.zip" + } + }, + "narrative": "An Encrypted Datapad." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A Stealth Keycard." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A Temporal Chip." + }, + { + "id": "calc_gcd_6f18", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "8877665544332211009988" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "1122334455667788990011" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "11" + } + ], + "init": { + "inputs": { + "a": "8877665544332211009988", + "b": "1122334455667788990011" + }, + "outputs": {} + }, + "narrative": "A Pulse Generator." + } + ], + "edges": [ + { + "source_id": "terminal_2", + "target_id": "container_1", + "connection_type": "Hex_String", + "source_port": "hex_result", + "target_port": "fingerprint_input" + }, + { + "source_id": "calc_bigmul", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "num2" + }, + { + "source_id": "zip_unzip_item", + "target_id": "calc_bigmul", + "connection_type": "Item", + "source_port": "item", + "target_port": "trigger_item" + }, + { + "source_id": "calc_inv_mod", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "a" + }, + { + "source_id": "num_base_convert", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "num1" + }, + { + "source_id": "terminal_2_b8dc", + "target_id": "zip_unzip_item", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "password" + }, + { + "source_id": "graph_shortest_path", + "target_id": "terminal_2_b8dc", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "num2" + }, + { + "source_id": "luhn_check", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "src" + }, + { + "source_id": "matter_synthesizer", + "target_id": "num_base_convert", + "connection_type": "Item", + "source_port": "output_slot", + "target_port": "trigger_item" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "zip_unzip_file_4d95", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "iban_validate", + "target_id": "luhn_check", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "number" + }, + { + "source_id": "calc_bigmul_1802", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "to_base" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_bigmul_1802", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "b" + }, + { + "source_id": "zip_unzip_file_a5c9", + "target_id": "zip_unzip_file_4d95", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "terminal_2_b8dc", + "target_id": "matter_synthesizer", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "blueprint" + }, + { + "source_id": "zip_unzip_file_a5c9", + "target_id": "zip_unzip_item", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "graph_shortest_path_6573", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "b" + }, + { + "source_id": "zip_unzip_file_92f4", + "target_id": "zip_unzip_file_a5c9", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "terminal_2_089e", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "dst" + }, + { + "source_id": "num_base_convert_ab18", + "target_id": "terminal_2_089e", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "num2" + }, + { + "source_id": "calc_bigmul_1802", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "mod" + }, + { + "source_id": "iban_validate", + "target_id": "graph_shortest_path_6573", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "dst" + }, + { + "source_id": "num_base_convert_ab18", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "b" + }, + { + "source_id": "calc_inv_mod", + "target_id": "terminal_2_089e", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "num1" + }, + { + "source_id": "calc_modexp", + "target_id": "num_base_convert_ab18", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "s" + }, + { + "source_id": "item_9", + "target_id": "zip_unzip_file_92f4", + "connection_type": "File_Id", + "source_port": "content", + "target_port": "zip_id" + }, + { + "source_id": "terminal_2_089e", + "target_id": "item_9", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "container" + }, + { + "source_id": "num_base_convert_ab18", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "s" + }, + { + "source_id": "item_8", + "target_id": "terminal_2_089e", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "item_16", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "calc_gcd_6f18", + "target_id": "terminal_2_b8dc", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "num1" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-5eefda51/solution/solve.sh b/tasks/agentescape-25-skeleton-5eefda51/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-25-skeleton-5eefda51/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-25-skeleton-5eefda51/task.toml b/tasks/agentescape-25-skeleton-5eefda51/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b89100c929ef280d78a74e534eb0d291de146462 --- /dev/null +++ b/tasks/agentescape-25-skeleton-5eefda51/task.toml @@ -0,0 +1,38 @@ +schema_version = "1.4" +source = "https://github.com/AGI-Eval-Official/Repo-of-AgentEscapeBench" + +[[artifacts]] +source = "/evidence/final.json" +service = "puzzle" + +[[artifacts]] +source = "/evidence/trace.jsonl" +service = "puzzle" + +[task] +name = "edbeeching/agentescape-25-skeleton-5eefda51" +version = "0.1.0" + +[metadata] +difficulty = 25 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "b1ee7bfee3b52c94ae2e5bccca11824723045fa1fadf2f348ae7be47c5d0d9e2" +protocol = "harbor-cli-action-budget-v1" +max_actions = 500 + +[agent] +timeout_sec = 1200 + +[environment] +build_timeout_sec = 900 +cpus = 1 +memory_mb = 1024 + +[verifier] +environment_mode = "separate" +timeout_sec = 60 + +[[verifier.collect]] +service = "puzzle" +command = "python -I /app/export.py" +timeout_sec = 15 diff --git a/tasks/agentescape-25-skeleton-5eefda51/tests/Dockerfile b/tasks/agentescape-25-skeleton-5eefda51/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-25-skeleton-5eefda51/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-25-skeleton-5eefda51/tests/expected.json b/tasks/agentescape-25-skeleton-5eefda51/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..f6b7fc27b72a1266528e16d09e47bb8cc959b58f --- /dev/null +++ b/tasks/agentescape-25-skeleton-5eefda51/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "b1ee7bfee3b52c94ae2e5bccca11824723045fa1fadf2f348ae7be47c5d0d9e2", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-5eefda51/tests/grade.py b/tasks/agentescape-25-skeleton-5eefda51/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-25-skeleton-5eefda51/tests/grade.py @@ -0,0 +1,21 @@ +"""Grade only Harbor-collected sidecar evidence in a fresh verifier container.""" + +import json +from pathlib import Path + +expected = json.loads(Path("/tests/expected.json").read_text()) +state = json.loads(Path("/evidence/final.json").read_text()) +assert state["collected_from_live_service"] is True, "Missing trusted service export" +assert state["scenario_sha256"] == expected["scenario_sha256"], ( + "Wrong scenario evidence" +) +assert state["max_actions"] == expected["max_actions"], "Wrong budget" +assert type(state["won"]) is bool +assert 0 <= state["action_count"] <= state["max_actions"] +assert state["termination_reason"] != "infrastructure_error", ( + "Infrastructure failure is not a puzzle failure" +) +assert not state["won"] or state["termination_reason"] == "success" +Path("/logs/verifier").mkdir(parents=True, exist_ok=True) +Path("/logs/verifier/state.json").write_text(json.dumps(state, indent=2)) +Path("/logs/verifier/reward.txt").write_text("1.0\n" if state["won"] else "0.0\n") diff --git a/tasks/agentescape-25-skeleton-5eefda51/tests/test.sh b/tasks/agentescape-25-skeleton-5eefda51/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-25-skeleton-5eefda51/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-25-skeleton-6ae6d120/environment/Dockerfile b/tasks/agentescape-25-skeleton-6ae6d120/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-25-skeleton-6ae6d120/environment/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-25-skeleton-6ae6d120/environment/agent/Dockerfile b/tasks/agentescape-25-skeleton-6ae6d120/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-25-skeleton-6ae6d120/environment/agent/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-25-skeleton-6ae6d120/environment/agent/cli.py b/tasks/agentescape-25-skeleton-6ae6d120/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-25-skeleton-6ae6d120/environment/agent/cli.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Public agent client; depends only on the Python standard library.""" + +import argparse +import json +import os +import sys +import urllib.error +import urllib.request + + +def main(): + parser = argparse.ArgumentParser(description="Interact with the escape room") + parser.add_argument( + "action", + choices=[ + "observe", + "state", + "investigate", + "tool-call", + "use-item", + "submit-answer", + ], + ) + parser.add_argument("value", nargs="?") + parser.add_argument("--arguments-json", default="{}") + args = parser.parse_args() + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000").rstrip("/") + if args.action in ("observe", "state"): + request = urllib.request.Request( + base + ("/observation" if args.action == "observe" else "/state") + ) + else: + if args.value is None: + parser.error("node ID or answer is required") + payload = {"action": args.action.replace("-", "_")} + if args.action == "submit-answer": + payload["answer"] = args.value + else: + payload["node_id"] = args.value + if args.action in ("tool-call", "use-item"): + payload["arguments"] = json.loads(args.arguments_json) + request = urllib.request.Request( + base + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=30) as response: + print(json.dumps(json.load(response), ensure_ascii=False)) + except (urllib.error.URLError, ValueError) as exc: + print(json.dumps({"ok": False, "error": str(exc)})) + sys.exit(2) + + +if __name__ == "__main__": + main() diff --git a/tasks/agentescape-25-skeleton-6ae6d120/environment/docker-compose.yaml b/tasks/agentescape-25-skeleton-6ae6d120/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..76161380d971e753c6049092ea2ea9872742be71 --- /dev/null +++ b/tasks/agentescape-25-skeleton-6ae6d120/environment/docker-compose.yaml @@ -0,0 +1,50 @@ +services: + main: + image: agentescapebench-agent:aab05a0a9ddb + build: + context: ./agent + networks: [default, puzzle] + security_opt: [no-new-privileges:true] + depends_on: + puzzle: + condition: service_healthy + puzzle: + image: agentescapebench-puzzle:agentescape-25-skeleton-6ae6d120-aab05a0a9ddb + build: + context: ./puzzle + networks: [puzzle, execution] + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 512m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"] + interval: 1s + timeout: 3s + retries: 30 + depends_on: + worker: + condition: service_healthy + worker: + image: agentescapebench-worker:aab05a0a9ddb + build: + context: ./puzzle + dockerfile: worker.Dockerfile + networks: [execution] + read_only: true + tmpfs: ["/tmp:size=64m,mode=1777"] + cap_drop: [ALL] + cap_add: [SETUID, SETGID, KILL, CHOWN, DAC_OVERRIDE] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 384m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8001/health')"] + interval: 1s + timeout: 3s + retries: 30 +networks: + puzzle: + internal: true + execution: + internal: true diff --git a/tasks/agentescape-25-skeleton-6ae6d120/environment/puzzle/Dockerfile b/tasks/agentescape-25-skeleton-6ae6d120/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-25-skeleton-6ae6d120/environment/puzzle/Dockerfile @@ -0,0 +1,9 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY upstream /app/upstream +COPY service.py export.py /app/ +COPY scenario.json /private/scenario.json +ENV SCENARIO_PATH=/private/scenario.json EVIDENCE_DIR=/evidence WORKER_URL=http://worker:8001 MAX_ACTIONS=500 +CMD ["uvicorn", "service:create_app", "--factory", "--host", "0.0.0.0", "--port", "8000", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-25-skeleton-6ae6d120/environment/puzzle/child.py b/tasks/agentescape-25-skeleton-6ae6d120/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-25-skeleton-6ae6d120/environment/puzzle/child.py @@ -0,0 +1,59 @@ +"""Run the original Python tool after reducing privileges and blocking networking.""" + +import ctypes +import errno +import json +import resource +import sys + +resource.setrlimit(resource.RLIMIT_CPU, (3, 3)) +resource.setrlimit(resource.RLIMIT_AS, (256 * 1024 * 1024, 256 * 1024 * 1024)) +resource.setrlimit(resource.RLIMIT_FSIZE, (65536, 65536)) +resource.setrlimit(resource.RLIMIT_NOFILE, (32, 32)) +resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + +# Filters survive fork/exec. Fail closed if seccomp cannot be loaded. +lib = ctypes.CDLL("libseccomp.so.2", use_errno=True) +lib.seccomp_init.argtypes = [ctypes.c_uint32] +lib.seccomp_init.restype = ctypes.c_void_p +lib.seccomp_rule_add.argtypes = [ + ctypes.c_void_p, + ctypes.c_uint32, + ctypes.c_int, + ctypes.c_uint, +] +lib.seccomp_syscall_resolve_name.argtypes = [ctypes.c_char_p] +lib.seccomp_load.argtypes = [ctypes.c_void_p] +lib.seccomp_release.argtypes = [ctypes.c_void_p] +ctx = lib.seccomp_init(0x7FFF0000) # SCMP_ACT_ALLOW +if not ctx: + raise RuntimeError("Cannot initialize execution isolation") +try: + for name in ( + "socket", + "socketpair", + "connect", + "ptrace", + "process_vm_readv", + "process_vm_writev", + "mount", + "unshare", + "setns", + "bpf", + ): + number = lib.seccomp_syscall_resolve_name(name.encode()) + if ( + number >= 0 + and lib.seccomp_rule_add(ctx, 0x00050000 | errno.EPERM, number, 0) != 0 + ): + raise RuntimeError("Cannot install execution isolation rule") + if lib.seccomp_load(ctx) != 0: + raise RuntimeError("Cannot activate execution isolation") +finally: + lib.seccomp_release(ctx) + +sys.path.insert(0, "/app") +from simulator import ToolSimulator # noqa: E402 + +request = json.load(sys.stdin) +json.dump(ToolSimulator().code_py_exec(request), sys.stdout) diff --git a/tasks/agentescape-25-skeleton-6ae6d120/environment/puzzle/export.py b/tasks/agentescape-25-skeleton-6ae6d120/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-25-skeleton-6ae6d120/environment/puzzle/export.py @@ -0,0 +1,13 @@ +"""Harbor invokes this inside the puzzle service after stopping the agent.""" + +import json +import pathlib +import urllib.request + +with urllib.request.urlopen("http://127.0.0.1:8000/state", timeout=10) as response: + state = json.load(response) +state["collected_from_live_service"] = True +target = pathlib.Path("/evidence/final.json") +temp = target.with_suffix(".tmp") +temp.write_text(json.dumps(state)) +temp.replace(target) diff --git a/tasks/agentescape-25-skeleton-6ae6d120/environment/puzzle/requirements.txt b/tasks/agentescape-25-skeleton-6ae6d120/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-25-skeleton-6ae6d120/environment/puzzle/requirements.txt @@ -0,0 +1,57 @@ +annotated-doc==0.0.5 + # via fastapi +annotated-types==0.8.0 + # via pydantic +anyio==4.16.0 + # via starlette +certifi==2026.10.23 + # via requests +cffi==2.1.1 ; platform_python_implementation != 'PyPy' + # via cryptography +charset-normalizer==3.5.2 + # via requests +click==8.5.0 + # via uvicorn +cryptography==50.0.2 + # via agentescapebench-harbor +fastapi==0.162.0 + # via agentescapebench-harbor +h11==0.16.0 + # via uvicorn +idna==3.20 + # via + # anyio + # requests +opentelemetry-api==1.45.2 + # via fastapi +pycparser==3.12 ; implementation_name != 'PyPy' and platform_python_implementation != 'PyPy' + # via cffi +pydantic==2.14.2 + # via + # agentescapebench-harbor + # fastapi +pydantic-core==2.50.2 + # via pydantic +pytz==2025.2 + # via agentescapebench-harbor +requests==2.34.2 + # via agentescapebench-harbor +starlette==1.10.0 + # via fastapi +typing-extensions==4.16.0 + # via + # anyio + # fastapi + # opentelemetry-api + # pydantic + # pydantic-core + # starlette + # typing-inspection +typing-inspection==0.4.4 + # via + # fastapi + # pydantic +urllib3==2.8.0 + # via requests +uvicorn==0.54.0 + # via agentescapebench-harbor diff --git a/tasks/agentescape-25-skeleton-6ae6d120/environment/puzzle/scenario.json b/tasks/agentescape-25-skeleton-6ae6d120/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..27c8e29cb9f77da63260a8670d988e099d2da977 --- /dev/null +++ b/tasks/agentescape-25-skeleton-6ae6d120/environment/puzzle/scenario.json @@ -0,0 +1,1433 @@ +{ + "metadata": { + "total_nodes": 25, + "total_edges": 26, + "win_node_id": "hex_decode", + "win_condition": { + "type": "tool_output", + "node_id": "hex_decode", + "output_port": "text", + "output_type": "Text_Generic", + "description": "Execute Hex to Text Decoder and get the output from port 'text'" + }, + "source_init": { + "source_nodes": [ + "terminal_2", + "graph_shortest_path", + "calc_bigmul", + "zip_unzip_file", + "csv_query", + "zip_unzip_file_be1f", + "regex_search", + "container_4_4dab", + "luhn_check", + "num_base_convert", + "hash_sha256", + "calc_inv_mod", + "checksum_crc32_3498" + ], + "by_node": { + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": {}, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + } + } + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "src": { + "type": "Text_Generic", + "description": "Source node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "calc_bigmul": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First large integer" + }, + "b": { + "type": "Big_Int", + "description": "Second large integer" + } + }, + "init_outputs": {} + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + }, + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "csv_query": { + "node_name": "CSV Query", + "node_type": "Tool", + "template_id": "csv_query", + "init_inputs": { + "select": { + "type": "Text_Generic", + "description": "Columns to select" + } + }, + "init_outputs": { + "rows": { + "type": "Text_Generic", + "description": "Result rows" + } + } + }, + "zip_unzip_file_be1f": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + }, + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "regex_search": { + "node_name": "Regex Search", + "node_type": "Tool", + "template_id": "regex_search", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "File ID (optional)" + }, + "text": { + "type": "Text_Generic", + "description": "Text (optional)" + } + }, + "init_outputs": { + "matches": { + "type": "Text_Generic", + "description": "Found matches (List)" + } + } + }, + "container_4_4dab": { + "node_name": "", + "node_type": "Item", + "template_id": "container_4", + "init_inputs": { + "fingerprint_input": { + "type": "Text_Generic", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + }, + "luhn_check": { + "node_name": "Luhn Checker", + "node_type": "Tool", + "template_id": "luhn_check", + "init_inputs": { + "number": { + "type": "Text_Generic", + "description": "Number string" + } + }, + "init_outputs": {} + }, + "num_base_convert": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "to_base": { + "type": "Big_Int", + "description": "To base" + } + }, + "init_outputs": {} + }, + "hash_sha256": { + "node_name": "SHA-256 Hasher", + "node_type": "Tool", + "template_id": "hash_sha256", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text to hash" + } + }, + "init_outputs": {} + }, + "calc_inv_mod": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "Integer a" + }, + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "checksum_crc32_3498": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Execution of terminal module generated partial text result successfully.", + "hex_result": "2b4f6a8c0e1d3b5f7a9c2e4f6a8c0e1d" + } + }, + "graph_shortest_path": { + "init_inputs": { + "src": "Node_A10" + }, + "init_outputs": { + "path": "[\"Node_A10\", \"Node_B2\", \"Node_C5\", \"Node_D4\", \"Node_E9\", \"Node_F1\"]", + "cost": "784920" + } + }, + "calc_bigmul": { + "init_inputs": { + "a": "839475829104857261938", + "b": "104857293847562819384" + }, + "init_outputs": {} + }, + "zip_unzip_file": { + "init_inputs": { + "zip_id": "archive_main_73.zip", + "password": "Str0ngP@ssw0rd!" + }, + "init_outputs": { + "files": "extracted_data_73.csv" + } + }, + "csv_query": { + "init_inputs": { + "select": "id, name, age, email, status" + }, + "init_outputs": { + "rows": "[{\"id\": 1, \"name\": \"Alice\"}, {\"id\": 2, \"name\": \"Bob\"}, {\"id\": 3, \"name\": \"Charlie\"}, {\"id\": 4, \"name\": \"David\"}]" + } + }, + "zip_unzip_file_be1f": { + "init_inputs": { + "zip_id": "backup_logs_2023.zip", + "password": "B@ckup2023#secure" + }, + "init_outputs": { + "files": "logs_2023_parsed.json" + } + }, + "regex_search": { + "init_inputs": { + "file_id": "document_text_99.txt", + "text": "The quick brown fox jumps over the lazy dog 123456." + }, + "init_outputs": { + "matches": "[\"match_one\", \"match_two\", \"match_three\", \"match_four\"]" + } + }, + "container_4_4dab": { + "init_inputs": { + "fingerprint_input": "hash_fingerprint_8f2b" + }, + "init_outputs": {} + }, + "luhn_check": { + "init_inputs": { + "number": "79927398713" + }, + "init_outputs": {} + }, + "num_base_convert": { + "init_inputs": { + "to_base": "10" + }, + "init_outputs": {} + }, + "hash_sha256": { + "init_inputs": { + "text": "String to be hashed using SHA-256 algorithm." + }, + "init_outputs": {} + }, + "calc_inv_mod": { + "init_inputs": { + "a": "58291048573928174829", + "mod": "999983" + }, + "init_outputs": {} + }, + "checksum_crc32_3498": { + "init_inputs": { + "hex": "112233445566778899aabbccddeeff00" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You awaken in the dimly lit basement of what appears to be an abandoned intelligence agency outpost. Dust dances in the single beam of moonlight cutting through a high window. Scattered across the desks and workbenches are various obsolete yet highly modified mechanical and digital devices. A heavy steel door blocks your only exit, secured by a complex lock that requires a specific deciphered text. You must interact with the strange assortment of tools, scanners, and terminals to trace the final secret. Be careful—these machines are ingeniously interconnected, and determining the correct sequence of operations is your only chance to escape.", + "narrative_style": "mystery" + }, + "nodes": [ + { + "id": "hex_decode", + "name": "Hex to Text Decoder", + "description": "Decode hex to UTF-8 text.", + "type": "Tool", + "template_id": "hex_decode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex string", + "value": "0062a113" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decoded text", + "value": "\u0000b\u0013" + } + ], + "narrative": "This is the Final Deciphering Terminal. It requires input from the Mainframe Validation Module. Use the validation result here to reveal the ultimate secret." + }, + { + "id": "checksum_crc32", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "bb39b750" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "0062a113" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 6463763 + } + ], + "narrative": "This is the Mainframe Validation Module. It requires input from the Network Checksum Verifier. Once you have the verifier's result, enter it here." + }, + { + "id": "checksum_crc32_0015", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "789c0dc9d10d80200c04d0556e02b770108287212960da6b82dbebfb7de7664df535b11a441f7d16c358571a7173d28b78e129aefe87b80567a40991b532a2a5d97b7ceddf1bbf" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "bb39b750" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3141121872 + } + ], + "narrative": "This is the Network Checksum Verifier. It requires input from the Data Compression Unit. Bring the compressed data here for verification." + }, + { + "id": "zlib_deflate", + "name": "Zlib Deflate", + "description": "Deflate text to zlib bytes (hex).", + "type": "Tool", + "template_id": "zlib_deflate", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Text to compress", + "value": "Execution of terminal module generated partial text result successfully." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Compressed hex", + "value": "789c0dc9d10d80200c04d0556e02b770108287212960da6b82dbebfb7de7664df535b11a441f7d16c358571a7173d28b78e129aefe87b80567a40991b532a2a5d97b7ceddf1bbf" + } + ], + "narrative": "This is the Data Compression Unit. It requires input from the Main Computer Terminal to shrink the raw data." + }, + { + "id": "terminal_2", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this terminal" + }, + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "88025163690374446159044399731057871806192" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "784920" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Execution of terminal module generated partial text result successfully." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "2b4f6a8c0e1d3b5f7a9c2e4f6a8c0e1d" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "Execution of terminal module generated partial text result successfully.", + "hex_result": "2b4f6a8c0e1d3b5f7a9c2e4f6a8c0e1d" + } + }, + "narrative": "This is the Main Computer Terminal. It requires inputs from both the Routing Analyzer and the Old Adding Machine to boot up its core systems." + }, + { + "id": "container_3", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_3", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Big_Int", + "description": "Fingerprint Hash", + "value": 2292003582 + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is a High-Security Evidence Locker. It requires input from the Data Hash Verifier to unlock its electronic seal." + }, + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "extracted_data_73.csv" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Node_A10" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "[{\"wr\": 1, \"boas\": \"Ozwqs\"}, {\"wr\": 2, \"boas\": \"Pcp\"}, {\"wr\": 3, \"boas\": \"Qvofzws\"}, {\"wr\": 4, \"boas\": \"Rojwr\"}]" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Node_A10\", \"Node_B2\", \"Node_C5\", \"Node_D4\", \"Node_E9\", \"Node_F1\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "784920" + } + ], + "init": { + "inputs": { + "src": "Node_A10" + }, + "outputs": { + "path": "[\"Node_A10\", \"Node_B2\", \"Node_C5\", \"Node_D4\", \"Node_E9\", \"Node_F1\"]", + "cost": "784920" + } + }, + "narrative": "This is the Routing Analyzer. It requires inputs from both the Cipher Wheel and the Digital Forensic Tool to map out the correct pathways." + }, + { + "id": "text_rotN", + "name": "ROT-N Cipher", + "description": "Caesar shift by N.", + "type": "Tool", + "template_id": "text_rotN", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "[{\"id\": 1, \"name\": \"Alice\"}, {\"id\": 2, \"name\": \"Bob\"}, {\"id\": 3, \"name\": \"Charlie\"}, {\"id\": 4, \"name\": \"David\"}]" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Shift N", + "value": "2416908508" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Rotated text", + "value": "[{\"wr\": 1, \"boas\": \"Ozwqs\"}, {\"wr\": 2, \"boas\": \"Pcp\"}, {\"wr\": 3, \"boas\": \"Qvofzws\"}, {\"wr\": 4, \"boas\": \"Rojwr\"}]" + } + ], + "narrative": "This is a Cipher Wheel. It requires inputs from both the Database Inquiry Console and the Base Conversion Mechanism to align its cryptographic gears." + }, + { + "id": "container_4", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_4", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Text_Generic", + "description": "Fingerprint Hash", + "value": "false" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is a Biometric Safe. It requires input from the ID Card Scanner to verify authorization." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A Dusty Keybox resting on a forgotten shelf. It seems to have been left untouched for years." + }, + { + "id": "calc_bigmul", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "839475829104857261938" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "104857293847562819384" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "88025163690374446159044399731057871806192" + } + ], + "init": { + "inputs": { + "a": "839475829104857261938", + "b": "104857293847562819384" + }, + "outputs": {} + }, + "narrative": "An Old Adding Machine with heavy mechanical keys. It still seems functional despite its age." + }, + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "archive_main_73.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Str0ngP@ssw0rd!" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_data_73.csv" + } + ], + "init": { + "inputs": { + "zip_id": "archive_main_73.zip", + "password": "Str0ngP@ssw0rd!" + }, + "outputs": { + "files": "extracted_data_73.csv" + } + }, + "narrative": "A Digital Forensic Tool used for analyzing complex digital archives." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "An Abandoned Briefcase left carelessly under a desk." + }, + { + "id": "csv_query", + "name": "CSV Query", + "description": "Query CSV: select columns and simple WHERE.", + "type": "Tool", + "template_id": "csv_query", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "CSV file ID", + "value": "logs_2023_parsed.json" + }, + { + "name": "select", + "type": "Text_Generic", + "description": "Columns to select", + "value": "id, name, age, email, status" + }, + { + "name": "where", + "type": "Text_Generic", + "description": "Where clause", + "value": "[\"match_one\", \"match_two\", \"match_three\", \"match_four\"]" + } + ], + "outputs": [ + { + "name": "rows", + "type": "Text_Generic", + "description": "Result rows", + "value": "[{\"id\": 1, \"name\": \"Alice\"}, {\"id\": 2, \"name\": \"Bob\"}, {\"id\": 3, \"name\": \"Charlie\"}, {\"id\": 4, \"name\": \"David\"}]" + } + ], + "init": { + "inputs": { + "select": "id, name, age, email, status" + }, + "outputs": { + "rows": "[{\"id\": 1, \"name\": \"Alice\"}, {\"id\": 2, \"name\": \"Bob\"}, {\"id\": 3, \"name\": \"Charlie\"}, {\"id\": 4, \"name\": \"David\"}]" + } + }, + "narrative": "This is the Database Inquiry Console. It requires inputs from both the Encrypted Archive Extractor and the Pattern Scanner to run a successful query." + }, + { + "id": "zip_unzip_file_be1f", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "backup_logs_2023.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "B@ckup2023#secure" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "logs_2023_parsed.json" + } + ], + "init": { + "inputs": { + "zip_id": "backup_logs_2023.zip", + "password": "B@ckup2023#secure" + }, + "outputs": { + "files": "logs_2023_parsed.json" + } + }, + "narrative": "An Encrypted Archive Extractor designed to bypass file restrictions." + }, + { + "id": "regex_search", + "name": "Regex Search", + "description": "Search regex in either raw text or a file.", + "type": "Tool", + "template_id": "regex_search", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "pattern", + "type": "Text_Generic", + "description": "Regex pattern", + "value": "false" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "File ID (optional)", + "value": "document_text_99.txt" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text (optional)", + "value": "The quick brown fox jumps over the lazy dog 123456." + } + ], + "outputs": [ + { + "name": "matches", + "type": "Text_Generic", + "description": "Found matches (List)", + "value": "[\"match_one\", \"match_two\", \"match_three\", \"match_four\"]" + } + ], + "init": { + "inputs": { + "file_id": "document_text_99.txt", + "text": "The quick brown fox jumps over the lazy dog 123456." + }, + "outputs": { + "matches": "[\"match_one\", \"match_two\", \"match_three\", \"match_four\"]" + } + }, + "narrative": "This is the Pattern Scanner. It requires input from the Secondary Credential Scanner to filter through the noise." + }, + { + "id": "item_16_0c5b", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A Concealed Pocketwatch hidden away from prying eyes." + }, + { + "id": "container_4_4dab", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_4", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Text_Generic", + "description": "Fingerprint Hash", + "value": "hash_fingerprint_8f2b" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "hash_fingerprint_8f2b" + }, + "outputs": {} + }, + "narrative": "An Initial Lockbox bolted to the heavy oak desk." + }, + { + "id": "checksum_crc32_609c", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "7708352a6e1dcb790460322cb7e410ddd06a0d58112982f48f131f307f2b2395" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "889d32fe" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 2292003582 + } + ], + "narrative": "This is the Data Hash Verifier. It requires input from the Cryptographic Hashing Terminal to function properly." + }, + { + "id": "luhn_check", + "name": "Luhn Checker", + "description": "Luhn validity of number string.", + "type": "Tool", + "template_id": "luhn_check", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "number", + "type": "Text_Generic", + "description": "Number string", + "value": "79927398713" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "false" + } + ], + "init": { + "inputs": { + "number": "79927398713" + }, + "outputs": {} + }, + "narrative": "An ID Card Scanner mounted near the main entrance." + }, + { + "id": "num_base_convert", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": 2416908508 + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "619044" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "10" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "2416908508" + } + ], + "init": { + "inputs": { + "to_base": "10" + }, + "outputs": {} + }, + "narrative": "This is the Base Conversion Mechanism. It requires inputs from both the Mathematical Computation Module and the Localized Integrity Checker to align the numeric formats." + }, + { + "id": "luhn_check_d1a4", + "name": "Luhn Checker", + "description": "Luhn validity of number string.", + "type": "Tool", + "template_id": "luhn_check", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "number", + "type": "Text_Generic", + "description": "Number string", + "value": "false" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "false" + } + ], + "narrative": "This is a Secondary Credential Scanner. It requires input from the ID Card Scanner to proceed with the next level of clearance." + }, + { + "id": "hash_sha256", + "name": "SHA-256 Hasher", + "description": "SHA-256 over UTF-8 text; returns hex.", + "type": "Tool", + "template_id": "hash_sha256", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text to hash", + "value": "String to be hashed using SHA-256 algorithm." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "SHA-256 Hex digest", + "value": "7708352a6e1dcb790460322cb7e410ddd06a0d58112982f48f131f307f2b2395" + } + ], + "init": { + "inputs": { + "text": "String to be hashed using SHA-256 algorithm." + }, + "outputs": {} + }, + "narrative": "A Cryptographic Hashing Terminal with a blinking green cursor." + }, + { + "id": "calc_inv_mod", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "58291048573928174829" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "999983" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "619044" + } + ], + "init": { + "inputs": { + "a": "58291048573928174829", + "mod": "999983" + }, + "outputs": {} + }, + "narrative": "A Mathematical Computation Module, perfect for solving complex numerical equations." + }, + { + "id": "checksum_crc32_3498", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "112233445566778899aabbccddeeff00" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "900f18dc" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 2416908508 + } + ], + "init": { + "inputs": { + "hex": "112233445566778899aabbccddeeff00" + }, + "outputs": {} + }, + "narrative": "A Localized Integrity Checker, meant for verifying small fragments of data." + } + ], + "edges": [ + { + "source_id": "checksum_crc32", + "target_id": "hex_decode", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "checksum_crc32_0015", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "zlib_deflate", + "target_id": "checksum_crc32_0015", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "terminal_2", + "target_id": "zlib_deflate", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "text" + }, + { + "source_id": "container_3", + "target_id": "terminal_2", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "terminal_2", + "target_id": "checksum_crc32", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "trigger_item" + }, + { + "source_id": "graph_shortest_path", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "num2" + }, + { + "source_id": "text_rotN", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "dst" + }, + { + "source_id": "container_4", + "target_id": "graph_shortest_path", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "item_16", + "target_id": "container_3", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "calc_bigmul", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "num1" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "item_8", + "target_id": "container_4", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "csv_query", + "target_id": "text_rotN", + "connection_type": "Text_Generic", + "source_port": "rows", + "target_port": "text" + }, + { + "source_id": "zip_unzip_file_be1f", + "target_id": "csv_query", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "regex_search", + "target_id": "csv_query", + "connection_type": "Text_Generic", + "source_port": "matches", + "target_port": "where" + }, + { + "source_id": "item_16_0c5b", + "target_id": "text_rotN", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "container_4_4dab", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "checksum_crc32_609c", + "target_id": "container_3", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "fingerprint_input" + }, + { + "source_id": "luhn_check", + "target_id": "container_4", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "fingerprint_input" + }, + { + "source_id": "num_base_convert", + "target_id": "text_rotN", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "n" + }, + { + "source_id": "luhn_check_d1a4", + "target_id": "regex_search", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "pattern" + }, + { + "source_id": "luhn_check", + "target_id": "luhn_check_d1a4", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "number" + }, + { + "source_id": "hash_sha256", + "target_id": "checksum_crc32_609c", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "calc_inv_mod", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "from_base" + }, + { + "source_id": "checksum_crc32_3498", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "s" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-6ae6d120/environment/puzzle/service.py b/tasks/agentescape-25-skeleton-6ae6d120/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-25-skeleton-6ae6d120/environment/puzzle/service.py @@ -0,0 +1,212 @@ +"""Restricted facade over the unchanged, pinned upstream puzzle handlers.""" + +import hashlib +import json +import logging +import os +import sys +import threading +import urllib.request +import uuid +from pathlib import Path + +from fastapi import FastAPI, HTTPException +from fastapi.responses import JSONResponse +from pydantic import BaseModel, ConfigDict + +sys.path.insert(0, str(Path(__file__).parent / "upstream")) +import server as upstream # noqa: E402 + +log = logging.getLogger(__name__) + + +def public(value): + """Keep upstream agent-internal template hints out of the public response.""" + if isinstance(value, dict): + return {k: public(v) for k, v in value.items() if not k.startswith("_")} + if isinstance(value, list): + return [public(v) for v in value] + return value + + +class Action(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + action: str + node_id: str | None = None + arguments: dict | None = None + answer: str | None = None + + +class Episode: + def __init__( + self, scenario_path, max_actions=500, evidence_dir=None, worker_url=None + ): + if max_actions < 1: + raise ValueError("max_actions must be positive") + self.lock = threading.Lock() + self.max_actions = max_actions + self.count = 0 + self.won = False + self.reason = None + self.evidence_dir = Path(evidence_dir) if evidence_dir else None + self.scenario_hash = hashlib.sha256( + Path(scenario_path).read_bytes() + ).hexdigest() + self.initial = upstream.reset_case( + case_file_path=str(scenario_path), session_id=uuid.uuid4().hex + ) + self.case_id = self.initial["case_id"] + # Hide source file paths; no upstream reset/stats/routes are mounted. + self.initial.pop("message", None) + simulator = upstream.SIMULATORS[self.case_id] + if worker_url is None: + + def no_worker(_inputs): + self.reason = "infrastructure_error" + raise RuntimeError("isolated Python worker is not configured") + + simulator.tool_map["code_py_exec"] = no_worker + else: + + def execute_python(inputs): + request = urllib.request.Request( + worker_url + "/execute", + data=json.dumps({"code": inputs.get("code", "")}).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=12) as response: + result = json.load(response) + if not isinstance(result.get("stdout"), str): + raise RuntimeError("Invalid Python worker response") + return result + except Exception: + self.reason = "infrastructure_error" + raise + + simulator.tool_map["code_py_exec"] = execute_python + self.save() + if self.evidence_dir is not None: + (self.evidence_dir / "trace.jsonl").touch() + + def state(self): + return { + "scenario_sha256": self.scenario_hash, + "action_count": self.count, + "max_actions": self.max_actions, + "won": self.won, + "termination_reason": self.reason, + } + + def save(self, action=None, result=None): + if self.evidence_dir is None: + return + self.evidence_dir.mkdir(parents=True, exist_ok=True) + target = self.evidence_dir / "outcome.json" + temp = target.with_suffix(".tmp") + temp.write_text(json.dumps(self.state())) + temp.replace(target) + if action is not None: + with (self.evidence_dir / "trace.jsonl").open("a") as handle: + handle.write( + json.dumps( + {"index": self.count, "action": action, "result": result} + ) + + "\n" + ) + + def dispatch(self, payload): + with self.lock: + if self.reason is not None: + return { + "ok": False, + "error": "Episode has ended", + "episode": self.state(), + } + self.count += 1 + try: + action = Action.model_validate(payload) + if action.action == "submit_answer" and action.answer is not None: + result = upstream.submit_answer( + self.case_id, upstream.SubmitAnswerRequest(answer=action.answer) + ) + if result.get("is_win"): + self.won = True + self.reason = "success" + elif action.action == "investigate" and action.node_id is not None: + result = upstream.investigate( + self.case_id, + upstream.InvestigateRequest(node_id=action.node_id), + ) + elif ( + action.action in ("tool_call", "use_item") + and action.node_id is not None + ): + request_type, handler = ( + (upstream.ToolCallRequest, upstream.tool_call) + if action.action == "tool_call" + else (upstream.UseItemRequest, upstream.use_item) + ) + result = handler( + self.case_id, + request_type( + node_id=action.node_id, arguments=action.arguments or {} + ), + ) + else: + result = { + "ok": False, + "error": "Unknown action or missing action parameter", + } + except HTTPException as exc: + result = {"ok": False, "error": exc.detail} + except ValueError: + result = {"ok": False, "error": "Malformed action"} + except Exception: + log.exception("Puzzle service failure") + self.reason = "infrastructure_error" + self.save() + raise + if self.reason is None and self.count >= self.max_actions: + self.reason = "action_budget_exhausted" + result = public(result) + result["episode"] = self.state() + self.save(payload, result) + return result + + +def create_app( + scenario_path=None, max_actions=None, evidence_dir=None, worker_url=None +): + episode = Episode( + scenario_path or os.environ["SCENARIO_PATH"], + max_actions or int(os.environ.get("MAX_ACTIONS", "500")), + evidence_dir if evidence_dir is not None else os.environ.get("EVIDENCE_DIR"), + worker_url if worker_url is not None else os.environ.get("WORKER_URL"), + ) + app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) + app.state.episode = episode + + @app.get("/health") + def health(): + return {"ok": True} + + @app.get("/observation") + def observation(): + return {**public(episode.initial), "episode": episode.state()} + + @app.get("/state") + def state(): + return episode.state() + + @app.post("/action") + def action(payload: dict): + try: + return episode.dispatch(payload) + except Exception: + return JSONResponse( + status_code=503, + content={"ok": False, "error": "Puzzle infrastructure failure"}, + ) + + return app diff --git a/tasks/agentescape-25-skeleton-6ae6d120/environment/puzzle/upstream/models.py b/tasks/agentescape-25-skeleton-6ae6d120/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-25-skeleton-6ae6d120/environment/puzzle/upstream/models.py @@ -0,0 +1,108 @@ +from enum import Enum +from typing import List, Dict, Any, Optional +from pydantic import BaseModel, Field + +# 1. 细粒度接口类型定义 +class InterfaceType(str, Enum): + ''' + BIG_INT + TEXT_GENERIC + HEX_STRING + FILE_ID + HEX_STRING_KEY_AES + HEX_STRING_IV_AES + CODE_PYTHON + HIDDEN_ITEM + ITEM + ''' + # --- 基础类型 --- + TEXT_GENERIC = "Text_Generic" + BIG_INT = "Big_Int" + + # --- 编码/格式化字符串 --- + HEX_STRING = "Hex_String" # 通用 Hex + + # --- 特定用途的 Hex 字符串 (用于精确匹配) --- + HEX_STRING_KEY_AES = "Hex_String_Key_AES" + HEX_STRING_IV_AES = "Hex_String_IV_AES" + + # --- 文件类型 --- + FILE_ID = "File_Id" + + # --- 代码/脚本 --- + CODE_PYTHON = "Code_Python" + + # --- 实体交互类型 (严格命名) --- + ITEM = "Item" # 主动掉落接口 (Tool -> Item) + HIDDEN_ITEM = "Hidden_Item" # 被动掉落接口 (Item -> Item) + +# 3. 端口定义 +class Port(BaseModel): + name: str + type: InterfaceType + description: str + +# 4. 统一节点定义 (融合工具和物品) +class Node(BaseModel): + id: str + name: str + description: str + type: str # "Tool" or "Item" + + # 接口定义 + inputs: List[Port] = [] + outputs: List[Port] = [] + + # 状态字段 + content: Optional[Any] = None # 物品有内容,工具为None + if_success: Optional[bool] = None # 工具初始为False,物品为None + initial_visible: bool = False + + # 运行时状态 (Server维护) + is_revealed: bool = False + + # 标记该 Tool 节点是否有待触发的 HIDDEN_ITEM 掉落 + # 当 Tool 按照 golden_input 正确执行且有 HIDDEN_ITEM 输出边时设为 True + # 在 investigate 该 Tool 时触发掉落并重置为 False + has_hidden_item_ready: bool = False + + # 初始输入值 (metadata.initial_values.init_inputs,用于渐进式暴露判断) + init_input_values: Dict[str, Any] = {} + + # Golden 输入值 (nodes[].inputs[].value,用于评测验证) + golden_input_values: Dict[str, Any] = {} + + # Golden 输出值 (nodes[].outputs[].value,用于评测验证和 Item 节点的 content) + golden_output_values: Dict[str, Any] = {} + + # 实际获得的输出值历史 (工具每次执行后实际返回的输出列表,用于渐进式暴露判断) + # 格式: List[Dict[str, Any]],每个元素是一次执行的输出字典 + actual_outputs_history: List[Dict[str, Any]] = [] + + # 逻辑规则 (用于终端机等复杂物品) + logic_rules: Optional[Dict[str, Any]] = None + + def copy(self, **kwargs): + """Helper to create a copy with updated fields.""" + data = self.dict() + data.update(kwargs) + return Node(**data) + +# 5. 边定义 (拓扑结构) +class Edge(BaseModel): + source_id: str + target_id: str + connection_type: InterfaceType # 直接使用 InterfaceType + # 如果是 Data_Flow,指定端口对应关系 + source_port: Optional[str] = None + target_port: Optional[str] = None + +# 6. 完整图定义 +class GraphScenario(BaseModel): + case_id: str + title: str + intro_narrative: str + nodes: Dict[str, Node] + edges: List[Edge] + difficulty: int + win_node_id: str # 标记哪个节点是最终目标(通常是一个提交工具或最终物品) diff --git a/tasks/agentescape-25-skeleton-6ae6d120/environment/puzzle/upstream/server.py b/tasks/agentescape-25-skeleton-6ae6d120/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-25-skeleton-6ae6d120/environment/puzzle/upstream/server.py @@ -0,0 +1,1490 @@ +import json +import os +import time +import logging +import random +from pathlib import Path +from typing import Dict, Any, List, Optional +from datetime import datetime +from collections import defaultdict +from fastapi import FastAPI, HTTPException, Request +from fastapi.responses import JSONResponse +from fastapi.middleware.cors import CORSMiddleware +from pydantic import BaseModel, Field + +from models import GraphScenario, Node, InterfaceType +# from generator import ScenarioGenerator +from simulator import ToolSimulator +import uvicorn + +# 配置日志 +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler('server.log'), + logging.StreamHandler() + ] +) +logger = logging.getLogger(__name__) + +app = FastAPI( + title="AgentEscapeBench Universal Server", + version="1.0.0", + description="Industrial-grade evaluation server for escape room AI agents" +) + +# 添加 CORS 支持 +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# In-memory State +SCENARIOS: Dict[str, GraphScenario] = {} +SIMULATORS: Dict[str, ToolSimulator] = {} # case_id -> ToolSimulator +RAW_NODES_DATA: Dict[str, Dict[str, Any]] = {} # case_id -> node_id -> raw node data (for template_id) +FILE_METADATA: Dict[str, Dict[str, Any]] = {} # case_id -> metadata (for initial_values access) + +# Performance monitoring +STATS: Dict[str, Any] = { + "total_requests": 0, + "successful_requests": 0, + "failed_requests": 0, + "tool_calls": defaultdict(int), + "investigates": defaultdict(int), + "use_items": defaultdict(int), + "case_loads": 0, + "start_time": datetime.now() +} + +# Request timing middleware +@app.middleware("http") +async def add_process_time_header(request: Request, call_next): + start_time = time.time() + STATS["total_requests"] += 1 + + try: + response = await call_next(request) + STATS["successful_requests"] += 1 + process_time = time.time() - start_time + response.headers["X-Process-Time"] = str(process_time) + logger.info(f"{request.method} {request.url.path} - {response.status_code} - {process_time:.3f}s") + return response + except Exception as e: + STATS["failed_requests"] += 1 + logger.error(f"{request.method} {request.url.path} - Error: {str(e)}") + raise + +# Exception handler +@app.exception_handler(Exception) +async def global_exception_handler(request: Request, exc: Exception): + logger.error(f"Unhandled exception: {exc}", exc_info=True) + return JSONResponse( + status_code=500, + content={ + "ok": False, + "error": "Internal server error", + "detail": str(exc) if os.getenv("DEBUG") else "An error occurred" + } + ) + +# Health check endpoint +@app.get("/health") +def health_check(): + """健康检查端点""" + uptime = (datetime.now() - STATS["start_time"]).total_seconds() + return { + "status": "healthy", + "version": "1.0.0", + "uptime_seconds": uptime, + "loaded_cases": len(SCENARIOS), + "stats": { + "total_requests": STATS["total_requests"], + "successful_requests": STATS["successful_requests"], + "failed_requests": STATS["failed_requests"], + "success_rate": STATS["successful_requests"] / max(STATS["total_requests"], 1) + } + } + +# Statistics endpoint +@app.get("/stats") +def get_stats(): + """获取详细统计信息""" + return { + "stats": STATS, + "loaded_cases": list(SCENARIOS.keys()), + "uptime": str(datetime.now() - STATS["start_time"]) + } + +def _apply_progressive_reveal_at_init(scenario: GraphScenario): + """ + 在初始化时应用渐进式暴露机制(基于ITEM/HIDDEN_ITEM边) + + 新逻辑: + - 如果一个节点没有 ITEM/HIDDEN_ITEM 类型的入边,它就是初始可见的 + - 如果一个节点有 ITEM/HIDDEN_ITEM 类型的入边,它初始不可见,需要等待上游触发 + + Args: + scenario: 场景对象 + """ + # 收集所有有 ITEM/HIDDEN_ITEM 入边的节点 + nodes_with_item_edges = set() + for edge in scenario.edges: + if edge.connection_type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + nodes_with_item_edges.add(edge.target_id) + + logger.info(f"Nodes with ITEM/HIDDEN_ITEM incoming edges: {nodes_with_item_edges}") + + # 设置初始可见性:没有 ITEM/HIDDEN_ITEM 入边的节点初始可见 + initially_visible_count = 0 + for node_id, node in scenario.nodes.items(): + if node_id not in nodes_with_item_edges: + node.is_revealed = True + initially_visible_count += 1 + logger.info(f"Initial visible (no ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + else: + node.is_revealed = False + logger.debug(f"Initial hidden (has ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + + logger.info(f"Progressive reveal initialized: {initially_visible_count}/{len(scenario.nodes)} nodes initially visible") + + +def _check_inputs_match_golden(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> bool: + """ + 检查实际输入参数是否与 golden inputs 完全匹配 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + True 表示所有 golden inputs 都存在且值匹配 + """ + if not golden_inputs: + return True # 如果没有 golden inputs,认为匹配 + + for key, expected_value in golden_inputs.items(): + actual_value = arguments.get(key) + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) != str(expected_value): + logger.debug(f"Input mismatch for '{key}': expected '{expected_value}', got '{actual_value}'") + return False + + return True + + +def _get_parameter_validation_feedback(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> Dict[str, Any]: + """ + 对源头节点的参数进行详细验证,返回验证反馈 + + 注意:不返回期望值(expected),避免泄漏答案 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + 包含验证结果的字典: + - all_correct: bool - 所有参数是否正确 + - correct_params: List[str] - 正确的参数名列表 + - incorrect_params: List[str] - 错误的参数名列表(不包含期望值) + """ + if not golden_inputs: + return { + "all_correct": True, + "correct_params": [], + "incorrect_params": [] + } + + correct_params = [] + incorrect_params = [] + + for key, actual_value in arguments.items(): + # 只对用户实际提交的参数给反馈,未提交的参数不评价 + if key not in golden_inputs: + continue # 该参数不在 golden 中,跳过(如 _golden_inputs 等内部参数) + expected_value = golden_inputs[key] + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) == str(expected_value): + correct_params.append(key) + else: + # 只记录参数名,不包含期望值,避免泄漏答案 + incorrect_params.append(key) + + # all_correct:用户提交的所有参数都正确,且覆盖了全部 golden 参数 + all_provided_correct = len(incorrect_params) == 0 + all_golden_covered = all(k in arguments for k in golden_inputs) + return { + "all_correct": all_provided_correct and all_golden_covered, + "correct_params": correct_params, + "incorrect_params": incorrect_params + } + + +def _is_source_node(node_id: str, scenario: GraphScenario) -> bool: + """ + 判断节点是否是源头节点(完全没有任何入边的节点) + + 源头节点定义: + - 没有任何类型的入边(包括 DATA、ITEM、HIDDEN_ITEM) + - 即没有任何上游节点 + + Args: + node_id: 节点ID + scenario: 场景对象 + + Returns: + True 表示是源头节点 + """ + for edge in scenario.edges: + if edge.target_id == node_id: + # 只要有任何入边,就不是源头节点 + return False + + return True + + +def _check_and_reveal_ready_nodes(scenario: GraphScenario, recent_outputs: Dict[str, Any], source_node_id: str) -> List[Dict[str, Any]]: + """ + 检查并释放参数齐全的隐藏节点(渐进式暴露机制) + + 核心逻辑: + 1. 维护"可见值集合":包含所有被测模型当前可以看到的值 + - init_inputs 的值(初始可见) + - 工具执行后的实际输出值(运行时获得) + - 可见 Item 的输出值 + 2. 检查隐藏节点:该节点的所有 golden_input 值是否都在可见值集合中 + 3. 如果是,则释放该节点 + + Args: + scenario: 场景对象 + recent_outputs: 最近执行的工具的输出 + source_node_id: 刚执行的工具节点ID + + Returns: + 新释放的节点列表 + """ + newly_revealed = [] + + # 构建"可见值集合"(Set of visible values) + # 存储格式:set of values (转为字符串) + visible_values = set() + + # 1. 添加有意义的 init_inputs 值到可见值集合 + # Item 的 init_inputs 不应该加入,因为它们在密室中完全用不到 + for node_id, node in scenario.nodes.items(): + # 跳过源头 Item 节点(没有入边的 Item) + if node.type == "Item": + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,跳过其 init_inputs + continue + + # 添加其他节点的 init_inputs + for port_name, init_value in node.init_input_values.items(): + if init_value: + visible_values.add(str(init_value)) + + # 2. 添加已执行工具的所有历史输出值 + for node_id, node in scenario.nodes.items(): + if node.type == "Tool" and node.if_success and node.actual_outputs_history: + # 遍历所有历史执行记录 + for output_dict in node.actual_outputs_history: + for output_port_name, output_value in output_dict.items(): + if output_value: + visible_values.add(str(output_value)) + + # 3. 添加已被 investigate 的 Item 的 golden 输出值 + # 注意:Item 可见不等于其输出值可见,需要 investigate 后才能获得 + # 这里我们使用 actual_outputs_history 来标记 Item 是否已被 investigate + for node_id, node in scenario.nodes.items(): + if node.type == "Item" and node.is_revealed and node.actual_outputs_history: + # Item 通常只会被 investigate 一次,但为了一致性也使用历史列表 + for output_dict in node.actual_outputs_history: + for port_name, port_value in output_dict.items(): + if port_value: + visible_values.add(str(port_value)) + + # 遍历所有隐藏的节点,检查其 golden_input 是否都在可见值集合中 + for node_id, node in scenario.nodes.items(): + # 跳过已可见的节点 + if node.is_revealed: + continue + + # 只检查工具节点(物品节点由 ITEM 输出触发) + if node.type != "Tool": + continue + + # 检查该节点的所有 golden_input 值是否都在可见值集合中 + all_inputs_ready = True + missing_values = [] + + for input_port_name, golden_input_value in node.golden_input_values.items(): + # 检查这个 golden 值是否在可见值集合中 + if str(golden_input_value) not in visible_values: + all_inputs_ready = False + missing_values.append(f"{input_port_name}={golden_input_value}") + + # 如果所有 golden_input 值都在可见值集合中,释放该节点 + if all_inputs_ready and len(node.golden_input_values) > 0: + logger.info(f"All golden inputs ready for {node_id}: {list(node.golden_input_values.values())}") + + # 如果所有输入都齐全,释放该节点 + if all_inputs_ready: + node.is_revealed = True + + # 构建节点信息返回给模型 + node_info = { + "id": node.id, + "type": node.type, + "can_investigate": True, + "hint": "This tool's input parameters are now complete, you can use investigate to view detailed information" + } + + # if node.name: + # node_info["name"] = node.name + if node.description: + node_info["description"] = node.description + + newly_revealed.append(node_info) + logger.info(f"Progressive reveal: {node_id} is now ready (all inputs satisfied)") + + return newly_revealed + + +def _initialize_node_values(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]): + """ + Initialize node state and load values from port value fields. + 应用渐进式暴露机制:初始时只显示参数齐全的节点(源头节点) + + 重要区分: + 1. input_values: 只加载 metadata.initial_values 中的 init_inputs(真正的初始值) + 2. output_values: 加载 nodes[].outputs[].value(golden 输出,用于验证) + """ + # 第一步:加载所有节点的值,并将所有节点初始设为隐藏 + initial_values = metadata.get('initial_values', {}) + + for node_id, node in scenario.nodes.items(): + # 忽略 initial_visible 字段,初始全部隐藏 + # 由渐进式暴露机制根据参数齐全情况决定是否显示 + node.is_revealed = False + + if node.type == "Tool": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + elif node.type == "Item": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + + # 从 JSON 加载值 + if node_id in raw_nodes_data: + node_data = raw_nodes_data[node_id] # node_data是json文件中nodes中的字典 + + # 【重要】只加载 metadata.initial_values 中的初始输入值 + if node_id in initial_values: + init_data = initial_values[node_id] + # 加载初始输入值(用于渐进式暴露判断) + for port_name, port_value in init_data.get('init_inputs', {}).items(): + node.init_input_values[port_name] = port_value + + # 【评测用】加载 golden 输入值(用于验证模型传入的参数是否正确) + for input_port_data in node_data.get('inputs', []): + if 'value' in input_port_data: + node.golden_input_values[input_port_data['name']] = input_port_data['value'] + + # 【评测用】加载 golden 输出值(用于验证工具调用是否正确,以及 Item 节点的 content) + for output_port_data in node_data.get('outputs', []): + if 'value' in output_port_data: + node.golden_output_values[output_port_data['name']] = output_port_data['value'] + + # For Items, set content from golden_output_values + if node.type == "Item" and node.golden_output_values: + # Item 的 content 是其第一个 golden 输出值 + node.content = list(node.golden_output_values.values())[0] + + # 第二步:应用渐进式暴露机制 + # 检查所有节点,根据参数齐全情况释放源头节点(工具 + Item) + _apply_progressive_reveal_at_init(scenario) + +def _build_node_info(node: Node, raw_nodes_data: Dict[str, Any]) -> Dict[str, Any]: + """ + 构建节点信息(工具或物品) + + Args: + node: 节点对象 + raw_nodes_data: 原始节点数据(用于获取 template_id 等) + + Returns: + 节点信息字典 + """ + if node.type == "Tool": + # 过滤掉输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口) + # 这些端口仅用于控制掉落机制,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + tool_info = { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Tool", + "inputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.inputs if p.type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]], + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id(工具的标准名称) + if node.id in raw_nodes_data: + node_data = raw_nodes_data[node.id] + template_id = node_data.get('template_id') + if template_id: + tool_info['template_id'] = template_id + + return tool_info + + elif node.type == "Item": + return { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Item" + } + + else: + return { + "id": node.id, + # "name": node.name, + "type": node.type + } + +def _get_initial_observation(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]) -> Dict[str, Any]: + """ + Generate initial observation for the agent (what they see when entering the room). + + 策略: + - Tools: 只显示名称和描述,不显示接口定义。需要 investigate 才能获得详细接口信息。 + - Items: 只显示存在,不显示内容。需要 investigate 才能获得内容值。 + - init_inputs: 作为"可用信息"告诉模型,这些是可以用作工具参数的初始值。 + - init_outputs: 不告诉模型(这些是答案,需要模型通过调用工具获得)。 + """ + available_entities = [] # 统一的实体列表(Tools 和 Items) + available_information = [] # 可用的初始信息(来自 init_inputs) + + # 从 metadata.initial_values 提取 init_inputs 作为可用信息 + # 只提供值本身,不透露这些值对应哪个节点的哪个参数,让模型自己推理 + # 注意:跳过源头 Item(没有入边的 Item)的 init_inputs,因为它们在密室中完全用不到 + initial_values = metadata.get('initial_values', {}) + # initial_values字段的格式 + # "initial_values": { + # "terminal_1": { + # "init_inputs": {}, + # "init_outputs": { + # "text_output": "System initialization complete.", + # "hex_output": "48656c6c6f20576f726c64", + # "item_dispenser": "掉落了一张纸条,上面写着“请勿随意触摸终端”" + # } + # } + # } + for node_id, init_data in initial_values.items(): + # 获取节点信息,判断是否为源头 Item + node = scenario.nodes.get(node_id) + if node and node.type == "Item": + # 检查是否为源头 Item(没有入边) + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,检查是否有 init_inputs + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 有 init_inputs,需要暴露这些参数 + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + # 处理完后跳过后续的通用逻辑 + continue + + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 为每个 init_input 值创建一个信息条目(不包含 source_node 和 parameter 信息) + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + + for node in scenario.nodes.values(): + if node.is_revealed: + # Tools: 只显示基本信息,提示可以 investigate 查看详细接口 + if node.type == "Tool": + tool_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Tool", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the tool's detailed interface information for calling" + } + # 只在 name 非空时添加 + # if node.name: + # tool_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_info["description"] = node.description + + available_entities.append(tool_info) + + # Items: 只显示基本信息,提示可以 investigate 查看内容 + elif node.type == "Item": + item_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Item", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the item's content" + } + # 只在 name 非空时添加 + # if node.name: + # item_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + item_info["description"] = node.description + + available_entities.append(item_info) + + return { + "narrative": scenario.intro_narrative, + "available_entities": available_entities, # 使用统一的实体列表 + "available_information": available_information, # 可用的初始信息(只包含 init_inputs) + "win_node_id": scenario.win_node_id # 胜利节点ID,让模型知道需要关注哪个节点 + } + +@app.post("/env/reset") +def reset_case(case_id: str = None, case_file_path: str = None, session_id: str = None): + """Loads a specific case from file and resets it. + + Args: + case_id: Optional case ID for resetting an existing case + case_file_path: Path to case file for loading a new case + session_id: Optional session ID to ensure isolation between concurrent evaluations + """ + logger.info(f"Reset request - case_id: {case_id}, case_file_path: {case_file_path}, session_id: {session_id}") + STATS["case_loads"] += 1 + + if case_file_path: + if not os.path.exists(case_file_path): + logger.error(f"Case file not found: {case_file_path}") + raise HTTPException(status_code=404, detail=f"File not found: {case_file_path}") + try: + with open(case_file_path, "r", encoding="utf-8") as f: + file_data = json.load(f) + + # 转换格式:从 DAG executor 生成的格式转换为 GraphScenario 格式 + # 1. 提取 metadata + metadata = file_data.get('metadata', {}) + + # 2. 生成 case_id, title, intro_narrative + # 【修复】为每个评测会话生成唯一的 case_id,防止并发评测时状态污染 + base_name = os.path.basename(case_file_path).replace('.json', '').replace('_full', '').replace('_full2', '') + + if session_id: + # 如果提供了 session_id,使用它来确保唯一性 + case_id = f"{base_name}_{session_id}" + else: + # 否则使用时间戳和随机数确保唯一性 + unique_suffix = f"{int(time.time() * 1000)}_{random.randint(1000, 9999)}" + case_id = f"{base_name}_{unique_suffix}" + + file_data['case_id'] = case_id + logger.info(f"Generated unique case_id: {case_id} (base: {base_name}, session: {session_id})") + + if 'title' not in file_data: + file_data['title'] = f"Escape Room: {file_data['case_id']}" + + if 'intro_narrative' not in file_data: # 目前的json文件中已经有了intro_narrative字段,不会使用下面一行的内容,而是使用每个评测问题的json文件中的对应字段 + 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]".' + + # 3. 转换 nodes 列表为字典(DAG executor 生成的文件中 nodes 是列表格式) + nodes_dict = {} + for node_data in file_data['nodes']: + nodes_dict[node_data['id']] = node_data # 这里的id是template_id之后可能添加一个后缀 + file_data['nodes'] = nodes_dict # 把列表转成一个字典 + + # 4. 添加缺失的字段 + if 'difficulty' not in file_data: + file_data['difficulty'] = metadata.get('total_nodes', 5) + + if 'win_node_id' not in file_data: + file_data['win_node_id'] = metadata.get('win_node_id', '') + + scenario = GraphScenario(**file_data) + + # Extract raw nodes data for template_id access + # nodes 已经在上面转换为字典格式 + raw_nodes_data = file_data.get('nodes', {}) + RAW_NODES_DATA[scenario.case_id] = raw_nodes_data + + # Store metadata for initial values access + FILE_METADATA[scenario.case_id] = metadata + + logger.info(f"Successfully parsed case file: {scenario.case_id}, nodes: {len(scenario.nodes)}, edges: {len(scenario.edges)}") + except Exception as e: + logger.error(f"Failed to load case file: {str(e)}", exc_info=True) + raise HTTPException(status_code=500, detail=f"Failed to load case file: {str(e)}") + + # Initialize node state and load values + _initialize_node_values(scenario, raw_nodes_data, metadata) + + SCENARIOS[scenario.case_id] = scenario + simulator = ToolSimulator() + SIMULATORS[scenario.case_id] = simulator + + 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'])}") + + # 生成初始观察信息(进入密室后看到的环境) + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + ''' + initial_observation的格式: + { + "narrative": scenario.intro_narrative, + "available_entities": available_entities # 使用统一的实体列表 + "available_information": available_information # 可用的初始信息(只包含 init_inputs) + } + ''' + + return { + "ok": True, + "message": f"Case loaded from {case_file_path}", + "case_id": scenario.case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果没有提供 case_file_path,但提供了 case_id,则尝试从内存重置 + if case_id and case_id in SCENARIOS: + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + metadata = FILE_METADATA.get(case_id, {}) + + # Reset dynamic fields and re-apply progressive reveal + # 重新初始化节点状态(包括渐进式暴露) + _initialize_node_values(scenario, raw_nodes_data, metadata) + + 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'])}") + + # 生成初始观察信息 + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + + return { + "ok": True, + "message": f"Case {case_id} reset.", + "case_id": case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果既没有 case_file_path,也没有在内存中找到,返回错误 + raise HTTPException( + status_code=400, + detail="Must provide case_file_path to load a new case, or use case_id to reset an existing case." + ) + +class InvestigateRequest(BaseModel): + node_id: str + +@app.post("/env/{case_id}/investigate") +def investigate(case_id: str, req: InvestigateRequest): + """ + Investigates a Tool or Item to reveal detailed information. + + - For Tools: Returns detailed interface information (inputs/outputs) needed to call the tool + - For Items: Returns content value and triggers hidden item drops + """ + logger.info(f"Investigate request - case_id: {case_id}, node_id: {req.node_id}") + STATS["investigates"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + node = scenario.nodes[req.node_id] + + if not node.is_revealed: + logger.warning(f"Attempt to investigate hidden node: {req.node_id}") + return {"ok": False, "error": "Node is not visible yet."} + + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + newly_revealed = [] + + # 处理 Tool 的 investigate + if node.type == "Tool": + logger.info(f"Investigating tool: {req.node_id}") + + # 返回工具的详细接口信息 + # id 字段使用 node.id(节点唯一标识),agent 用这个字段识别和调用具体的节点 + # template_id 是工具类型标识符,Agent 内部用于判断工具特性(如 terminal 类工具参数可选) + # 注意:只过滤输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口),这些端口仅用于控制掉落,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + # 【端口上游依赖提示 & 初始值直接给出】 + # 针对参数语义模糊(全为数字类型)的工具,在 investigate 返回信息中标注 + # 哪个输入端口来自哪个上游节点(upstream_from)。 + # 对于所有工具:若该节点不是纯源头节点(有任意数据流入边), + # 且某个端口没有上游入边(值来自初始可见参数),则直接给出该端口的 golden input 值。 + AMBIGUOUS_TOOLS = { + "num_base_convert", "calc_modexp", "calc_modexp_int", + "calc_inv_mod", "calc_inv_mod_int", "crypto_rsa_decrypt_hex", "geo_haversine" + } + # Terminal 类工具自带参数对错反馈机制,玩家/模型可自行试错, + # 无需在 investigate 时直接暴露 init_value + SELF_FEEDBACK_TOOLS = { + "terminal_1", "terminal_2", + "Logic Terminal", "Math Terminal", "Encryption Terminal", "Sequence Terminal" + } + _template_id_for_hint = raw_nodes_data.get(node.id, {}).get("template_id", "") + # 构建数据流入边映射(对所有工具):{target_port -> (source_node_id, source_port)} + _upstream_map = {} + for _edge in scenario.edges: + if (_edge.target_id == node.id + and _edge.connection_type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM] + and _edge.target_port is not None): + _upstream_map[_edge.target_port] = (_edge.source_id, _edge.source_port) + # 判断该节点是否有任意数据流入边(即不是纯源头节点) + _has_any_upstream = len(_upstream_map) > 0 + # 判断该节点是否有任意入边(包括 ITEM/HIDDEN_ITEM 掉落边) + # 有任意入边(含掉落边)但无数据流入边的节点,其输入来自初始可见参数,应直接给出 + _has_any_edge = any(_edge.target_id == node.id for _edge in scenario.edges) + # 构建 inputs 列表 + _inputs_list = [] + for p in node.inputs: + if p.type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + continue + port_dict = {"name": p.name, "type": p.type, "description": p.description} + if p.name in _upstream_map: + # 该端口有上游数据流依赖,且属于语义模糊工具 → 标注来源 + if _template_id_for_hint in AMBIGUOUS_TOOLS: + src_node_id, src_port = _upstream_map[p.name] + port_dict["upstream_from"] = f"{src_node_id}.{src_port}" if src_port else src_node_id + elif _has_any_edge and _template_id_for_hint not in SELF_FEEDBACK_TOOLS: + # 该节点有任意入边,但此端口没有数据流入边 → 值来自初始可见参数,直接给出 + # 排除自带反馈机制的 terminal 类工具(它们通过执行结果反馈对错,无需提前暴露参数值) + golden_val = node.golden_input_values.get(p.name) + if golden_val is not None: + port_dict["init_value"] = golden_val + _inputs_list.append(port_dict) + + tool_details = { + "id": node.id, # 节点 ID,用于唯一标识和调用这个具体节点 + "type": "Tool", + "inputs": _inputs_list, + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id 用于 Agent 内部判断工具类型(不会展示给被测模型) + if node.id in raw_nodes_data: + template_id = raw_nodes_data[node.id].get('template_id') + if template_id: + tool_details["_template_id"] = template_id # 使用下划线前缀标记为内部字段 + + # 只在 name 非空时添加 + # if node.name: + # tool_details["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_details["description"] = node.description + + # 添加 narrative 字段(如果存在) + if node.id in raw_nodes_data: + narrative = raw_nodes_data[node.id].get('narrative') + if narrative: + tool_details['narrative'] = narrative + + # 不再返回 init_values,避免泄漏答案 + # investigate 只应该返回工具的接口定义,不应该暴露初始值 + + # 【新增】检查该 Tool 是否有待触发的 HIDDEN_ITEM 掉落 + # 如果该工具已按照 golden_input 正确执行,且有 HIDDEN_ITEM 输出边,则触发掉落 + if node.has_hidden_item_ready: + logger.info(f"Tool has HIDDEN_ITEM ready - triggering passive drop for: {req.node_id}") + + # 遍历该工具的所有 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + # 重置标志,已经触发过了,避免重复 + node.has_hidden_item_ready = False + + logger.info(f"Tool investigation successful - node: {req.node_id}, revealed: {len(newly_revealed)}") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Tool", + "details": tool_details + } + + # 如果有新掉落的节点,添加到响应中 + if newly_revealed: + result["newly_revealed"] = newly_revealed + + return result + + # 处理 Item 的 investigate + elif node.type == "Item": + logger.info(f"Investigating item: {req.node_id}") + + # 【第一步】检查该 Item 是否有需要参数的输入端口 + # 如果有,且尚未通过 use_item 验证,则不返回内容,只返回参数要求 + required_inputs = [] + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + inputs_info = raw_node.get('inputs', []) + required_inputs = [ + { + "name": inp.get("name"), + "type": inp.get("type"), + "description": inp.get("description", "") + } + for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + # 如果有 required_inputs 且尚未通过 use_item 验证(if_success == False) + # 则不返回内容,只返回参数要求提示 + if required_inputs and not node.if_success: + logger.info(f"Item has required inputs and not yet unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "required_inputs": required_inputs + } + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + param_names = ', '.join([inp['name'] for inp in required_inputs]) + 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}" + + return result + + # 【新增】如果有 required_inputs 且已经通过 use_item 验证(if_success == True) + # 则返回提示:该节点已经被成功解决 + if required_inputs and node.if_success: + logger.info(f"Item has required inputs and already unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "message": "This item has already been successfully unlocked by you." + } + return result + + # 【第二步】该 Item 没有 required_inputs 或已通过验证,返回内容 + # 1. 返回 Item 的 golden_output_values(即 Item 的内容) + # 注意:某些 Item 仅用于触发 HIDDEN_ITEM 掉落,没有实际内容 + has_actual_content = bool(node.golden_output_values) or node.content is not None + content = node.golden_output_values if node.golden_output_values else node.content + + # 【关键】将 golden_output_values 追加到 actual_outputs_history,标记该 Item 已被 investigate + # 这样在渐进式暴露时,这些值才会被加入可见值集合 + # 即使是空字典(仅触发 HIDDEN_ITEM 的 Item),也要记录,以便渐进式暴露逻辑知道该 Item 已被调查 + if node.golden_output_values is not None: + node.actual_outputs_history.append(dict(node.golden_output_values)) + + # 2. Trigger Hidden Item Drops (Passive Drop) + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + logger.info(f"Item investigation successful - node: {req.node_id}, has_content: {has_actual_content}, revealed: {len(newly_revealed)}") + + # 【渐进式暴露】旧机制(基于 golden_input)已禁用 + # 现在完全由 ITEM/HIDDEN_ITEM 边触发控制节点可见性 + # 上面的 HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, node.golden_output_values or {}, node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # logger.info(f"Progressive reveal after Item investigate: {len(progressive_revealed)} nodes now ready") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Item" + } + + # 只在有实际内容时才添加 content 字段 + # 对于仅触发 HIDDEN_ITEM 掉落的 Item,不返回 content 字段,避免返回 None 或空字典让模型困惑 + if has_actual_content: + result["content"] = content + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型通过 investigate 获得内容后,需要自己识别这是否是胜利字符串 + + return result + + else: + logger.warning(f"Attempt to investigate unknown node type: {req.node_id} (type: {node.type})") + return {"ok": False, "error": f"Cannot investigate node type: {node.type}"} + +class ToolCallRequest(BaseModel): + node_id: str # 使用 node_id 精确指定要调用的节点 + arguments: Dict[str, Any] + +@app.post("/env/{case_id}/tool_call") +def tool_call(case_id: str, req: ToolCallRequest): + """Executes a tool and triggers item drops.""" + logger.info(f"Tool call request - case_id: {case_id}, node_id: {req.node_id}, args: {list(req.arguments.keys())}") + STATS["tool_calls"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + + # 通过 node_id 精确查找节点 + node_id = req.node_id + if node_id not in scenario.nodes: + logger.error(f"Node not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + tool_node = scenario.nodes[node_id] + + if not tool_node: + logger.error(f"Tool not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Tool not found") + + if not tool_node.is_revealed: + logger.warning(f"Attempt to call hidden tool: {node_id}") + return {"ok": False, "error": "Tool is not visible yet."} + + if tool_node.type != "Tool": + logger.warning(f"Attempt to call non-tool node: {node_id} (type: {tool_node.type})") + return {"ok": False, "error": "Only tools can be called."} + + # 1. Execute Tool (Real Execution via Simulator) + simulator = SIMULATORS[case_id] + + # Get tool name from template_id if available, otherwise use node name + tool_name = tool_node.name + if case_id in RAW_NODES_DATA and node_id in RAW_NODES_DATA[case_id]: + template_id = RAW_NODES_DATA[case_id][node_id].get('template_id') + if template_id: + tool_name = template_id + + # 文件处理工具和 Terminal 需要验证输入并返回预先计算的输出 + # 传递节点的实际输入输出值(从 DAG 执行后填充的数据) + tool_arguments = dict(req.arguments) # Make a copy + + # 传递节点的 golden values(从 JSON 的 inputs[].value 和 outputs[].value 加载) + # 用于在评测阶段验证被测模型传入的参数是否正确 + if tool_node.golden_input_values: + tool_arguments['_golden_inputs'] = tool_node.golden_input_values + if tool_node.golden_output_values: + tool_arguments['_golden_outputs'] = tool_node.golden_output_values + + logger.debug(f"Executing tool {tool_name} (node: {tool_node.name}) with args {tool_arguments}") + + try: + output_values = simulator.execute(tool_name, tool_arguments) + logger.info(f"Tool invoked - {tool_name}: {list(output_values.keys())}") + except Exception as e: + logger.error(f"Tool execution failed - {tool_name}: {str(e)}", exc_info=True) + return {"ok": False, "error": f"Tool execution failed: {str(e)}"} + + # 检查验证结果(精细化错误反馈) + validation = output_values.pop("_validation", {"valid": True}) + + if not validation["valid"]: + # 根据错误类型构造友好的错误消息 + error_type = validation.get("error_type") + + if error_type == "missing_required": + missing = validation.get("missing_params", []) + error_msg = f"Error: Missing required parameters {', '.join(missing)}" + + elif error_type == "type_error": + param = validation.get("param_name") + message = validation.get("message", "Parameter type error") + error_msg = f"Error: {message}" + + elif error_type == "incomplete_optional": + provided = validation.get("provided_params", []) + missing = validation.get("missing_params", []) + error_msg = ( + f"Hint: You provided some parameters ({', '.join(provided)}), " + f"but may also need: {', '.join(missing)}.\n" + f"Trying to provide these parameters together might yield better results." + ) + + elif error_type == "value_mismatch": + param = validation.get("param_name") + hint = validation.get("hint", "Parameter value may be incorrect") + error_msg = f"Hint: {hint}.\nPlease check if this parameter value meets the requirements." + + else: + error_msg = validation.get("hint") or validation.get("message", "Parameter validation failed") + + logger.info(f"Tool validation failed - {tool_name}: {error_type}") + return { + "ok": False, + "error": error_msg, + "error_type": error_type + } + + # Simulate success + tool_node.if_success = True + + # 【关键】将本次执行的输出值追加到历史列表(用于渐进式暴露判断) + # 每次调用都会记录,不会覆盖之前的执行结果 + tool_node.actual_outputs_history.append(dict(output_values)) + + # 2. 检查是否应该触发掉落(只有输入参数正确时才掉落) + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, tool_node.golden_input_values) + + newly_revealed = [] + investigate_hints = [] # 提示模型哪些节点可以 investigate 来发现隐藏内容 + + if inputs_match_golden: + logger.info(f"✓ Tool inputs match golden - node: {node_id}, triggering drops") + + # 检查该工具是否有 ITEM 或 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == tool_node.id: + target_node = scenario.nodes[edge.target_id] + + # ITEM 边:立即掉落(主动掉落) + if edge.connection_type == InterfaceType.ITEM: + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from {node_id})") + + # HIDDEN_ITEM 边:不立即掉落,标记并提示(被动掉落) + elif edge.connection_type == InterfaceType.HIDDEN_ITEM: + # 标记该工具有待触发的 HIDDEN_ITEM 掉落 + tool_node.has_hidden_item_ready = True + + # 提示模型可以 investigate 这个工具来发现隐藏内容 + hint_info = { + "tool_id": tool_node.id, + "hint": f"Tool '{tool_node.id}' seems to hide something, try investigating it to discover more information" + } + # if tool_node.name: + # hint_info["tool_name"] = tool_node.name + + investigate_hints.append(hint_info) + logger.info(f"HIDDEN_ITEM ready: {tool_node.id} -> {target_node.id} (will drop on investigate)") + else: + logger.info(f"✗ Tool inputs do NOT match golden - node: {node_id}, no drops triggered") + + response = { + "ok": True, + "message": "Tool invoked", + "output_values": output_values # Return raw outputs to Agent + } + + # 【新增】对源头节点进行参数验证反馈 + # 源头节点:没有数据流入边的节点,这些节点的参数需要模型自己推理 + # 验证模型使用的参数是否正确,并提供明确的反馈 + if _is_source_node(node_id, scenario) and tool_node.golden_input_values: + validation_feedback = _get_parameter_validation_feedback(req.arguments, tool_node.golden_input_values) + + if validation_feedback["all_correct"]: + # 用户提交了全部 golden 参数且全部正确 + response["parameter_feedback"] = { + "status": "correct", + "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." + } + logger.info(f"✓ Source node parameters all correct - node: {node_id}") + elif validation_feedback["incorrect_params"]: + # 有提交了但值错误的参数,只对这些参数给出反馈 + incorrect_list = [] + for param_name in validation_feedback["incorrect_params"]: + incorrect_list.append(f" - Parameter '{param_name}' is incorrect") + + correct_info = "" + if validation_feedback["correct_params"]: + correct_info = f"\n✓ Correct parameters: {', '.join(validation_feedback['correct_params'])}" + + response["parameter_feedback"] = { + "status": "incorrect", + "message": ( + f"⚠️ Some parameters are incorrect:\n" + + "\n".join(incorrect_list) + + correct_info + + 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." + ), + "incorrect_params": validation_feedback["incorrect_params"], + "correct_params": validation_feedback["correct_params"] + } + logger.info(f"✗ Source node parameters incorrect - node: {node_id}, incorrect: {validation_feedback['incorrect_params']}") + # else: 部分提交且全部正确 → 不给任何 parameter_feedback,避免对未提交的参数发表意见 + + # 检查工具调用是否完全正确(输出与 golden outputs 匹配) + # 用于给模型正向反馈,让它知道这个工具已经正确调用过,避免重复调用 + # 注意:只有当输出完全匹配时才标记为 correct,不会在错误时提供具体错误信息 + # if tool_node.golden_output_values and output_values: + # is_correct = True + # for port_name, expected_value in tool_node.golden_output_values.items(): + # actual_value = output_values.get(port_name) + # if str(actual_value) != str(expected_value): + # is_correct = False + # break + + # if is_correct: + # response["tool_call_correct"] = True + # logger.info(f"✓ Tool called with correct result - node: {node_id}") + + # 只在有新内容掉落时才返回 newly_revealed + if newly_revealed: + response["newly_revealed"] = newly_revealed + + # 添加 investigate 提示(对于有待触发 HIDDEN_ITEM 掉落的工具) + if investigate_hints: + response["investigate_hints"] = investigate_hints + + # 3. 渐进式暴露机制 - 现在完全由 ITEM/HIDDEN_ITEM 边控制 + # 旧机制(基于 golden_input 检查)已被禁用 + # 新机制中,节点的可见性只由 ITEM/HIDDEN_ITEM 边触发决定 + # 上面的 ITEM/HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, output_values, tool_node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # response["newly_revealed"] = newly_revealed + # logger.info(f"Progressive reveal: {len(progressive_revealed)} nodes now ready") + + # Check if this is the win node + if node_id == scenario.win_node_id: + # 验证输出值是否等于预期的胜利值 + # 从节点的 golden_output_values 中获取预期值(在 _initialize_node_values 时从 JSON 加载) + expected_outputs = tool_node.golden_output_values + + # 检查实际输出是否与预期输出匹配 + is_correct = False + victory_string = None + mismatch_info = [] + + if expected_outputs and output_values: + # 检查每个预期输出端口的值是否匹配 + is_correct = True + for port_name, expected_value in expected_outputs.items(): + actual_value = output_values.get(port_name) + if actual_value != expected_value: + is_correct = False + mismatch_info.append(f"Port '{port_name}': expected '{expected_value}', actual '{actual_value}'") + logger.warning(f"Win node output mismatch - port: {port_name}, expected: {expected_value}, actual: {actual_value}") + + # 如果所有输出都匹配,使用第一个输出作为胜利字符串 + if is_correct and output_values: + victory_string = list(output_values.values())[0] + else: + logger.warning(f"Win node called but missing output values - expected: {expected_outputs}, actual: {output_values}") + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型调用工具获得输出后,需要自己识别这是否是胜利字符串并提交 + if is_correct: + logger.info(f"🎯 Win node called with correct output - case: {case_id}, node: {node_id}, victory: {victory_string}") + else: + logger.info(f"❌ Win node called with incorrect output - case: {case_id}, node: {node_id}") + + return response + +class UseItemRequest(BaseModel): + node_id: str = Field(..., description="The ID of the Item node to use (must be Item type)") + arguments: Dict[str, Any] = Field(default_factory=dict, description="Input arguments to provide to the item") + +@app.post("/env/{case_id}/use_item") +def use_item(case_id: str, req: UseItemRequest): + """ + Use an Item node by providing input arguments. + + This is specifically for Item nodes that require parameters to be "unlocked" or "activated", + such as containers that need a password/fingerprint. + + - Validates that the node is of type Item + - Checks if provided arguments match the item's golden_input_values + - If match: triggers ITEM-type edge drops and returns the item's content + - If not match: returns error message + """ + logger.info(f"Use item request - case_id: {case_id}, node_id: {req.node_id}, args: {req.arguments}") + STATS["use_items"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + item_node = scenario.nodes[req.node_id] + + if not item_node.is_revealed: + logger.warning(f"Attempt to use hidden item: {req.node_id}") + return {"ok": False, "error": "Item is not visible yet."} + + if item_node.type != "Item": + logger.warning(f"Attempt to use non-item node: {req.node_id} (type: {item_node.type})") + return {"ok": False, "error": "Only Item nodes can be used with use_item. Tools should be called with tool_call."} + + # 【新增】检查该 Item 是否已经被成功解锁 + # 如果已经被正确使用过,直接返回成功提示 + if item_node.if_success: + logger.info(f"Item already unlocked, returning success message: {req.node_id}") + return { + "ok": True, + "message": "This item has already been successfully unlocked by you." + } + + # 检查该 Item 是否真的需要通过 use_item 提供参数 + # 只有当 Item 有非 Item/Hidden_Item 类型的输入时,才应该使用 use_item + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + non_hidden_inputs = [ + inp for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + if not non_hidden_inputs: + # 该 Item 不需要参数,应该只使用 investigate + logger.warning(f"Attempt to use_item on a node that doesn't require parameters: {req.node_id}") + return { + "ok": False, + "error": "This item does not require parameters. Please use investigate to examine the item directly." + } + + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, item_node.golden_input_values) + + if not inputs_match_golden: + logger.info(f"✗ Item inputs do NOT match golden - node: {req.node_id}") + # 提供更详细的错误信息,帮助 Agent 理解问题 + # 只显示非 Item/Hidden_Item 类型的参数(Hidden_Item 由系统自动处理) + expected_params = [] + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + expected_params = [ + inp.get("name") for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + provided_params = list(req.arguments.keys()) if req.arguments else [] + + # 检查参数名是否匹配 + if set(expected_params) == set(provided_params): + # 参数名正确但值不匹配 - 不泄漏正确的值 + error_msg = f"Parameter names are correct, but the parameter values are incorrect. Please try using different parameter values." + else: + error_msg = f"Parameter names do not match. Expected parameter names: {expected_params}, you provided: {provided_params}." + + return { + "ok": False, + "error": error_msg + } + + logger.info(f"✓ Item inputs match golden - node: {req.node_id}, activating item") + + # 标记该 Item 已被正确使用 + item_node.if_success = True + + # 将 golden_output_values 追加到 actual_outputs_history + if item_node.golden_output_values: + item_node.actual_outputs_history.append(dict(item_node.golden_output_values)) + + # 触发 ITEM 类型边的掉落 + newly_revealed = [] + for edge in scenario.edges: + if edge.source_id == item_node.id and edge.connection_type == InterfaceType.ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from use_item on {req.node_id})") + + # 检查是否为 Win Node + win_node_id = scenario.win_node_id + is_win_node = (req.node_id == win_node_id) + + # 构建返回结果 + result = { + "ok": True, + "message": "Item used successfully.", + "content": item_node.golden_output_values if item_node.golden_output_values else None + } + + # 获取 narrative(如果存在) + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + narrative = raw_nodes_data[req.node_id].get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 如果是 Win Node,只记录日志 + if is_win_node: + logger.info(f"Win node (Item) unlocked via use_item - case: {case_id}, node: {req.node_id}") + + return result + + +class SubmitAnswerRequest(BaseModel): + answer: str = Field(..., description="The victory string to submit") + +@app.post("/env/{case_id}/submit_answer") +def submit_answer(case_id: str, req: SubmitAnswerRequest): + """ + 提交答案接口 + 被测模型在获得胜利字符串提示后,需要调用此接口提交答案 + """ + logger.info(f"Submit answer request - case_id: {case_id}, answer: {req.answer}") + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + + # 获取 win_node 的 golden_output_values + if not scenario.win_node_id: + logger.error(f"No win node defined for case: {case_id}") + return { + "ok": False, + "error": "This case has no victory node defined" + } + + win_node = scenario.nodes.get(scenario.win_node_id) + if not win_node: + logger.error(f"Win node not found: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node does not exist" + } + + # 获取正确的胜利字符串(取第一个 golden_output_value) + if win_node.golden_output_values: + correct_answer = list(win_node.golden_output_values.values())[0] + else: + logger.error(f"Win node has no golden_output_values: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node has no correct answer" + } + + # 验证提交的答案 + if req.answer == correct_answer: + logger.info(f"🎉 CORRECT ANSWER SUBMITTED - case: {case_id}, answer: {req.answer}") + return { + "ok": True, + "is_win": True, + "victory_message": f"🎉 Congratulations on successfully escaping the room! Your answer is correct: {req.answer}" + } + else: + logger.info(f"❌ INCORRECT ANSWER SUBMITTED - case: {case_id}, submitted: {req.answer}, correct: {correct_answer}") + return { + "ok": True, + "is_win": False, + "error": f"The submitted answer is incorrect. You submitted: {req.answer}" + } + +if __name__ == "__main__": + + uvicorn.run(app, host="0.0.0.0", port=8000) \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-6ae6d120/environment/puzzle/upstream/simulator.py b/tasks/agentescape-25-skeleton-6ae6d120/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-25-skeleton-6ae6d120/environment/puzzle/upstream/simulator.py @@ -0,0 +1,2911 @@ +import hashlib +import hmac +import base64 +import binascii +import zlib +import json +import uuid +import math +import re +from typing import Dict, Any, List + +class ToolSimulator: + def __init__(self): + """工具模拟器 + + 文件处理工具(zip_unzip, zip_unzip_file, zip_unzip_item, json_get, csv_query, + regex_search, graph_shortest_path)不需要真实文件系统。 + 这些工具只验证输入参数,然后返回预先初始化好的 golden_outputs。 + """ + self.tool_map = { + # 数论 + "calc_bigmul": self.calc_bigmul, + "calc_modexp": self.calc_modexp, + "calc_modexp_int": self.calc_modexp_int, + "calc_gcd": self.calc_gcd, + "calc_gcd_int": self.calc_gcd_int, + "calc_inv_mod": self.calc_inv_mod, + "calc_inv_mod_int": self.calc_inv_mod_int, + + # 哈希 + "hash_sha256": self.hash_sha256, + "hash_md5": self.hash_md5, + "hmac_sha256": self.hmac_sha256, + + # 编码 + "base64_decode": self.base64_decode, + "base64_encode": self.base64_encode, + "hex_decode": self.hex_decode, + "hex_encode": self.hex_encode, + "zlib_inflate": self.zlib_inflate, + "zlib_deflate": self.zlib_deflate, + + # 文件 + "zip_unzip": self.zip_unzip, + "zip_unzip_file": self.zip_unzip_file, + "zip_unzip_item": self.zip_unzip_item, + "regex_search": self.regex_search, + "json_get": self.json_get, + "csv_query": self.csv_query, + "code_py_exec": self.code_py_exec, + + # 图 + "graph_shortest_path": self.graph_shortest_path, + + # 加解密 (简化模拟) + "crypto_aes_cbc_decrypt": self.crypto_aes_cbc_decrypt, + "crypto_rsa_decrypt_hex": self.crypto_rsa_decrypt_hex, + + # 其他 + "num_base_convert": self.num_base_convert, + "time_convert": self.time_convert, + "checksum_crc32": self.checksum_crc32, + "geo_haversine": self.geo_haversine, + "otp_totp_generate": self.otp_totp_generate, + "unicode_norm": self.unicode_norm, + "text_bidi_sanitize": self.text_bidi_sanitize, + "text_xor_hex": self.text_xor_hex, + "text_rotN": self.text_rotN, + "luhn_check": self.luhn_check, + "iban_validate": self.iban_validate, + + # 物理 + "matter_synthesizer": self.matter_synthesizer, + + # 终端机 + "terminal_1": self.terminal_1, + "terminal_2": self.terminal_2, + "Logic Terminal": self.logic_terminal, + "Math Terminal": self.math_terminal, + "Encryption Terminal": self.crypt_terminal, + "Sequence Terminal": self.sequence_terminal + } + + def execute(self, tool_name: str, inputs: Dict[str, Any]) -> Dict[str, Any]: + if tool_name not in self.tool_map: + # Fallback for unknown tools: return dummy outputs based on expected output types + # This should ideally not happen if all tools are implemented + return {} + + try: + return self.tool_map[tool_name](inputs) + except Exception as e: + print(f"Error executing {tool_name}: {e}") + # Return empty or error indication? For generation, we might want to fail hard or return dummy. + # For now, return dummy to keep flow going, but log error. + return {} + + # --- Implementations --- + + def calc_bigmul(self, inputs): + # Check if required parameters are present + if "a" not in inputs or "b" not in inputs: + raise ValueError("Missing required parameters 'a' and/or 'b'") + + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + return {"product": str(a * b)} + except (ValueError, TypeError) as e: + raise ValueError(f"Failed to convert parameters to integers: {str(e)}") + + def calc_modexp(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + try: + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if isinstance(base, str): + base = int(base) + elif not isinstance(base, int): + raise ValueError("Parameter 'base' must be a string or integer") + + if isinstance(exp, str): + exp = int(exp) + elif not isinstance(exp, int): + raise ValueError("Parameter 'exp' must be a string or integer") + + if isinstance(mod, str): + mod = int(mod) + elif not isinstance(mod, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": str(pow(base, exp, mod))} + + def calc_modexp_int(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["base"], int): + raise ValueError("Parameter 'base' must be an integer") + if not isinstance(inputs["exp"], int): + raise ValueError("Parameter 'exp' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": pow(base, exp, mod)} + + def calc_gcd(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + # 计算 GCD 并返回字符串格式(符合 Big_Int 输出类型) + result = math.gcd(a, b) + return {"gcd": str(result)} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def calc_gcd_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["b"], int): + raise ValueError("Parameter 'b' must be an integer") + + # 获取参数 + a = inputs["a"] + b = inputs["b"] + + return {"gcd": math.gcd(a, b)} + + def calc_inv_mod(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + m = inputs["mod"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(m, str): + m = int(m) + elif not isinstance(m, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": str(pow(a, -1, m))} + except ValueError as e: + # 模逆不存在时,返回一个特殊值(用于数据传递) + # 在 DAG 生成阶段,这允许数据流继续 + return {"inv": str(a)} + + def calc_inv_mod_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + a = inputs["a"] + m = inputs["mod"] + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": pow(a, -1, m)} + except ValueError as e: + raise ValueError(f"Modular inverse does not exist: {str(e)}") + + def hash_sha256(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.sha256(text.encode()).hexdigest()} + + def hash_md5(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.md5(text.encode()).hexdigest()} + + def hmac_sha256(self, inputs): + # 参数检查 + if "hex_key" not in inputs: + raise ValueError("Missing required parameter: hex_key") + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["hex_key"], str): + raise ValueError("Parameter 'hex_key' must be a string") + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + try: + key = bytes.fromhex(inputs["hex_key"]) + text = inputs["text"].encode() + return {"hex": hmac.new(key, text, hashlib.sha256).hexdigest()} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def base64_decode(self, inputs): + # 参数检查 + if "data" not in inputs: + raise ValueError("Missing required parameter: data") + + # 类型检查 + if not isinstance(inputs["data"], str): + raise ValueError("Parameter 'data' must be a string") + + data = inputs["data"] + try: + return {"bytes_hex": binascii.hexlify(base64.b64decode(data)).decode()} + except Exception as e: + raise ValueError(f"Base64 decode error: {str(e)}") + + def base64_encode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"b64": base64.b64encode(bytes.fromhex(hex_data)).decode()} + except Exception as e: + raise ValueError(f"Base64 encode error: {str(e)}") + + def hex_decode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"text": bytes.fromhex(hex_data).decode('utf-8', errors='ignore')} + except Exception as e: + raise ValueError(f"Hex decode error: {str(e)}") + + def hex_encode(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + try: + return {"hex": text.encode().hex()} + except Exception as e: + raise ValueError(f"Hex encode error: {str(e)}") + + + # 到此处实现已经更新 + + def zlib_inflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("Parameter 'hex' must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("Missing required parameter: hex") + + try: + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空字符串 + if not hex_data: + raise ValueError("Empty hex string provided") + + # 检查十六进制字符串的有效性 + if len(hex_data) % 2 != 0: + raise ValueError("Hex string must have even length") + + # 检查是否只包含有效的十六进制字符 + if not all(c in '0123456789abcdefABCDEF' for c in hex_data): + raise ValueError("Invalid hex string provided") + + # 尝试解压缩 + return {"text": zlib.decompress(bytes.fromhex(hex_data)).decode('utf-8')} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hex string provided") from e + raise ValueError(f"Invalid zlib data: {e}") from e + except Exception as e: + raise RuntimeError(f"Failed to inflate data: {e}") from e + + def zlib_deflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("Parameter 'text' must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("Missing required parameter: text") + + try: + # 压缩文本 + return {"hex": zlib.compress(text.encode('utf-8')).hex()} + except Exception as e: + raise RuntimeError(f"Failed to deflate data: {e}") from e + + # --- File Operations --- + + def zip_unzip(self, inputs): + """ZIP 解压工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"files": golden_outputs.get("files", "")} + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return {"files": golden_outputs.get("files", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "files" in golden_outputs: + # 验证必需参数 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 检查类型 + if has_zip_id and not isinstance(zip_id, str): + return {"error": "Parameter 'zip_id' must be a string type"} + if has_password and not isinstance(password, str): + return {"error": "Parameter 'password' must be a string type"} + + # 验证输入是否与预期匹配 + if golden_inputs: + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return {"files": golden_outputs["files"]} + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + # 没有golden_inputs但有golden_outputs,直接返回输出 + return {"files": golden_outputs["files"]} + + # 如果没有预期输出,返回空结果 + return {"files": ""} + + def regex_search(self, inputs): + """正则搜索工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"matches": golden_outputs.get("matches", "[]")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "matches" in golden_outputs: + # 提取实际参数 + pattern = inputs.get("pattern") + file_id = inputs.get("file_id") + text = inputs.get("text") + + # 1. 检查必需参数 + if pattern is None: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["pattern"], + "message": "Missing required parameter 'pattern'" + } + } + + # 类型检查 + if not isinstance(pattern, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "pattern", + "message": "Parameter 'pattern' must be a string type" + } + } + if file_id is not None and not isinstance(file_id, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if text is not None and not isinstance(text, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "text", + "message": "Parameter 'text' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合 + provided_params = {} + if pattern is not None: + provided_params["pattern"] = pattern + if file_id is not None: + provided_params["file_id"] = file_id + if text is not None: + provided_params["text"] = text + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数(关键改进) + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_pattern = golden_inputs.get("pattern") + expected_file_id = golden_inputs.get("file_id") + expected_text = golden_inputs.get("text") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_pattern is not None: + if str(pattern) != str(expected_pattern): + incorrect_params.append("pattern") + else: + correct_params.append("pattern") + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_text is not None: + if str(text) != str(expected_text): + incorrect_params.append("text") + else: + correct_params.append("text") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "matches": "[]", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "matches": golden_outputs["matches"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空列表 + return {"matches": "[]"} + + def json_get(self, inputs): + """JSON 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"values": golden_outputs.get("values", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "values" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + jsonpath = inputs.get("jsonpath", "") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if jsonpath is not None and not isinstance(jsonpath, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "jsonpath", + "message": "Parameter 'jsonpath' must be a string type" + } + } + + # 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:jsonpath有默认值"") + provided_params = {} + if file_id is not None: + provided_params["file_id"] = file_id + if jsonpath != "": + provided_params["jsonpath"] = jsonpath + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_jsonpath = golden_inputs.get("jsonpath") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_jsonpath is not None: + if str(jsonpath) != str(expected_jsonpath): + incorrect_params.append("jsonpath") + else: + correct_params.append("jsonpath") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "values": "", + "_validation": validation_info + } + + # 所有验证通过,返回正确输出 + return { + "values": golden_outputs["values"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"values": ""} + + def csv_query(self, inputs): + """CSV 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"rows": golden_outputs.get("rows", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "rows" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + select_columns = inputs.get("select", "") + where_clause = inputs.get("where", "") + + # 1. 检查必需参数 + if file_id is None: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["file_id"], + "message": "Missing required parameter 'file_id'" + } + } + + # 类型检查 + if not isinstance(file_id, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if not isinstance(select_columns, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "select", + "message": "Parameter 'select' must be a string type" + } + } + if not isinstance(where_clause, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "where", + "message": "Parameter 'where' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:select和where有默认值"") + provided_params = {"file_id": file_id} + if select_columns != "": + provided_params["select"] = select_columns + if where_clause != "": + provided_params["where"] = where_clause + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_select = golden_inputs.get("select") + expected_where = golden_inputs.get("where") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_select is not None: + if str(select_columns) != str(expected_select): + incorrect_params.append("select") + else: + correct_params.append("select") + + if expected_where is not None: + if str(where_clause) != str(expected_where): + incorrect_params.append("where") + else: + correct_params.append("where") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "rows": "", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "rows": golden_outputs["rows"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"rows": ""} + + def graph_shortest_path(self, inputs): + """图最短路径工具 + + 如果有 _golden_outputs 或 _init_outputs,验证输入并返回预设输出。 + 否则执行真实的 Dijkstra 算法。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 检查是否在预设模式中(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + if golden_outputs and "path" in golden_outputs: + # 评测阶段但没有 golden_inputs,直接返回 outputs + if not golden_inputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 评测模式:验证输入参数是否匹配 golden 值 + src = inputs.get("src") + dst = inputs.get("dst") + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + + has_src = src is not None and src != "" + has_dst = dst is not None and dst != "" + + # 验证必需参数 + if not has_src or not has_dst: + missing = [] + if not has_src: + missing.append("src") + if not has_dst: + missing.append("dst") + return {"error": "Missing required parameters: " + ", ".join(missing)} + + # 类型检查 + if not isinstance(src, str): + return {"error": "Parameter 'src' must be a string"} + if not isinstance(dst, str): + return {"error": "Parameter 'dst' must be a string"} + + # 验证输入是否匹配期望值 + if golden_inputs: + expected_src = golden_inputs.get("src") + expected_dst = golden_inputs.get("dst") + expected_file_id = golden_inputs.get("file_id") + expected_graph_data = golden_inputs.get("graph_data") + + # 收集验证结果 + incorrect_params = [] + correct_params = [] + + # 检查必需参数是否匹配 + if expected_src is not None: + if str(src) != str(expected_src): + incorrect_params.append("src") + else: + correct_params.append("src") + + if expected_dst is not None: + if str(dst) != str(expected_dst): + incorrect_params.append("dst") + else: + correct_params.append("dst") + + # 检查可选参数(如果在 expected_inputs 中定义了) + if expected_file_id is not None: + if file_id != expected_file_id: + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_graph_data is not None: + if graph_data != expected_graph_data: + incorrect_params.append("graph_data") + else: + correct_params.append("graph_data") + + # 如果有参数不正确,返回详细的反馈 + if incorrect_params: + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 验证通过,返回预设的输出 + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 获取参数(真实执行路径) + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + # Support both src/dst (interface definition) and start/end (original implementation) + start = inputs.get("src") + end = inputs.get("dst") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + raise TypeError("file_id must be a string") + + if graph_data is not None and not isinstance(graph_data, str): + raise TypeError("graph_data must be a string") + + if start is not None and not isinstance(start, str): + raise TypeError("src/start must be a string") + + if end is not None and not isinstance(end, str): + raise TypeError("dst/end must be a string") + + # 检查必需参数 + if file_id is None and graph_data is None: + raise ValueError("Either file_id or graph_data must be provided") + + if start is None: + raise ValueError("src/start parameter is required") + + if end is None: + raise ValueError("dst/end parameter is required") + + # Get graph content + content = None + if file_id is not None: + # 尝试从 VFS 获取(如果存在) + if hasattr(self, 'vfs') and file_id in self.vfs: + content = self.vfs[file_id] + else: + # VFS 不存在或文件不在 VFS 中 + # 返回一个默认的空图结果,或者抛出错误提示需要 init_outputs + raise ValueError( + f"File '{file_id}' not found. For tools that require files, " + f"please provide init_outputs in the initial_values." + ) + elif graph_data is not None: + content = graph_data + + if content is None: + content = "{}" + + try: + # Parse graph data + graph = json.loads(content) + + # 类型检查 + if not isinstance(graph, dict): + raise TypeError("Graph data must be a dictionary") + + # If graph is not in the expected format, try to extract adjacency list + if "nodes" in graph and "edges" in graph: + # 验证nodes和edges的类型 + if not isinstance(graph["nodes"], list): + raise TypeError("Nodes must be a list") + + if not isinstance(graph["edges"], list): + raise TypeError("Edges must be a list") + + # Convert from nodes/edges format to adjacency list + adjacency_list = {} + for node in graph["nodes"]: + # 验证node类型 + if not isinstance(node, dict): + raise TypeError("Each node must be a dictionary") + + # Use node ID as key, not the entire node dictionary + node_id = node.get("id", "") + if node_id: + adjacency_list[node_id] = {} + + for edge in graph["edges"]: + # 验证edge类型 + if not isinstance(edge, dict): + raise TypeError("Each edge must be a dictionary") + + u = edge["from"] + v = edge["to"] + weight = edge.get("weight", 1) # Default to unweighted + + # 类型检查 + if not isinstance(u, str): + raise TypeError("Edge 'from' must be a string") + + if not isinstance(v, str): + raise TypeError("Edge 'to' must be a string") + + if not isinstance(weight, (int, float)): + raise TypeError("Edge weight must be a number") + + if u not in adjacency_list: + adjacency_list[u] = {} + if v not in adjacency_list: + adjacency_list[v] = {} + + adjacency_list[u][v] = weight + # If undirected, add reverse edge + if not edge.get("directed", False): + adjacency_list[v][u] = weight + elif isinstance(graph, dict): + # Already in adjacency list format + adjacency_list = graph + + # 验证邻接表结构 + for node, neighbors in adjacency_list.items(): + if not isinstance(neighbors, dict): + raise TypeError("Adjacency list must be a dictionary of dictionaries") + + for neighbor, weight in neighbors.items(): + if not isinstance(weight, (int, float)): + raise TypeError("Edge weights must be numbers") + else: + raise TypeError("Graph data must be a dictionary") + + # 检查起点和终点是否为空 + if not start: + raise ValueError("Start node cannot be empty") + + if not end: + raise ValueError("End node cannot be empty") + + # 检查起点和终点是否在图中 + if start not in adjacency_list: + raise ValueError(f"Start node '{start}' not found in graph") + + if end not in adjacency_list: + raise ValueError(f"End node '{end}' not found in graph") + + # Dijkstra's algorithm implementation + import heapq + + # Initialize distances and previous nodes + distances = {node: float('infinity') for node in adjacency_list} + previous = {node: None for node in adjacency_list} + distances[start] = 0 + + # Priority queue + pq = [(0, start)] + heapq.heapify(pq) + + while pq: + current_dist, current_node = heapq.heappop(pq) + + # If we've reached the end node, we can break early + if current_node == end: + break + + # Nodes can be added multiple times to the priority queue, but we only process them once + if current_dist > distances[current_node]: + continue + + # Explore neighbors + for neighbor, weight in adjacency_list[current_node].items(): + distance = current_dist + weight + + # If a shorter path is found + if distance < distances[neighbor]: + distances[neighbor] = distance + previous[neighbor] = current_node + heapq.heappush(pq, (distance, neighbor)) + + # Reconstruct the shortest path + path = [] + current = end + while current is not None: + path.append(current) + current = previous[current] + path.reverse() # Reverse to get from start to end + + # Check if path exists + if not path or path[0] != start: + return {"path": "[]", "cost": 0} + + return { + "path": json.dumps(path), + "cost": distances[end] + } + except json.JSONDecodeError as e: + raise ValueError(f"Invalid JSON in graph data: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in graph_shortest_path: {str(e)}") + + # --- Crypto (Simplified) --- + def crypto_aes_cbc_decrypt(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 (使用模板中定义的参数名) + hex_cipher = inputs.get("hex_cipher") + hex_key = inputs.get("hex_key") + hex_iv = inputs.get("hex_iv") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + + if hex_key is not None and not isinstance(hex_key, str): + raise TypeError("hex_key must be a string") + + if hex_iv is not None and not isinstance(hex_iv, str): + raise TypeError("hex_iv must be a string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + + if hex_key is None: + raise ValueError("hex_key parameter is required") + + if hex_iv is None: + raise ValueError("hex_iv parameter is required") + + from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes + from cryptography.hazmat.backends import default_backend + from cryptography.hazmat.primitives import padding + + try: + # Convert hex strings to bytes + ciphertext = bytes.fromhex(hex_cipher) + key = bytes.fromhex(hex_key) + iv = bytes.fromhex(hex_iv) + + # Validate key length (AES-128, AES-192, AES-256) + if len(key) not in [16, 24, 32]: + raise ValueError("Invalid key length. Must be 16, 24, or 32 bytes.") + + if len(iv) != 16: + raise ValueError("Invalid IV length. Must be 16 bytes.") + + # Create cipher object + cipher = Cipher( + algorithms.AES(key), + modes.CBC(iv), + backend=default_backend() + ) + + decryptor = cipher.decryptor() + + # Decrypt the ciphertext + padded_plaintext = decryptor.update(ciphertext) + decryptor.finalize() + + # Remove PKCS7 padding + unpadder = padding.PKCS7(128).unpadder() + plaintext = unpadder.update(padded_plaintext) + unpadder.finalize() + + # Return decrypted text + return {"text": plaintext.decode('utf-8', errors='ignore')} + except ValueError as e: + if "non-hexadecimal number found in fromhex()" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher, hex_key, or hex_iv") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in crypto_aes_cbc_decrypt: {str(e)}") + + def crypto_rsa_decrypt_hex(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_cipher = inputs.get("hex_cipher") + n = inputs.get("n") + d = inputs.get("d") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + if n is not None and not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + if d is not None and not isinstance(d, (int, str)): + raise TypeError("d must be an integer or string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + if n is None: + raise ValueError("n parameter is required") + if d is None: + raise ValueError("d parameter is required") + + try: + # Convert parameters to appropriate types + cipher_int = int(hex_cipher, 16) + n_int = int(n) if isinstance(n, str) else n + d_int = int(d) if isinstance(d, str) else d + + # RSA decryption: plaintext = ciphertext^d mod n + plaintext_int = pow(cipher_int, d_int, n_int) + + # Convert result to hex and then to text + plaintext_hex = hex(plaintext_int)[2:] + + # Pad with leading zero if odd length + if len(plaintext_hex) % 2 != 0: + plaintext_hex = '0' + plaintext_hex + + # Convert hex to bytes and then to text + try: + plaintext_bytes = bytes.fromhex(plaintext_hex) + plaintext_text = plaintext_bytes.decode('utf-8', errors='ignore') + except: + # If decoding fails, return hex representation + plaintext_text = plaintext_hex + + return {"text": plaintext_text} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in crypto_rsa_decrypt_hex: {str(e)}") + + # --- Others --- + def num_base_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + s = inputs.get("s") + from_base = inputs.get("from_base") + to_base = inputs.get("to_base") + + # 类型检查 - 接受 str 或 int + if s is not None and not isinstance(s, (str, int)): + raise TypeError("s must be a string or integer") + + if from_base is not None and not isinstance(from_base, (int, str)): + raise TypeError("from_base must be an integer") + + if to_base is not None and not isinstance(to_base, (int, str)): + raise TypeError("to_base must be an integer") + + # 检查必需参数 + if s is None: + raise ValueError("s parameter is required") + + if from_base is None: + raise ValueError("from_base parameter is required") + + if to_base is None: + raise ValueError("to_base parameter is required") + + try: + # Convert to int if needed + from_base = int(from_base) if isinstance(from_base, str) else from_base + to_base = int(to_base) if isinstance(to_base, str) else to_base + s_str = str(s) + + # 验证基数范围 + if from_base < 2 or from_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + if to_base < 2 or to_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + # Convert from source base to decimal + val = int(s_str, from_base) + + # Convert from decimal to target base + if to_base == 10: + result = str(val) + elif to_base == 16: + result = hex(val)[2:] + elif to_base == 8: + result = oct(val)[2:] + elif to_base == 2: + result = bin(val)[2:] + else: + # Generic base conversion for other bases + if val == 0: + result = "0" + else: + digits = "0123456789abcdefghijklmnopqrstuvwxyz" + result = "" + n = abs(val) + while n: + result = digits[n % to_base] + result + n //= to_base + if val < 0: + result = "-" + result + + return {"str": result} + except ValueError as e: + raise ValueError(f"Invalid number format: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in num_base_convert: {str(e)}") + + def time_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iso = inputs.get("iso") + timestamp = inputs.get("timestamp") + datetime_str = inputs.get("datetime") + from_tz = inputs.get("from_tz") + to_tz = inputs.get("to_tz") + format_str = inputs.get("format") + + # 类型检查 + if iso is not None and not isinstance(iso, str): + raise TypeError("iso must be a string") + + if timestamp is not None and not isinstance(timestamp, (str, int, float)): + raise TypeError("timestamp must be a string, integer, or float") + + if datetime_str is not None and not isinstance(datetime_str, str): + raise TypeError("datetime must be a string") + + if from_tz is not None and not isinstance(from_tz, str): + raise TypeError("from_tz must be a string") + + if to_tz is not None and not isinstance(to_tz, str): + raise TypeError("to_tz must be a string") + + if format_str is not None and not isinstance(format_str, str): + raise TypeError("format must be a string") + + # 设置默认值 + if from_tz is None: + from_tz = "UTC" + + if to_tz is None: + to_tz = "UTC" + + import datetime + import pytz + + # 验证时区参数 + try: + if from_tz: + pytz.timezone(from_tz) + if to_tz: + pytz.timezone(to_tz) + except Exception: + raise ValueError("Invalid timezone provided") + + try: + # Parse input time + dt = None + + if iso is not None: + # Parse ISO 8601 format + dt = datetime.datetime.fromisoformat(iso.replace('Z', '+00:00')) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=pytz.UTC) + elif timestamp is not None: + # Parse Unix timestamp + timestamp = float(timestamp) + dt = datetime.datetime.fromtimestamp(timestamp, pytz.UTC) + elif datetime_str is not None: + # Parse datetime string + # Try common formats + formats_to_try = [ + "%Y-%m-%d %H:%M:%S", + "%Y-%m-%d %H:%M:%S.%f", + "%Y-%m-%d", + "%m/%d/%Y %H:%M:%S", + "%m/%d/%Y" + ] + + parse_success = False + for fmt in formats_to_try: + try: + dt = datetime.datetime.strptime(datetime_str, fmt) + dt = pytz.timezone(from_tz).localize(dt) + parse_success = True + break + except ValueError: + continue + + if not parse_success: + raise ValueError("Unable to parse datetime string with common formats") + else: + # 如果没有提供任何时间参数,则使用当前时间 + dt = datetime.datetime.now(pytz.UTC) + except ValueError as e: + raise ValueError(f"Error parsing time input: {str(e)}") + except Exception as e: + raise RuntimeError(f"Unexpected error parsing time input: {str(e)}") + + try: + # Convert timezone + if from_tz != to_tz: + dt = dt.astimezone(pytz.timezone(to_tz)) + + # Format outputs + result = { + "iso": dt.isoformat(), + "timestamp": str(dt.timestamp()), + "datetime": dt.strftime("%Y-%m-%d %H:%M:%S"), + "date": dt.strftime("%Y-%m-%d"), + "time": dt.strftime("%H:%M:%S"), + "timezone": to_tz + } + + # Add custom format if requested + if format_str: + try: + result["formatted"] = dt.strftime(format_str) + except ValueError as e: + raise ValueError(f"Invalid format string: {str(e)}") + + return result + except Exception as e: + raise RuntimeError(f"Error in time_convert: {str(e)}") + + def checksum_crc32(self, inputs): + import zlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("hex must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("hex parameter is required") + + try: + # 验证十六进制字符串 + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空 + if not hex_data: + raise ValueError("hex data cannot be empty") + + # 检查是否为有效的十六进制字符串 + if not all(c in "0123456789abcdefABCDEF" for c in hex_data): + raise ValueError("hex must be a valid hexadecimal string") + + # 检查长度是否为偶数 + if len(hex_data) % 2 != 0: + raise ValueError("hex must have even number of characters") + + val = zlib.crc32(bytes.fromhex(hex_data)) + # 确保 hex 输出是 8 位,前导补 0 + return {"hex": f"{val:08x}", "int": val} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in checksum_crc32: {str(e)}") + + def geo_haversine(self, inputs): + import math + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + lat1 = inputs.get("lat1") + lon1 = inputs.get("lon1") + lat2 = inputs.get("lat2") + lon2 = inputs.get("lon2") + + # 类型检查 + if lat1 is not None and not isinstance(lat1, (int, float, str)): + raise TypeError("lat1 must be a number or string") + if lon1 is not None and not isinstance(lon1, (int, float, str)): + raise TypeError("lon1 must be a number or string") + if lat2 is not None and not isinstance(lat2, (int, float, str)): + raise TypeError("lat2 must be a number or string") + if lon2 is not None and not isinstance(lon2, (int, float, str)): + raise TypeError("lon2 must be a number or string") + + # 检查必需参数 + if lat1 is None: + raise ValueError("lat1 parameter is required") + if lon1 is None: + raise ValueError("lon1 parameter is required") + if lat2 is None: + raise ValueError("lat2 parameter is required") + if lon2 is None: + raise ValueError("lon2 parameter is required") + + try: + # 转换为浮点数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(lat1, str): + lat1 = float(lat1) + elif not isinstance(lat1, (int, float)): + raise TypeError("lat1 must be a number or string") + else: + lat1 = float(lat1) + + if isinstance(lon1, str): + lon1 = float(lon1) + elif not isinstance(lon1, (int, float)): + raise TypeError("lon1 must be a number or string") + else: + lon1 = float(lon1) + + if isinstance(lat2, str): + lat2 = float(lat2) + elif not isinstance(lat2, (int, float)): + raise TypeError("lat2 must be a number or string") + else: + lat2 = float(lat2) + + if isinstance(lon2, str): + lon2 = float(lon2) + elif not isinstance(lon2, (int, float)): + raise TypeError("lon2 must be a number or string") + else: + lon2 = float(lon2) + + # Validate coordinates (approximate range check) + if not (-90 <= lat1 <= 90): + raise ValueError("lat1 must be between -90 and 90") + if not (-90 <= lat2 <= 90): + raise ValueError("lat2 must be between -90 and 90") + if not (-180 <= lon1 <= 180): + raise ValueError("lon1 must be between -180 and 180") + if not (-180 <= lon2 <= 180): + raise ValueError("lon2 must be between -180 and 180") + + # Earth radius in meters + R = 6371000 # Approximate radius of Earth + + # Convert degrees to radians + lat1_rad = math.radians(lat1) + lon1_rad = math.radians(lon1) + lat2_rad = math.radians(lat2) + lon2_rad = math.radians(lon2) + + # Calculate differences + delta_lat = lat2_rad - lat1_rad + delta_lon = lon2_rad - lon1_rad + + # Haversine formula + a = math.sin(delta_lat / 2) ** 2 + \ + math.cos(lat1_rad) * math.cos(lat2_rad) * \ + math.sin(delta_lon / 2) ** 2 + c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) + distance_m = R * c + + # Return distance in meters + return {"meters": round(distance_m, 2)} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in geo_haversine: {str(e)}") + + def otp_totp_generate(self, inputs): + import hmac + import hashlib + import base64 + import time + import struct + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + base32_secret = inputs.get("base32_secret") + step = inputs.get("step", 30) # Default to 30 seconds + digits = inputs.get("digits", 6) # Default to 6 digits + timestamp_iso = inputs.get("timestamp_iso", "") + algo = inputs.get("algo", "sha1") # Default to sha1 as current implementation only supports this + + # 类型检查 + if base32_secret is not None and not isinstance(base32_secret, str): + raise TypeError("base32_secret must be a string") + if not isinstance(step, (int, str)): + raise TypeError("step must be an integer or string") + if not isinstance(digits, (int, str)): + raise TypeError("digits must be an integer or string") + if not isinstance(timestamp_iso, str): + raise TypeError("timestamp_iso must be a string") + if not isinstance(algo, str): + raise TypeError("algo must be a string") + + # 检查必需参数 + if base32_secret is None: + raise ValueError("base32_secret parameter is required") + + try: + # Convert step and digits to appropriate types + step = int(step) + digits = int(digits) + if digits < 6 or digits > 8: + raise ValueError("Digits must be between 6 and 8") + + # Convert timestamp_iso to integer timestamp + if timestamp_iso: + import datetime + dt = datetime.datetime.fromisoformat(timestamp_iso.replace('Z', '+00:00')) + timestamp = int(dt.timestamp()) + else: + timestamp = int(time.time()) + + # Calculate counter value (T = floor(timestamp / step)) + counter = timestamp // step + + # Decode the base32 secret + # Add padding if necessary (base64 requires padding to be multiple of 8) + base32_secret = base32_secret.upper().replace(' ', '') + if len(base32_secret) % 8 != 0: + base32_secret += '=' * (8 - (len(base32_secret) % 8)) + key = base64.b32decode(base32_secret, casefold=True) + + # Calculate HMAC-SHA1 + counter_bytes = struct.pack('>Q', counter) # Big-endian 8-byte integer + hmac_hash = hmac.new(key, counter_bytes, hashlib.sha1).digest() + + # Dynamic truncation + offset = hmac_hash[-1] & 0xF + code = struct.unpack('>I', hmac_hash[offset:offset+4])[0] & 0x7FFFFFFF + + # Generate the OTP + otp = str(code % (10 ** digits)).zfill(digits) + + # Calculate remaining time until next OTP change + remaining_time = step - (timestamp % step) + + return {"totp": otp, "remaining_time": remaining_time, "time_step": step} + except ValueError as e: + if "invalid literal for int()" in str(e): + raise ValueError("step and digits must be valid integers") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in otp_totp_generate: {str(e)}") + + def unicode_norm(self, inputs): + import unicodedata + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + form = inputs.get("form", "NFC") # Default to NFC + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if form is not None and not isinstance(form, str): + raise TypeError("form must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Normalize form (NFC, NFD, NFKC, NFKD) + form = form.upper().strip() + + if form not in ['NFC', 'NFD', 'NFKC', 'NFKD']: + raise ValueError(f"Invalid normalization form: {form}. Must be one of: NFC, NFD, NFKC, NFKD") + + # Apply Unicode normalization + normalized_text = unicodedata.normalize(form, text) + + return {"text": normalized_text} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in unicode_norm: {str(e)}") + + def text_bidi_sanitize(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Bidi control characters to remove + bidi_controls = [ + '\u200E', # LEFT-TO-RIGHT MARK + '\u200F', # RIGHT-TO-LEFT MARK + '\u202A', # LEFT-TO-RIGHT EMBEDDING + '\u202B', # RIGHT-TO-LEFT EMBEDDING + '\u202C', # POP DIRECTIONAL FORMATTING + '\u202D', # LEFT-TO-RIGHT OVERRIDE + '\u202E', # RIGHT-TO-LEFT OVERRIDE + '\u2066', # LEFT-TO-RIGHT ISOLATE + '\u2067', # RIGHT-TO-LEFT ISOLATE + '\u2068', # FIRST STRONG ISOLATE + '\u2069', # POP DIRECTIONAL ISOLATE + ] + + # Remove all Bidi control characters + sanitized_text = text + for control_char in bidi_controls: + sanitized_text = sanitized_text.replace(control_char, '') + + return {"text": sanitized_text} + except Exception as e: + raise RuntimeError(f"Error in text_bidi_sanitize: {str(e)}") + + def text_xor_hex(self, inputs): + import binascii + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_a = inputs.get("hex_a") + hex_b = inputs.get("hex_b") + + # 类型检查 + if hex_a is not None and not isinstance(hex_a, str): + raise TypeError("hex_a must be a string") + if hex_b is not None and not isinstance(hex_b, str): + raise TypeError("hex_b must be a string") + + # 检查必需参数 + if hex_a is None: + raise ValueError("hex_a parameter is required") + if hex_b is None: + raise ValueError("hex_b parameter is required") + + try: + # Remove any whitespace + hex_a = hex_a.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + hex_b = hex_b.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + + # Validate hex strings + if not (all(c in "0123456789abcdefABCDEF" for c in hex_a) and len(hex_a) % 2 == 0): + raise ValueError("hex_a must be a valid hexadecimal string with even length") + if not (all(c in "0123456789abcdefABCDEF" for c in hex_b) and len(hex_b) % 2 == 0): + raise ValueError("hex_b must be a valid hexadecimal string with even length") + + # Convert hex strings to bytes + bytes_a = binascii.unhexlify(hex_a) + bytes_b = binascii.unhexlify(hex_b) + + # Make the byte arrays the same length by padding the shorter one with zeros + max_len = max(len(bytes_a), len(bytes_b)) + bytes_a = bytes_a.ljust(max_len, b'\x00') + bytes_b = bytes_b.ljust(max_len, b'\x00') + + # Perform XOR operation + result_bytes = bytes(a ^ b for a, b in zip(bytes_a, bytes_b)) + + # Convert result back to hex + result_hex = binascii.hexlify(result_bytes).decode('utf-8') + + return {"hex": result_hex} + except ValueError as e: + if "Non-hexadecimal digit found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in text_xor_hex: {str(e)}") + + def text_rotN(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + n = inputs.get("n", 0) + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + n = int(n) + except ValueError: + raise ValueError("n must be a valid integer") + + result = [] + for char in text: + if char.isupper(): + # Rotate uppercase letters + result_char = chr((ord(char) - ord('A') + n) % 26 + ord('A')) + result.append(result_char) + elif char.islower(): + # Rotate lowercase letters + result_char = chr((ord(char) - ord('a') + n) % 26 + ord('a')) + result.append(result_char) + else: + # Keep non-alphabetic characters unchanged + result.append(char) + + return {"text": ''.join(result)} + + def luhn_check(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数(支持 card_number 和 number 两个参数名) + card_number = inputs.get("number") or inputs.get("card_number") + + # 类型检查 + if card_number is not None and not isinstance(card_number, str): + raise TypeError("number must be a string") + + # 检查必需参数 + if card_number is None: + raise ValueError("number parameter is required") + + try: + # 如果输入是JSON数组或其他非数字字符串,返回该字符串本身(用于数据传递) + # 这种情况发生在DAG设计中类型不匹配时 + if card_number.startswith('[') or card_number.startswith('{'): + # 输入是JSON,直接返回原值(用于传递) + return {"valid": card_number} + + # Remove whitespace from card number + card_number = card_number.replace(" ", "").replace("-", "") + + # Check if card number is all digits + if not card_number.isdigit() or len(card_number) < 13: + return {"valid": "false"} + + # Implement Luhn algorithm + total = 0 + reverse_digits = card_number[::-1] # Reverse the number for easier processing + + for i, digit in enumerate(reverse_digits): + num = int(digit) + if i % 2 == 1: # Every second digit starting from the right (which is first in reversed string) + num *= 2 + if num > 9: + num -= 9 # Equivalent to sum of digits for 2-digit numbers + total += num + + # Check if total is divisible by 10 + is_valid = total % 10 == 0 + return {"valid": "true" if is_valid else "false"} + except Exception as e: + raise RuntimeError(f"Error in luhn_check: {str(e)}") + + def iban_validate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iban = inputs.get("iban") + + # 类型检查 + if iban is not None and not isinstance(iban, str): + raise TypeError("iban must be a string") + + # 检查必需参数 + if iban is None: + raise ValueError("iban parameter is required") + + try: + # Remove whitespace from IBAN + iban = iban.replace(" ", "") + + # Basic length and format check + if not (len(iban) >= 15 and len(iban) <= 34): + return {"valid": "False"} + + if not (iban[:2].isalpha() and iban[2:].isdigit()): + return {"valid": "False"} + + # Move first four characters to the end + rearranged = iban[4:] + iban[:4] + + # Replace letters with numbers (A=10, B=11, ..., Z=35) + numeric_iban = '' + for char in rearranged: + if char.isdigit(): + numeric_iban += char + else: + numeric_iban += str(ord(char.upper()) - ord('A') + 10) + + # Perform modulo 97 check + # Use step-by-step approach for very large numbers + remainder = 0 + for char in numeric_iban: + remainder = (remainder * 10 + int(char)) % 97 + + is_valid = remainder == 1 + return {"valid": "True" if is_valid else "False"} + except Exception as e: + raise RuntimeError(f"Error in iban_validate: {str(e)}") + + def matter_synthesizer(self, inputs): + import hashlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + blueprint = inputs.get("blueprint") + + # 类型检查 + if blueprint is not None and not isinstance(blueprint, str): + raise TypeError("blueprint must be a string") + + try: + # Get blueprint parameter as defined in interface + if blueprint is None: + blueprint = "" + + # Generate a unique item ID based on the blueprint + # This ensures the same blueprint always produces the same item + blueprint_hash = hashlib.sha256(blueprint.encode()).hexdigest()[:16] + + # Create a synthesized item with a deterministic ID based on blueprint + synthesized_item = f"synthesized_item_{blueprint_hash}" + + return {"output_slot": synthesized_item} + except Exception as e: + raise RuntimeError(f"Error in matter_synthesizer: {str(e)}") + + # --- Terminal Implementations --- + def terminal_1(self, inputs): + """ + terminal_1: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 只返回 text_output + - 只输入正确的 slot_b → 只返回 hex_output + - 同时输入正确的 slot_a 和 slot_b → 返回 item_dispenser(物品掉落) + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + # 检查哪些输入被提供了 + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值是否正确(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + expected_a = golden_inputs["slot_a"] + a_valid = str(slot_a) == str(expected_a) + + if has_b and "slot_b" in golden_inputs: + expected_b = golden_inputs["slot_b"] + b_valid = str(slot_b) == str(expected_b) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 item_dispenser + if has_a and has_b: + if a_valid and b_valid: + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 text_output + if has_a and not has_b: + if a_valid: + if "text_output" in golden_outputs: + result["text_output"] = golden_outputs["text_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 hex_output + if has_b and not has_a: + if b_valid: + if "hex_output" in golden_outputs: + result["hex_output"] = golden_outputs["hex_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def terminal_2(self, inputs): + """ + terminal_2: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 text_result + - 同时输入正确的 num1 和 num2 → 返回 hex_result 和 math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + # 检查哪些输入被提供了 + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值是否正确(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + expected_num1 = golden_inputs["num1"] + num1_valid = str(num1) == str(expected_num1) + + if has_num2 and "num2" in golden_inputs: + expected_num2 = golden_inputs["num2"] + num2_valid = str(num2) == str(expected_num2) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 hex_result 和 math_token + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 text_result + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "text_result" in golden_outputs: + result["text_result"] = golden_outputs["text_result"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def logic_terminal(self, inputs): + """ + Logic Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 返回 screen(部分输出) + - 只输入正确的 slot_b → 返回 screen 和 secondary_output + - 同时输入正确的 slot_a 和 slot_b → 返回 screen, secondary_output, item_dispenser + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + a_valid = str(slot_a) == str(golden_inputs["slot_a"]) + + if has_b and "slot_b" in golden_inputs: + b_valid = str(slot_b) == str(golden_inputs["slot_b"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出(包括 item_dispenser) + if has_a and has_b: + if a_valid and b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 screen(部分输出) + if has_a and not has_b: + if a_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 screen 和 secondary_output + if has_b and not has_a: + if b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def math_terminal(self, inputs): + """ + Math Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 result_display + - 同时输入正确的 num1 和 num2 → 返回 result_display, hex_result, math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + num1_valid = str(num1) == str(golden_inputs["num1"]) + + if has_num2 and "num2" in golden_inputs: + num2_valid = str(num2) == str(golden_inputs["num2"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 result_display + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def crypt_terminal(self, inputs): + """ + Encryption Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 plaintext → 返回 status(部分输出) + - 同时输入正确的 plaintext 和 key → 返回 status, encrypted_hex, encryption_chip + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + plaintext = inputs.get("plaintext") + key = inputs.get("key") + + has_plaintext = plaintext is not None and plaintext != "" + has_key = key is not None and key != "" + + # 验证输入值(与 golden values 比较) + plaintext_valid = False + key_valid = False + + if has_plaintext and "plaintext" in golden_inputs: + plaintext_valid = str(plaintext) == str(golden_inputs["plaintext"]) + + if has_key and "key" in golden_inputs: + key_valid = str(key) == str(golden_inputs["key"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_plaintext and has_key: + if plaintext_valid and key_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + if "encrypted_hex" in golden_outputs: + result["encrypted_hex"] = golden_outputs["encrypted_hex"] + if "encryption_chip" in golden_outputs: + result["encryption_chip"] = golden_outputs["encryption_chip"] + return result + else: + incorrect_params = [] + correct_params = [] + if not plaintext_valid: + incorrect_params.append("plaintext") + else: + correct_params.append("plaintext") + if not key_valid: + incorrect_params.append("key") + else: + correct_params.append("key") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 plaintext 且正确 → 返回 status(部分输出) + if has_plaintext and not has_key: + if plaintext_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: plaintext"} + + # 只提供 key 但没有 plaintext + if has_key and not has_plaintext: + return {"error": "plaintext required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + def sequence_terminal(self, inputs): + """ + Sequence Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 sequence → 返回 verification(部分输出) + - 同时输入正确的 sequence 和 checksum → 返回 verification, auth_code, access_card + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + sequence = inputs.get("sequence") + checksum = inputs.get("checksum") + + has_sequence = sequence is not None and sequence != "" + has_checksum = checksum is not None and checksum != "" + + # 验证输入值(与 golden values 比较) + sequence_valid = False + checksum_valid = False + + if has_sequence and "sequence" in golden_inputs: + sequence_valid = str(sequence) == str(golden_inputs["sequence"]) + + if has_checksum and "checksum" in golden_inputs: + checksum_valid = str(checksum) == str(golden_inputs["checksum"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_sequence and has_checksum: + if sequence_valid and checksum_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + if "auth_code" in golden_outputs: + result["auth_code"] = golden_outputs["auth_code"] + if "access_card" in golden_outputs: + result["access_card"] = golden_outputs["access_card"] + return result + else: + incorrect_params = [] + correct_params = [] + if not sequence_valid: + incorrect_params.append("sequence") + else: + correct_params.append("sequence") + if not checksum_valid: + incorrect_params.append("checksum") + else: + correct_params.append("checksum") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 sequence 且正确 → 返回 verification(部分输出) + if has_sequence and not has_checksum: + if sequence_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: sequence"} + + # 只提供 checksum 但没有 sequence + if has_checksum and not has_sequence: + return {"error": "sequence required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + # --- Additional File Tools --- + + def zip_unzip_file(self, inputs): + """ZIP 解压文件工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def zip_unzip_item(self, inputs): + """ZIP 解压道具工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def code_py_exec(self, inputs): + """Python 代码执行工具 + + 这是一个真实执行的工具,在 DAG 生成阶段和运行时评测阶段都会执行代码。 + 输入: code (Python 代码字符串) + 输出: stdout (标准输出,包含执行结果和错误信息) + + 特殊行为: + - 如果代码定义了 main() 函数,会自动调用它 + - 如果执行出错,错误信息会包含在 stdout 中 + """ + code = inputs.get("code", "") + + if not code: + return {"stdout": "Error: No code provided"} + + try: + # 创建一个受限的执行环境 + import io + import sys + + # 捕获标准输出和标准错误 + old_stdout = sys.stdout + old_stderr = sys.stderr + sys.stdout = io.StringIO() + sys.stderr = io.StringIO() + + # 执行代码 + exec_globals = {"__builtins__": __builtins__} + exec_locals = {} + exec(code, exec_globals, exec_locals) + + # 如果定义了 main() 函数,自动调用它 + if 'main' in exec_locals and callable(exec_locals['main']): + exec_locals['main']() + + # 获取输出 + stdout_value = sys.stdout.getvalue() + stderr_value = sys.stderr.getvalue() + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 合并 stdout 和 stderr + output = stdout_value + if stderr_value: + output += ("\n" if output else "") + f"[stderr] {stderr_value}" + + # 如果没有任何输出,尝试返回 result 变量的值 + if not output: + result = exec_locals.get("_result") or exec_locals.get("result") + if result is not None: + output = str(result) + + return {"stdout": output if output else "(no output)"} + + except Exception as e: + # 恢复标准输出和错误输出 + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 返回错误信息 + return {"stdout": f"Error: {type(e).__name__}: {str(e)}"} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-6ae6d120/environment/puzzle/worker.Dockerfile b/tasks/agentescape-25-skeleton-6ae6d120/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-25-skeleton-6ae6d120/environment/puzzle/worker.Dockerfile @@ -0,0 +1,8 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends libseccomp2 && rm -rf /var/lib/apt/lists/* +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY worker.py child.py /app/ +COPY upstream/simulator.py /app/simulator.py +CMD ["uvicorn", "worker:app", "--host", "0.0.0.0", "--port", "8001", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-25-skeleton-6ae6d120/environment/puzzle/worker.py b/tasks/agentescape-25-skeleton-6ae6d120/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-25-skeleton-6ae6d120/environment/puzzle/worker.py @@ -0,0 +1,73 @@ +"""Stateless Python tool worker. Never receives a scenario or reference values.""" + +import json +import os +import signal +import subprocess +import sys +import tempfile +import threading + +from fastapi import FastAPI +from pydantic import BaseModel, ConfigDict + +app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) +lock = threading.Lock() + + +class Execution(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + code: str + + +@app.get("/health") +def health(): + return {"ok": True} + + +@app.post("/execute") +def execute(request: Execution): + if len(request.code.encode()) > 65536: + return {"stdout": "Error: code exceeds 64 KiB limit"} + with lock, tempfile.TemporaryDirectory(prefix="escape-code-") as directory: + os.chown(directory, 65534, 65534) + with tempfile.TemporaryFile() as output: + process = subprocess.Popen( + [sys.executable, "-I", "/app/child.py"], + stdin=subprocess.PIPE, + stdout=output, + stderr=subprocess.DEVNULL, + cwd=directory, + user=65534, + group=65534, + extra_groups=[], + start_new_session=True, + env={"PATH": "/usr/local/bin:/usr/bin:/bin"}, + ) + try: + process.communicate( + json.dumps({"code": request.code}).encode(), timeout=5 + ) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + return {"stdout": "Error: Python execution timed out"} + finally: + # Also remove children still in the process group after normal exit. + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + output.seek(0) + value = output.read(65537) + if len(value) > 65536 or process.returncode != 0: + return { + "stdout": "Error: Python execution exceeded a resource limit or failed" + } + try: + result = json.loads(value) + if not isinstance(result.get("stdout"), str): + raise ValueError("Invalid worker response") + return result + except (ValueError, AttributeError): + return {"stdout": "Error: Python execution returned invalid output"} diff --git a/tasks/agentescape-25-skeleton-6ae6d120/instruction.md b/tasks/agentescape-25-skeleton-6ae6d120/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-25-skeleton-6ae6d120/instruction.md @@ -0,0 +1,18 @@ +# Escape the room + +Discover the victory string and submit it with `escape submit-answer`. +Start with `escape observe`. This returns the room, available information, visible entities, and victory node ID. + +Use these commands (JSON responses): + +```sh +escape investigate NODE_ID +escape tool-call NODE_ID --arguments-json '{"parameter": "value"}' +escape use-item NODE_ID --arguments-json '{"parameter": "value"}' +escape submit-answer 'exact victory string' +escape state +``` + +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. + +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. diff --git a/tasks/agentescape-25-skeleton-6ae6d120/solution/oracle.py b/tasks/agentescape-25-skeleton-6ae6d120/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-25-skeleton-6ae6d120/solution/oracle.py @@ -0,0 +1,133 @@ +"""Reference solver: use trusted inputs, but obtain the answer through public actions.""" + +import json +import urllib.request +from pathlib import Path + + +def http_action(base_url, payload): + request = urllib.request.Request( + base_url + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(request, timeout=30) as response: + return json.load(response) + + +def solve(scenario, act, observe): + nodes = {node["id"]: node for node in scenario["nodes"]} + visible = {entity["id"] for entity in observe["available_entities"]} + solved = set() + seen_outputs = {} + action_count = 0 + + def call(payload): + nonlocal action_count + action_count += 1 + response = act(payload) + visible.update(entity["id"] for entity in response.get("newly_revealed", [])) + if ( + response.get("episode", {}).get("termination_reason") + == "infrastructure_error" + ): + raise RuntimeError("Infrastructure failure") + return response + + for _round in range(len(nodes) + 2): + progress = False + for node_id, node in nodes.items(): + if node_id not in visible or node_id in solved: + continue + # Preserve graph order for data inputs; trigger/drop edges express visibility. + predecessors = [ + edge["source_id"] + for edge in scenario["edges"] + if edge["target_id"] == node_id + and edge["connection_type"] not in ("Item", "Hidden_Item") + ] + if any(pred not in solved for pred in predecessors): + continue + info = call({"action": "investigate", "node_id": node_id}) + if not info.get("ok"): + raise RuntimeError(f"Investigation failed: {node_id}: {info}") + inputs = { + port["name"]: port["value"] + for port in node.get("inputs", []) + if "value" in port + } + if node["type"] == "Tool": + result = call( + {"action": "tool_call", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok") or result.get("output_values", {}).get("error"): + raise RuntimeError(f"Tool failed: {node_id}: {result}") + output = result.get("output_values", {}) + if node.get("template_id") in ("terminal_1", "terminal_2"): + slots = { + port["name"]: inputs[port["name"]] + for port in node["inputs"] + if port["type"] not in ("Item", "Hidden_Item") + and port["name"] in inputs + } + triggers = { + key: value for key, value in inputs.items() if key not in slots + } + for key, value in slots.items(): + partial = call( + { + "action": "tool_call", + "node_id": node_id, + "arguments": {**triggers, key: value}, + } + ) + if partial.get("ok"): + output.update(partial.get("output_values", {})) + # HIDDEN_ITEM tool drops only occur on subsequent investigation. + call({"action": "investigate", "node_id": node_id}) + elif info.get("required_inputs"): + result = call( + {"action": "use_item", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok"): + raise RuntimeError(f"Item failed: {node_id}: {result}") + output = result.get("content") + else: + output = info.get("content") + seen_outputs[node_id] = output + solved.add(node_id) + progress = True + win_id = scenario["metadata"]["win_node_id"] + if win_id in solved and (len(solved) == len(nodes) or not progress): + outputs = seen_outputs[win_id] + if not outputs: + raise RuntimeError(f"Victory node returned no output: {win_id}") + # Upstream grades its first stored output port, independent of response order. + victory_port = next( + port["name"] for port in nodes[win_id]["outputs"] if "value" in port + ) + answer = outputs[victory_port] if isinstance(outputs, dict) else outputs + result = call({"action": "submit_answer", "answer": answer}) + if not result.get("is_win"): + raise RuntimeError(f"Victory submission failed: {result}") + return {"won": True, "actions": action_count, "visited_nodes": len(solved)} + if not progress: + raise RuntimeError(f"No progress: visible={visible}, solved={solved}") + raise RuntimeError("Reference solver exceeded graph traversal limit") + + +if __name__ == "__main__": + import os + + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000") + with urllib.request.urlopen(base + "/observation", timeout=20) as response: + observation = json.load(response) + print( + json.dumps( + solve( + json.loads(Path("/solution/scenario.json").read_text()), + lambda payload: http_action(base, payload), + observation, + ) + ) + ) diff --git a/tasks/agentescape-25-skeleton-6ae6d120/solution/scenario.json b/tasks/agentescape-25-skeleton-6ae6d120/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..27c8e29cb9f77da63260a8670d988e099d2da977 --- /dev/null +++ b/tasks/agentescape-25-skeleton-6ae6d120/solution/scenario.json @@ -0,0 +1,1433 @@ +{ + "metadata": { + "total_nodes": 25, + "total_edges": 26, + "win_node_id": "hex_decode", + "win_condition": { + "type": "tool_output", + "node_id": "hex_decode", + "output_port": "text", + "output_type": "Text_Generic", + "description": "Execute Hex to Text Decoder and get the output from port 'text'" + }, + "source_init": { + "source_nodes": [ + "terminal_2", + "graph_shortest_path", + "calc_bigmul", + "zip_unzip_file", + "csv_query", + "zip_unzip_file_be1f", + "regex_search", + "container_4_4dab", + "luhn_check", + "num_base_convert", + "hash_sha256", + "calc_inv_mod", + "checksum_crc32_3498" + ], + "by_node": { + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": {}, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + } + } + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "src": { + "type": "Text_Generic", + "description": "Source node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "calc_bigmul": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First large integer" + }, + "b": { + "type": "Big_Int", + "description": "Second large integer" + } + }, + "init_outputs": {} + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + }, + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "csv_query": { + "node_name": "CSV Query", + "node_type": "Tool", + "template_id": "csv_query", + "init_inputs": { + "select": { + "type": "Text_Generic", + "description": "Columns to select" + } + }, + "init_outputs": { + "rows": { + "type": "Text_Generic", + "description": "Result rows" + } + } + }, + "zip_unzip_file_be1f": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + }, + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "regex_search": { + "node_name": "Regex Search", + "node_type": "Tool", + "template_id": "regex_search", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "File ID (optional)" + }, + "text": { + "type": "Text_Generic", + "description": "Text (optional)" + } + }, + "init_outputs": { + "matches": { + "type": "Text_Generic", + "description": "Found matches (List)" + } + } + }, + "container_4_4dab": { + "node_name": "", + "node_type": "Item", + "template_id": "container_4", + "init_inputs": { + "fingerprint_input": { + "type": "Text_Generic", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + }, + "luhn_check": { + "node_name": "Luhn Checker", + "node_type": "Tool", + "template_id": "luhn_check", + "init_inputs": { + "number": { + "type": "Text_Generic", + "description": "Number string" + } + }, + "init_outputs": {} + }, + "num_base_convert": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "to_base": { + "type": "Big_Int", + "description": "To base" + } + }, + "init_outputs": {} + }, + "hash_sha256": { + "node_name": "SHA-256 Hasher", + "node_type": "Tool", + "template_id": "hash_sha256", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text to hash" + } + }, + "init_outputs": {} + }, + "calc_inv_mod": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "Integer a" + }, + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "checksum_crc32_3498": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Execution of terminal module generated partial text result successfully.", + "hex_result": "2b4f6a8c0e1d3b5f7a9c2e4f6a8c0e1d" + } + }, + "graph_shortest_path": { + "init_inputs": { + "src": "Node_A10" + }, + "init_outputs": { + "path": "[\"Node_A10\", \"Node_B2\", \"Node_C5\", \"Node_D4\", \"Node_E9\", \"Node_F1\"]", + "cost": "784920" + } + }, + "calc_bigmul": { + "init_inputs": { + "a": "839475829104857261938", + "b": "104857293847562819384" + }, + "init_outputs": {} + }, + "zip_unzip_file": { + "init_inputs": { + "zip_id": "archive_main_73.zip", + "password": "Str0ngP@ssw0rd!" + }, + "init_outputs": { + "files": "extracted_data_73.csv" + } + }, + "csv_query": { + "init_inputs": { + "select": "id, name, age, email, status" + }, + "init_outputs": { + "rows": "[{\"id\": 1, \"name\": \"Alice\"}, {\"id\": 2, \"name\": \"Bob\"}, {\"id\": 3, \"name\": \"Charlie\"}, {\"id\": 4, \"name\": \"David\"}]" + } + }, + "zip_unzip_file_be1f": { + "init_inputs": { + "zip_id": "backup_logs_2023.zip", + "password": "B@ckup2023#secure" + }, + "init_outputs": { + "files": "logs_2023_parsed.json" + } + }, + "regex_search": { + "init_inputs": { + "file_id": "document_text_99.txt", + "text": "The quick brown fox jumps over the lazy dog 123456." + }, + "init_outputs": { + "matches": "[\"match_one\", \"match_two\", \"match_three\", \"match_four\"]" + } + }, + "container_4_4dab": { + "init_inputs": { + "fingerprint_input": "hash_fingerprint_8f2b" + }, + "init_outputs": {} + }, + "luhn_check": { + "init_inputs": { + "number": "79927398713" + }, + "init_outputs": {} + }, + "num_base_convert": { + "init_inputs": { + "to_base": "10" + }, + "init_outputs": {} + }, + "hash_sha256": { + "init_inputs": { + "text": "String to be hashed using SHA-256 algorithm." + }, + "init_outputs": {} + }, + "calc_inv_mod": { + "init_inputs": { + "a": "58291048573928174829", + "mod": "999983" + }, + "init_outputs": {} + }, + "checksum_crc32_3498": { + "init_inputs": { + "hex": "112233445566778899aabbccddeeff00" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You awaken in the dimly lit basement of what appears to be an abandoned intelligence agency outpost. Dust dances in the single beam of moonlight cutting through a high window. Scattered across the desks and workbenches are various obsolete yet highly modified mechanical and digital devices. A heavy steel door blocks your only exit, secured by a complex lock that requires a specific deciphered text. You must interact with the strange assortment of tools, scanners, and terminals to trace the final secret. Be careful—these machines are ingeniously interconnected, and determining the correct sequence of operations is your only chance to escape.", + "narrative_style": "mystery" + }, + "nodes": [ + { + "id": "hex_decode", + "name": "Hex to Text Decoder", + "description": "Decode hex to UTF-8 text.", + "type": "Tool", + "template_id": "hex_decode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex string", + "value": "0062a113" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decoded text", + "value": "\u0000b\u0013" + } + ], + "narrative": "This is the Final Deciphering Terminal. It requires input from the Mainframe Validation Module. Use the validation result here to reveal the ultimate secret." + }, + { + "id": "checksum_crc32", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "bb39b750" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "0062a113" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 6463763 + } + ], + "narrative": "This is the Mainframe Validation Module. It requires input from the Network Checksum Verifier. Once you have the verifier's result, enter it here." + }, + { + "id": "checksum_crc32_0015", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "789c0dc9d10d80200c04d0556e02b770108287212960da6b82dbebfb7de7664df535b11a441f7d16c358571a7173d28b78e129aefe87b80567a40991b532a2a5d97b7ceddf1bbf" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "bb39b750" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3141121872 + } + ], + "narrative": "This is the Network Checksum Verifier. It requires input from the Data Compression Unit. Bring the compressed data here for verification." + }, + { + "id": "zlib_deflate", + "name": "Zlib Deflate", + "description": "Deflate text to zlib bytes (hex).", + "type": "Tool", + "template_id": "zlib_deflate", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Text to compress", + "value": "Execution of terminal module generated partial text result successfully." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Compressed hex", + "value": "789c0dc9d10d80200c04d0556e02b770108287212960da6b82dbebfb7de7664df535b11a441f7d16c358571a7173d28b78e129aefe87b80567a40991b532a2a5d97b7ceddf1bbf" + } + ], + "narrative": "This is the Data Compression Unit. It requires input from the Main Computer Terminal to shrink the raw data." + }, + { + "id": "terminal_2", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this terminal" + }, + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "88025163690374446159044399731057871806192" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "784920" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Execution of terminal module generated partial text result successfully." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "2b4f6a8c0e1d3b5f7a9c2e4f6a8c0e1d" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "Execution of terminal module generated partial text result successfully.", + "hex_result": "2b4f6a8c0e1d3b5f7a9c2e4f6a8c0e1d" + } + }, + "narrative": "This is the Main Computer Terminal. It requires inputs from both the Routing Analyzer and the Old Adding Machine to boot up its core systems." + }, + { + "id": "container_3", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_3", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Big_Int", + "description": "Fingerprint Hash", + "value": 2292003582 + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is a High-Security Evidence Locker. It requires input from the Data Hash Verifier to unlock its electronic seal." + }, + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "extracted_data_73.csv" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Node_A10" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "[{\"wr\": 1, \"boas\": \"Ozwqs\"}, {\"wr\": 2, \"boas\": \"Pcp\"}, {\"wr\": 3, \"boas\": \"Qvofzws\"}, {\"wr\": 4, \"boas\": \"Rojwr\"}]" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Node_A10\", \"Node_B2\", \"Node_C5\", \"Node_D4\", \"Node_E9\", \"Node_F1\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "784920" + } + ], + "init": { + "inputs": { + "src": "Node_A10" + }, + "outputs": { + "path": "[\"Node_A10\", \"Node_B2\", \"Node_C5\", \"Node_D4\", \"Node_E9\", \"Node_F1\"]", + "cost": "784920" + } + }, + "narrative": "This is the Routing Analyzer. It requires inputs from both the Cipher Wheel and the Digital Forensic Tool to map out the correct pathways." + }, + { + "id": "text_rotN", + "name": "ROT-N Cipher", + "description": "Caesar shift by N.", + "type": "Tool", + "template_id": "text_rotN", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "[{\"id\": 1, \"name\": \"Alice\"}, {\"id\": 2, \"name\": \"Bob\"}, {\"id\": 3, \"name\": \"Charlie\"}, {\"id\": 4, \"name\": \"David\"}]" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Shift N", + "value": "2416908508" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Rotated text", + "value": "[{\"wr\": 1, \"boas\": \"Ozwqs\"}, {\"wr\": 2, \"boas\": \"Pcp\"}, {\"wr\": 3, \"boas\": \"Qvofzws\"}, {\"wr\": 4, \"boas\": \"Rojwr\"}]" + } + ], + "narrative": "This is a Cipher Wheel. It requires inputs from both the Database Inquiry Console and the Base Conversion Mechanism to align its cryptographic gears." + }, + { + "id": "container_4", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_4", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Text_Generic", + "description": "Fingerprint Hash", + "value": "false" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is a Biometric Safe. It requires input from the ID Card Scanner to verify authorization." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A Dusty Keybox resting on a forgotten shelf. It seems to have been left untouched for years." + }, + { + "id": "calc_bigmul", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "839475829104857261938" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "104857293847562819384" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "88025163690374446159044399731057871806192" + } + ], + "init": { + "inputs": { + "a": "839475829104857261938", + "b": "104857293847562819384" + }, + "outputs": {} + }, + "narrative": "An Old Adding Machine with heavy mechanical keys. It still seems functional despite its age." + }, + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "archive_main_73.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Str0ngP@ssw0rd!" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_data_73.csv" + } + ], + "init": { + "inputs": { + "zip_id": "archive_main_73.zip", + "password": "Str0ngP@ssw0rd!" + }, + "outputs": { + "files": "extracted_data_73.csv" + } + }, + "narrative": "A Digital Forensic Tool used for analyzing complex digital archives." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "An Abandoned Briefcase left carelessly under a desk." + }, + { + "id": "csv_query", + "name": "CSV Query", + "description": "Query CSV: select columns and simple WHERE.", + "type": "Tool", + "template_id": "csv_query", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "CSV file ID", + "value": "logs_2023_parsed.json" + }, + { + "name": "select", + "type": "Text_Generic", + "description": "Columns to select", + "value": "id, name, age, email, status" + }, + { + "name": "where", + "type": "Text_Generic", + "description": "Where clause", + "value": "[\"match_one\", \"match_two\", \"match_three\", \"match_four\"]" + } + ], + "outputs": [ + { + "name": "rows", + "type": "Text_Generic", + "description": "Result rows", + "value": "[{\"id\": 1, \"name\": \"Alice\"}, {\"id\": 2, \"name\": \"Bob\"}, {\"id\": 3, \"name\": \"Charlie\"}, {\"id\": 4, \"name\": \"David\"}]" + } + ], + "init": { + "inputs": { + "select": "id, name, age, email, status" + }, + "outputs": { + "rows": "[{\"id\": 1, \"name\": \"Alice\"}, {\"id\": 2, \"name\": \"Bob\"}, {\"id\": 3, \"name\": \"Charlie\"}, {\"id\": 4, \"name\": \"David\"}]" + } + }, + "narrative": "This is the Database Inquiry Console. It requires inputs from both the Encrypted Archive Extractor and the Pattern Scanner to run a successful query." + }, + { + "id": "zip_unzip_file_be1f", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "backup_logs_2023.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "B@ckup2023#secure" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "logs_2023_parsed.json" + } + ], + "init": { + "inputs": { + "zip_id": "backup_logs_2023.zip", + "password": "B@ckup2023#secure" + }, + "outputs": { + "files": "logs_2023_parsed.json" + } + }, + "narrative": "An Encrypted Archive Extractor designed to bypass file restrictions." + }, + { + "id": "regex_search", + "name": "Regex Search", + "description": "Search regex in either raw text or a file.", + "type": "Tool", + "template_id": "regex_search", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "pattern", + "type": "Text_Generic", + "description": "Regex pattern", + "value": "false" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "File ID (optional)", + "value": "document_text_99.txt" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text (optional)", + "value": "The quick brown fox jumps over the lazy dog 123456." + } + ], + "outputs": [ + { + "name": "matches", + "type": "Text_Generic", + "description": "Found matches (List)", + "value": "[\"match_one\", \"match_two\", \"match_three\", \"match_four\"]" + } + ], + "init": { + "inputs": { + "file_id": "document_text_99.txt", + "text": "The quick brown fox jumps over the lazy dog 123456." + }, + "outputs": { + "matches": "[\"match_one\", \"match_two\", \"match_three\", \"match_four\"]" + } + }, + "narrative": "This is the Pattern Scanner. It requires input from the Secondary Credential Scanner to filter through the noise." + }, + { + "id": "item_16_0c5b", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A Concealed Pocketwatch hidden away from prying eyes." + }, + { + "id": "container_4_4dab", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_4", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Text_Generic", + "description": "Fingerprint Hash", + "value": "hash_fingerprint_8f2b" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "hash_fingerprint_8f2b" + }, + "outputs": {} + }, + "narrative": "An Initial Lockbox bolted to the heavy oak desk." + }, + { + "id": "checksum_crc32_609c", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "7708352a6e1dcb790460322cb7e410ddd06a0d58112982f48f131f307f2b2395" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "889d32fe" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 2292003582 + } + ], + "narrative": "This is the Data Hash Verifier. It requires input from the Cryptographic Hashing Terminal to function properly." + }, + { + "id": "luhn_check", + "name": "Luhn Checker", + "description": "Luhn validity of number string.", + "type": "Tool", + "template_id": "luhn_check", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "number", + "type": "Text_Generic", + "description": "Number string", + "value": "79927398713" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "false" + } + ], + "init": { + "inputs": { + "number": "79927398713" + }, + "outputs": {} + }, + "narrative": "An ID Card Scanner mounted near the main entrance." + }, + { + "id": "num_base_convert", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": 2416908508 + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "619044" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "10" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "2416908508" + } + ], + "init": { + "inputs": { + "to_base": "10" + }, + "outputs": {} + }, + "narrative": "This is the Base Conversion Mechanism. It requires inputs from both the Mathematical Computation Module and the Localized Integrity Checker to align the numeric formats." + }, + { + "id": "luhn_check_d1a4", + "name": "Luhn Checker", + "description": "Luhn validity of number string.", + "type": "Tool", + "template_id": "luhn_check", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "number", + "type": "Text_Generic", + "description": "Number string", + "value": "false" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "false" + } + ], + "narrative": "This is a Secondary Credential Scanner. It requires input from the ID Card Scanner to proceed with the next level of clearance." + }, + { + "id": "hash_sha256", + "name": "SHA-256 Hasher", + "description": "SHA-256 over UTF-8 text; returns hex.", + "type": "Tool", + "template_id": "hash_sha256", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text to hash", + "value": "String to be hashed using SHA-256 algorithm." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "SHA-256 Hex digest", + "value": "7708352a6e1dcb790460322cb7e410ddd06a0d58112982f48f131f307f2b2395" + } + ], + "init": { + "inputs": { + "text": "String to be hashed using SHA-256 algorithm." + }, + "outputs": {} + }, + "narrative": "A Cryptographic Hashing Terminal with a blinking green cursor." + }, + { + "id": "calc_inv_mod", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "58291048573928174829" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "999983" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "619044" + } + ], + "init": { + "inputs": { + "a": "58291048573928174829", + "mod": "999983" + }, + "outputs": {} + }, + "narrative": "A Mathematical Computation Module, perfect for solving complex numerical equations." + }, + { + "id": "checksum_crc32_3498", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "112233445566778899aabbccddeeff00" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "900f18dc" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 2416908508 + } + ], + "init": { + "inputs": { + "hex": "112233445566778899aabbccddeeff00" + }, + "outputs": {} + }, + "narrative": "A Localized Integrity Checker, meant for verifying small fragments of data." + } + ], + "edges": [ + { + "source_id": "checksum_crc32", + "target_id": "hex_decode", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "checksum_crc32_0015", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "zlib_deflate", + "target_id": "checksum_crc32_0015", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "terminal_2", + "target_id": "zlib_deflate", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "text" + }, + { + "source_id": "container_3", + "target_id": "terminal_2", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "terminal_2", + "target_id": "checksum_crc32", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "trigger_item" + }, + { + "source_id": "graph_shortest_path", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "num2" + }, + { + "source_id": "text_rotN", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "dst" + }, + { + "source_id": "container_4", + "target_id": "graph_shortest_path", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "item_16", + "target_id": "container_3", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "calc_bigmul", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "num1" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "item_8", + "target_id": "container_4", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "csv_query", + "target_id": "text_rotN", + "connection_type": "Text_Generic", + "source_port": "rows", + "target_port": "text" + }, + { + "source_id": "zip_unzip_file_be1f", + "target_id": "csv_query", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "regex_search", + "target_id": "csv_query", + "connection_type": "Text_Generic", + "source_port": "matches", + "target_port": "where" + }, + { + "source_id": "item_16_0c5b", + "target_id": "text_rotN", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "container_4_4dab", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "checksum_crc32_609c", + "target_id": "container_3", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "fingerprint_input" + }, + { + "source_id": "luhn_check", + "target_id": "container_4", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "fingerprint_input" + }, + { + "source_id": "num_base_convert", + "target_id": "text_rotN", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "n" + }, + { + "source_id": "luhn_check_d1a4", + "target_id": "regex_search", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "pattern" + }, + { + "source_id": "luhn_check", + "target_id": "luhn_check_d1a4", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "number" + }, + { + "source_id": "hash_sha256", + "target_id": "checksum_crc32_609c", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "calc_inv_mod", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "from_base" + }, + { + "source_id": "checksum_crc32_3498", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "s" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-6ae6d120/solution/solve.sh b/tasks/agentescape-25-skeleton-6ae6d120/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-25-skeleton-6ae6d120/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-25-skeleton-6ae6d120/task.toml b/tasks/agentescape-25-skeleton-6ae6d120/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..43e8cfa53cae215adfbe2d5f8b1017f7a11b5da8 --- /dev/null +++ b/tasks/agentescape-25-skeleton-6ae6d120/task.toml @@ -0,0 +1,38 @@ +schema_version = "1.4" +source = "https://github.com/AGI-Eval-Official/Repo-of-AgentEscapeBench" + +[[artifacts]] +source = "/evidence/final.json" +service = "puzzle" + +[[artifacts]] +source = "/evidence/trace.jsonl" +service = "puzzle" + +[task] +name = "edbeeching/agentescape-25-skeleton-6ae6d120" +version = "0.1.0" + +[metadata] +difficulty = 25 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "ca989e0ef777c5cbbf551c98b279fe776dbf1f4490886ee3eaa732bbbd8e90bc" +protocol = "harbor-cli-action-budget-v1" +max_actions = 500 + +[agent] +timeout_sec = 1200 + +[environment] +build_timeout_sec = 900 +cpus = 1 +memory_mb = 1024 + +[verifier] +environment_mode = "separate" +timeout_sec = 60 + +[[verifier.collect]] +service = "puzzle" +command = "python -I /app/export.py" +timeout_sec = 15 diff --git a/tasks/agentescape-25-skeleton-6ae6d120/tests/Dockerfile b/tasks/agentescape-25-skeleton-6ae6d120/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-25-skeleton-6ae6d120/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-25-skeleton-6ae6d120/tests/expected.json b/tasks/agentescape-25-skeleton-6ae6d120/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..17c5a9541fdb799ad30332dce247c6c7ff18814f --- /dev/null +++ b/tasks/agentescape-25-skeleton-6ae6d120/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "ca989e0ef777c5cbbf551c98b279fe776dbf1f4490886ee3eaa732bbbd8e90bc", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-6ae6d120/tests/grade.py b/tasks/agentescape-25-skeleton-6ae6d120/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-25-skeleton-6ae6d120/tests/grade.py @@ -0,0 +1,21 @@ +"""Grade only Harbor-collected sidecar evidence in a fresh verifier container.""" + +import json +from pathlib import Path + +expected = json.loads(Path("/tests/expected.json").read_text()) +state = json.loads(Path("/evidence/final.json").read_text()) +assert state["collected_from_live_service"] is True, "Missing trusted service export" +assert state["scenario_sha256"] == expected["scenario_sha256"], ( + "Wrong scenario evidence" +) +assert state["max_actions"] == expected["max_actions"], "Wrong budget" +assert type(state["won"]) is bool +assert 0 <= state["action_count"] <= state["max_actions"] +assert state["termination_reason"] != "infrastructure_error", ( + "Infrastructure failure is not a puzzle failure" +) +assert not state["won"] or state["termination_reason"] == "success" +Path("/logs/verifier").mkdir(parents=True, exist_ok=True) +Path("/logs/verifier/state.json").write_text(json.dumps(state, indent=2)) +Path("/logs/verifier/reward.txt").write_text("1.0\n" if state["won"] else "0.0\n") diff --git a/tasks/agentescape-25-skeleton-6ae6d120/tests/test.sh b/tasks/agentescape-25-skeleton-6ae6d120/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-25-skeleton-6ae6d120/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-25-skeleton-7499421d/environment/Dockerfile b/tasks/agentescape-25-skeleton-7499421d/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-25-skeleton-7499421d/environment/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-25-skeleton-7499421d/environment/agent/Dockerfile b/tasks/agentescape-25-skeleton-7499421d/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-25-skeleton-7499421d/environment/agent/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-25-skeleton-7499421d/environment/agent/cli.py b/tasks/agentescape-25-skeleton-7499421d/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-25-skeleton-7499421d/environment/agent/cli.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Public agent client; depends only on the Python standard library.""" + +import argparse +import json +import os +import sys +import urllib.error +import urllib.request + + +def main(): + parser = argparse.ArgumentParser(description="Interact with the escape room") + parser.add_argument( + "action", + choices=[ + "observe", + "state", + "investigate", + "tool-call", + "use-item", + "submit-answer", + ], + ) + parser.add_argument("value", nargs="?") + parser.add_argument("--arguments-json", default="{}") + args = parser.parse_args() + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000").rstrip("/") + if args.action in ("observe", "state"): + request = urllib.request.Request( + base + ("/observation" if args.action == "observe" else "/state") + ) + else: + if args.value is None: + parser.error("node ID or answer is required") + payload = {"action": args.action.replace("-", "_")} + if args.action == "submit-answer": + payload["answer"] = args.value + else: + payload["node_id"] = args.value + if args.action in ("tool-call", "use-item"): + payload["arguments"] = json.loads(args.arguments_json) + request = urllib.request.Request( + base + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=30) as response: + print(json.dumps(json.load(response), ensure_ascii=False)) + except (urllib.error.URLError, ValueError) as exc: + print(json.dumps({"ok": False, "error": str(exc)})) + sys.exit(2) + + +if __name__ == "__main__": + main() diff --git a/tasks/agentescape-25-skeleton-7499421d/environment/docker-compose.yaml b/tasks/agentescape-25-skeleton-7499421d/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8079a6361fa208592a5d898c49617112a43ff966 --- /dev/null +++ b/tasks/agentescape-25-skeleton-7499421d/environment/docker-compose.yaml @@ -0,0 +1,50 @@ +services: + main: + image: agentescapebench-agent:aab05a0a9ddb + build: + context: ./agent + networks: [default, puzzle] + security_opt: [no-new-privileges:true] + depends_on: + puzzle: + condition: service_healthy + puzzle: + image: agentescapebench-puzzle:agentescape-25-skeleton-7499421d-aab05a0a9ddb + build: + context: ./puzzle + networks: [puzzle, execution] + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 512m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"] + interval: 1s + timeout: 3s + retries: 30 + depends_on: + worker: + condition: service_healthy + worker: + image: agentescapebench-worker:aab05a0a9ddb + build: + context: ./puzzle + dockerfile: worker.Dockerfile + networks: [execution] + read_only: true + tmpfs: ["/tmp:size=64m,mode=1777"] + cap_drop: [ALL] + cap_add: [SETUID, SETGID, KILL, CHOWN, DAC_OVERRIDE] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 384m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8001/health')"] + interval: 1s + timeout: 3s + retries: 30 +networks: + puzzle: + internal: true + execution: + internal: true diff --git a/tasks/agentescape-25-skeleton-7499421d/environment/puzzle/Dockerfile b/tasks/agentescape-25-skeleton-7499421d/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-25-skeleton-7499421d/environment/puzzle/Dockerfile @@ -0,0 +1,9 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY upstream /app/upstream +COPY service.py export.py /app/ +COPY scenario.json /private/scenario.json +ENV SCENARIO_PATH=/private/scenario.json EVIDENCE_DIR=/evidence WORKER_URL=http://worker:8001 MAX_ACTIONS=500 +CMD ["uvicorn", "service:create_app", "--factory", "--host", "0.0.0.0", "--port", "8000", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-25-skeleton-7499421d/environment/puzzle/child.py b/tasks/agentescape-25-skeleton-7499421d/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-25-skeleton-7499421d/environment/puzzle/child.py @@ -0,0 +1,59 @@ +"""Run the original Python tool after reducing privileges and blocking networking.""" + +import ctypes +import errno +import json +import resource +import sys + +resource.setrlimit(resource.RLIMIT_CPU, (3, 3)) +resource.setrlimit(resource.RLIMIT_AS, (256 * 1024 * 1024, 256 * 1024 * 1024)) +resource.setrlimit(resource.RLIMIT_FSIZE, (65536, 65536)) +resource.setrlimit(resource.RLIMIT_NOFILE, (32, 32)) +resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + +# Filters survive fork/exec. Fail closed if seccomp cannot be loaded. +lib = ctypes.CDLL("libseccomp.so.2", use_errno=True) +lib.seccomp_init.argtypes = [ctypes.c_uint32] +lib.seccomp_init.restype = ctypes.c_void_p +lib.seccomp_rule_add.argtypes = [ + ctypes.c_void_p, + ctypes.c_uint32, + ctypes.c_int, + ctypes.c_uint, +] +lib.seccomp_syscall_resolve_name.argtypes = [ctypes.c_char_p] +lib.seccomp_load.argtypes = [ctypes.c_void_p] +lib.seccomp_release.argtypes = [ctypes.c_void_p] +ctx = lib.seccomp_init(0x7FFF0000) # SCMP_ACT_ALLOW +if not ctx: + raise RuntimeError("Cannot initialize execution isolation") +try: + for name in ( + "socket", + "socketpair", + "connect", + "ptrace", + "process_vm_readv", + "process_vm_writev", + "mount", + "unshare", + "setns", + "bpf", + ): + number = lib.seccomp_syscall_resolve_name(name.encode()) + if ( + number >= 0 + and lib.seccomp_rule_add(ctx, 0x00050000 | errno.EPERM, number, 0) != 0 + ): + raise RuntimeError("Cannot install execution isolation rule") + if lib.seccomp_load(ctx) != 0: + raise RuntimeError("Cannot activate execution isolation") +finally: + lib.seccomp_release(ctx) + +sys.path.insert(0, "/app") +from simulator import ToolSimulator # noqa: E402 + +request = json.load(sys.stdin) +json.dump(ToolSimulator().code_py_exec(request), sys.stdout) diff --git a/tasks/agentescape-25-skeleton-7499421d/environment/puzzle/export.py b/tasks/agentescape-25-skeleton-7499421d/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-25-skeleton-7499421d/environment/puzzle/export.py @@ -0,0 +1,13 @@ +"""Harbor invokes this inside the puzzle service after stopping the agent.""" + +import json +import pathlib +import urllib.request + +with urllib.request.urlopen("http://127.0.0.1:8000/state", timeout=10) as response: + state = json.load(response) +state["collected_from_live_service"] = True +target = pathlib.Path("/evidence/final.json") +temp = target.with_suffix(".tmp") +temp.write_text(json.dumps(state)) +temp.replace(target) diff --git a/tasks/agentescape-25-skeleton-7499421d/environment/puzzle/requirements.txt b/tasks/agentescape-25-skeleton-7499421d/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-25-skeleton-7499421d/environment/puzzle/requirements.txt @@ -0,0 +1,57 @@ +annotated-doc==0.0.5 + # via fastapi +annotated-types==0.8.0 + # via pydantic +anyio==4.16.0 + # via starlette +certifi==2026.10.23 + # via requests +cffi==2.1.1 ; platform_python_implementation != 'PyPy' + # via cryptography +charset-normalizer==3.5.2 + # via requests +click==8.5.0 + # via uvicorn +cryptography==50.0.2 + # via agentescapebench-harbor +fastapi==0.162.0 + # via agentescapebench-harbor +h11==0.16.0 + # via uvicorn +idna==3.20 + # via + # anyio + # requests +opentelemetry-api==1.45.2 + # via fastapi +pycparser==3.12 ; implementation_name != 'PyPy' and platform_python_implementation != 'PyPy' + # via cffi +pydantic==2.14.2 + # via + # agentescapebench-harbor + # fastapi +pydantic-core==2.50.2 + # via pydantic +pytz==2025.2 + # via agentescapebench-harbor +requests==2.34.2 + # via agentescapebench-harbor +starlette==1.10.0 + # via fastapi +typing-extensions==4.16.0 + # via + # anyio + # fastapi + # opentelemetry-api + # pydantic + # pydantic-core + # starlette + # typing-inspection +typing-inspection==0.4.4 + # via + # fastapi + # pydantic +urllib3==2.8.0 + # via requests +uvicorn==0.54.0 + # via agentescapebench-harbor diff --git a/tasks/agentescape-25-skeleton-7499421d/environment/puzzle/scenario.json b/tasks/agentescape-25-skeleton-7499421d/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..7deb8073bae4c50646f2a9308bb7471a096478c2 --- /dev/null +++ b/tasks/agentescape-25-skeleton-7499421d/environment/puzzle/scenario.json @@ -0,0 +1,1453 @@ +{ + "metadata": { + "total_nodes": 25, + "total_edges": 30, + "win_node_id": "zlib_deflate", + "win_condition": { + "type": "tool_output", + "node_id": "zlib_deflate", + "output_port": "hex", + "output_type": "Hex_String", + "description": "Execute Zlib Deflate and get the output from port 'hex'" + }, + "source_init": { + "source_nodes": [ + "crypto_rsa_decrypt_hex", + "terminal_2", + "zip_unzip_file", + "zip_unzip_file_61fa", + "num_base_convert", + "zip_unzip_file_5af7", + "calc_gcd", + "num_base_convert_53cc", + "regex_search", + "csv_query", + "luhn_check", + "zip_unzip_file_1f72", + "checksum_crc32_18c4", + "code_py_exec" + ], + "by_node": { + "crypto_rsa_decrypt_hex": { + "node_name": "RSA Decrypt", + "node_type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "init_inputs": { + "hex_cipher": { + "type": "Hex_String", + "description": "Ciphertext (Hex)" + } + }, + "init_outputs": {} + }, + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": { + "num1": { + "type": "Big_Int", + "description": "First Number" + } + }, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + }, + "math_token": { + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "zip_unzip_file_61fa": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "num_base_convert": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "s": { + "type": "Big_Int", + "description": "Input integer value" + } + }, + "init_outputs": {} + }, + "zip_unzip_file_5af7": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "calc_gcd": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "b": { + "type": "Big_Int", + "description": "Second integer" + } + }, + "init_outputs": {} + }, + "num_base_convert_53cc": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "from_base": { + "type": "Big_Int", + "description": "From base" + }, + "to_base": { + "type": "Big_Int", + "description": "To base" + } + }, + "init_outputs": {} + }, + "regex_search": { + "node_name": "Regex Search", + "node_type": "Tool", + "template_id": "regex_search", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "File ID (optional)" + } + }, + "init_outputs": { + "matches": { + "type": "Text_Generic", + "description": "Found matches (List)" + } + } + }, + "csv_query": { + "node_name": "CSV Query", + "node_type": "Tool", + "template_id": "csv_query", + "init_inputs": {}, + "init_outputs": { + "rows": { + "type": "Text_Generic", + "description": "Result rows" + } + } + }, + "luhn_check": { + "node_name": "Luhn Checker", + "node_type": "Tool", + "template_id": "luhn_check", + "init_inputs": { + "number": { + "type": "Text_Generic", + "description": "Number string" + } + }, + "init_outputs": {} + }, + "zip_unzip_file_1f72": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + }, + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "checksum_crc32_18c4": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + }, + "code_py_exec": { + "node_name": "Python Executor", + "node_type": "Tool", + "template_id": "code_py_exec", + "init_inputs": { + "code": { + "type": "Code_Python", + "description": "Python code" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "crypto_rsa_decrypt_hex": { + "init_inputs": { + "hex_cipher": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + }, + "init_outputs": {} + }, + "terminal_2": { + "init_inputs": { + "num1": "8472948175928374928157" + }, + "init_outputs": { + "text_result": "Terminal output partial result ready.", + "hex_result": "ab12cd34ef569078", + "math_token": "Just an empty useless mathematical token here." + } + }, + "zip_unzip_file": { + "init_inputs": { + "password": "securePass123" + }, + "init_outputs": { + "files": "extracted_data_1.csv" + } + }, + "zip_unzip_file_61fa": { + "init_inputs": {}, + "init_outputs": { + "files": "extracted_data_2.txt" + } + }, + "num_base_convert": { + "init_inputs": { + "s": "48291048293847192837482" + }, + "init_outputs": {} + }, + "zip_unzip_file_5af7": { + "init_inputs": {}, + "init_outputs": { + "files": "extracted_data_3.json" + } + }, + "calc_gcd": { + "init_inputs": { + "b": "29481759283748192837582" + }, + "init_outputs": {} + }, + "num_base_convert_53cc": { + "init_inputs": { + "from_base": "16", + "to_base": "10" + }, + "init_outputs": {} + }, + "regex_search": { + "init_inputs": { + "file_id": "search_target.log" + }, + "init_outputs": { + "matches": "[\"user_1\", \"user_2\", \"user_3\", \"user_4\", \"user_5\"]" + } + }, + "csv_query": { + "init_inputs": {}, + "init_outputs": { + "rows": "[{\"col1\":\"val1\"}, {\"col1\":\"val2\"}, {\"col1\":\"val3\"}, {\"col1\":\"val4\"}]" + } + }, + "luhn_check": { + "init_inputs": { + "number": "4561261212345464" + }, + "init_outputs": {} + }, + "zip_unzip_file_1f72": { + "init_inputs": { + "zip_id": "archive_main.zip", + "password": "archivePass456" + }, + "init_outputs": { + "files": "extracted_data_4.xml" + } + }, + "checksum_crc32_18c4": { + "init_inputs": { + "hex": "112233445566778899aabbccddeeff00" + }, + "init_outputs": {} + }, + "code_py_exec": { + "init_inputs": { + "code": "print('Hello World')\nresult = 42" + }, + "init_outputs": {} + } + }, + "intro_narrative": "The year is 2142. The world you once knew has been reduced to ash and twisted metal, ravaged by the Great Collapse. You are a Scavenger, wandering the irradiated wasteland of Sector 7. Your Geiger counter clicks rapidly as you stumble upon an underground bunker, its heavy blast doors slightly ajar. Inside lies a complex network of ancient terminals, cryptographic devices, and forgotten storage drives left behind by the architects of the old world. Your objective is clear: navigate this labyrinth of decayed technology, restore the power relays, and extract the encrypted emergency coordinates before the bunker's collapsing power grid seals you inside forever. Every device is interconnected, demanding logic and careful exploration to piece together the final transmission. Time is running out, and the wasteland forgives no mistakes.", + "narrative_style": "post_apocalyptic" + }, + "nodes": [ + { + "id": "zlib_deflate", + "name": "Zlib Deflate", + "description": "Deflate text to zlib bytes (hex).", + "type": "Tool", + "template_id": "zlib_deflate", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Text to compress", + "value": "Al9LDmUX" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Compressed hex", + "value": "789c73ccb1f471c90d8d00000b2f0291" + } + ], + "narrative": "This is the Final Compression Protocol. It requires input from the Transmission Relay to finalize the emergency broadcast." + }, + { + "id": "base64_encode", + "name": "Base64 Encoder", + "description": "Encode hex bytes to base64.", + "type": "Tool", + "template_id": "base64_encode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex bytes", + "value": "025f4b0e6517" + } + ], + "outputs": [ + { + "name": "b64", + "type": "Text_Generic", + "description": "Base64 string", + "value": "Al9LDmUX" + } + ], + "narrative": "This is a Transmission Relay. It requires input from the Data Compiler to establish an uplink." + }, + { + "id": "hex_encode", + "name": "Text to Hex Encoder", + "description": "Encode UTF-8 text to hex.", + "type": "Tool", + "template_id": "hex_encode", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "\u0002_K\u000ee\u0017" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Encoded hex", + "value": "025f4b0e6517" + } + ], + "narrative": "This is a Data Compiler. It requires input from the Decryption Matrix to structure the recovered files." + }, + { + "id": "zip_unzip_item", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_item", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "extracted_data_1.csv" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Terminal output partial result ready." + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip" + } + ], + "narrative": "This is a Secure Vault. It requires inputs from the Main Command Terminal and the Encrypted Storage Drive Delta." + }, + { + "id": "crypto_rsa_decrypt_hex", + "name": "RSA Decrypt", + "description": "RSA decrypt (hex cipher) with n,d (decimal).", + "type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex_cipher", + "type": "Hex_String", + "description": "Ciphertext (Hex)", + "value": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Modulus n", + "value": "48291048293847192837482" + }, + { + "name": "d", + "type": "Big_Int", + "description": "Private exponent d", + "value": 3549980404 + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decrypted text", + "value": "\u0002_K\u000ee\u0017" + } + ], + "init": { + "inputs": { + "hex_cipher": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + }, + "outputs": {} + }, + "narrative": "This is a Decryption Matrix. It requires inputs from the Secondary Radiation Scanner and the Quantum Decoupler." + }, + { + "id": "terminal_2", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this terminal" + }, + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "8472948175928374928157" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "154997392648" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Terminal output partial result ready." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "ab12cd34ef569078" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "Just an empty useless mathematical token here." + } + ], + "init": { + "inputs": { + "num1": "8472948175928374928157" + }, + "outputs": { + "text_result": "Terminal output partial result ready.", + "hex_result": "ab12cd34ef569078", + "math_token": "Just an empty useless mathematical token here." + } + }, + "narrative": "This is the Main Command Terminal. It requires input from the Power Conversion Relay to boot up its interface." + }, + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "extracted_data_2.txt" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "securePass123" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_data_1.csv" + } + ], + "init": { + "inputs": { + "password": "securePass123" + }, + "outputs": { + "files": "extracted_data_1.csv" + } + }, + "narrative": "This is Encrypted Storage Drive Delta. It requires input from the Encrypted Storage Drive Gamma to initiate extraction." + }, + { + "id": "zip_unzip_file_61fa", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "extracted_data_3.json" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Terminal output partial result ready." + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_data_2.txt" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "extracted_data_2.txt" + } + }, + "narrative": "This is Encrypted Storage Drive Gamma. It requires inputs from the Main Command Terminal and the Encrypted Storage Drive Beta." + }, + { + "id": "checksum_crc32", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "5b22757365725f31222c2022757365725f32222c2022757365725f33222c2022757365725f34222c2022757365725f35225d" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "d39866f4" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3549980404 + } + ], + "narrative": "This is a Secondary Radiation Scanner. It requires input from the Signal Modulator to verify integrity." + }, + { + "id": "hex_encode_f266", + "name": "Text to Hex Encoder", + "description": "Encode UTF-8 text to hex.", + "type": "Tool", + "template_id": "hex_encode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "[\"user_1\", \"user_2\", \"user_3\", \"user_4\", \"user_5\"]" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Encoded hex", + "value": "5b22757365725f31222c2022757365725f32222c2022757365725f33222c2022757365725f34222c2022757365725f35225d" + } + ], + "narrative": "This is a Signal Modulator. It requires input from the Pattern Analyzer to encode the outgoing frequencies." + }, + { + "id": "num_base_convert", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "48291048293847192837482" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "2" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "154997392648" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "48291048293847192837482" + } + ], + "init": { + "inputs": { + "s": "48291048293847192837482" + }, + "outputs": {} + }, + "narrative": "This is a Quantum Decoupler. It requires inputs from both the Harmonic Resonance Calibrator and the Power Conversion Relay." + }, + { + "id": "zip_unzip_file_5af7", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "extracted_data_4.xml" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "false" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_data_3.json" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "extracted_data_3.json" + } + }, + "narrative": "This is Encrypted Storage Drive Beta. It requires inputs from the Encrypted Storage Drive Alpha and the Biometric Authenticator." + }, + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "154997392648" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "29481759283748192837582" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "2" + } + ], + "init": { + "inputs": { + "b": "29481759283748192837582" + }, + "outputs": {} + }, + "narrative": "This is a Harmonic Resonance Calibrator. It requires input from the Power Conversion Relay to synchronize." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "An Access Token. A small metallic chip bearing the insignia of the old world." + }, + { + "id": "item_8_8e8e", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A Rusty Keycard. A dilapidated piece of plastic with a faded magnetic strip." + }, + { + "id": "num_base_convert_53cc", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": 2416908508 + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "16" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "10" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "154997392648" + } + ], + "init": { + "inputs": { + "from_base": "16", + "to_base": "10" + }, + "outputs": {} + }, + "narrative": "This is a Power Conversion Relay. It requires input from the Primary Radiation Scanner to calibrate its output." + }, + { + "id": "regex_search", + "name": "Regex Search", + "description": "Search regex in either raw text or a file.", + "type": "Tool", + "template_id": "regex_search", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "pattern", + "type": "Text_Generic", + "description": "Regex pattern", + "value": "Terminal output partial result ready." + }, + { + "name": "file_id", + "type": "File_Id", + "description": "File ID (optional)", + "value": "search_target.log" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text (optional)", + "value": "[{\"col1\":\"val1\"}, {\"col1\":\"val2\"}, {\"col1\":\"val3\"}, {\"col1\":\"val4\"}]" + } + ], + "outputs": [ + { + "name": "matches", + "type": "Text_Generic", + "description": "Found matches (List)", + "value": "[\"user_1\", \"user_2\", \"user_3\", \"user_4\", \"user_5\"]" + } + ], + "init": { + "inputs": { + "file_id": "search_target.log" + }, + "outputs": { + "matches": "[\"user_1\", \"user_2\", \"user_3\", \"user_4\", \"user_5\"]" + } + }, + "narrative": "This is a Pattern Analyzer. It requires inputs from the Main Command Terminal and the Database Server to run diagnostics." + }, + { + "id": "csv_query", + "name": "CSV Query", + "description": "Query CSV: select columns and simple WHERE.", + "type": "Tool", + "template_id": "csv_query", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "CSV file ID", + "value": "extracted_data_2.txt" + }, + { + "name": "select", + "type": "Text_Generic", + "description": "Columns to select", + "value": "false" + }, + { + "name": "where", + "type": "Text_Generic", + "description": "Where clause", + "value": "Hello World\n" + } + ], + "outputs": [ + { + "name": "rows", + "type": "Text_Generic", + "description": "Result rows", + "value": "[{\"col1\":\"val1\"}, {\"col1\":\"val2\"}, {\"col1\":\"val3\"}, {\"col1\":\"val4\"}]" + } + ], + "init": { + "inputs": {}, + "outputs": { + "rows": "[{\"col1\":\"val1\"}, {\"col1\":\"val2\"}, {\"col1\":\"val3\"}, {\"col1\":\"val4\"}]" + } + }, + "narrative": "This is a Database Server. It requires inputs from the Biometric Authenticator, the Encrypted Storage Drive Gamma, and the Automated Maintenance Drone." + }, + { + "id": "luhn_check", + "name": "Luhn Checker", + "description": "Luhn validity of number string.", + "type": "Tool", + "template_id": "luhn_check", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "number", + "type": "Text_Generic", + "description": "Number string", + "value": "4561261212345464" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "false" + } + ], + "init": { + "inputs": { + "number": "4561261212345464" + }, + "outputs": {} + }, + "narrative": "A Biometric Authenticator. A grimy handprint scanner mounted on the reinforced wall." + }, + { + "id": "zip_unzip_file_1f72", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "archive_main.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "archivePass456" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_data_4.xml" + } + ], + "init": { + "inputs": { + "zip_id": "archive_main.zip", + "password": "archivePass456" + }, + "outputs": { + "files": "extracted_data_4.xml" + } + }, + "narrative": "Encrypted Storage Drive Alpha. A heavily encrypted data drive found in the debris." + }, + { + "id": "item_8_bcb4", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A Control Module. A dust-covered circuit board missing its casing." + }, + { + "id": "item_8_df11", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "An Override Chip. A specialized bypass circuit found among the ruins." + }, + { + "id": "checksum_crc32_18c4", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "112233445566778899aabbccddeeff00" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "900f18dc" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 2416908508 + } + ], + "init": { + "inputs": { + "hex": "112233445566778899aabbccddeeff00" + }, + "outputs": {} + }, + "narrative": "The Primary Radiation Scanner. An old handheld device used to measure residual radiation levels in the sector." + }, + { + "id": "code_py_exec", + "name": "Python Executor", + "description": "Run limited Python: only safe builtins.", + "type": "Tool", + "template_id": "code_py_exec", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "code", + "type": "Code_Python", + "description": "Python code", + "value": "print('Hello World')\nresult = 42" + } + ], + "outputs": [ + { + "name": "stdout", + "type": "Text_Generic", + "description": "Standard Output (includes errors if any)", + "value": "Hello World\n" + } + ], + "init": { + "inputs": { + "code": "print('Hello World')\nresult = 42" + }, + "outputs": {} + }, + "narrative": "An Automated Maintenance Drone. A barely functioning robotic unit wandering the facility." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A Chronometer. A shattered digital watch that still weakly flashes." + } + ], + "edges": [ + { + "source_id": "base64_encode", + "target_id": "zlib_deflate", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "text" + }, + { + "source_id": "hex_encode", + "target_id": "base64_encode", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "zip_unzip_item", + "target_id": "hex_encode", + "connection_type": "Item", + "source_port": "item", + "target_port": "trigger_item" + }, + { + "source_id": "crypto_rsa_decrypt_hex", + "target_id": "hex_encode", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "text" + }, + { + "source_id": "terminal_2", + "target_id": "zip_unzip_item", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "password" + }, + { + "source_id": "zip_unzip_file", + "target_id": "zip_unzip_item", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "zip_unzip_file_61fa", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "checksum_crc32", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "d" + }, + { + "source_id": "hex_encode_f266", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "terminal_2", + "target_id": "zip_unzip_file_61fa", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "password" + }, + { + "source_id": "num_base_convert", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "n" + }, + { + "source_id": "zip_unzip_file_5af7", + "target_id": "zip_unzip_file_61fa", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "calc_gcd", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "from_base" + }, + { + "source_id": "item_8", + "target_id": "calc_gcd", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "item_8_8e8e", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "num_base_convert_53cc", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "num2" + }, + { + "source_id": "num_base_convert_53cc", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "a" + }, + { + "source_id": "regex_search", + "target_id": "hex_encode_f266", + "connection_type": "Text_Generic", + "source_port": "matches", + "target_port": "text" + }, + { + "source_id": "terminal_2", + "target_id": "regex_search", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "pattern" + }, + { + "source_id": "csv_query", + "target_id": "regex_search", + "connection_type": "Text_Generic", + "source_port": "rows", + "target_port": "text" + }, + { + "source_id": "luhn_check", + "target_id": "csv_query", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "select" + }, + { + "source_id": "num_base_convert_53cc", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "to_base" + }, + { + "source_id": "zip_unzip_file_1f72", + "target_id": "zip_unzip_file_5af7", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "item_8_bcb4", + "target_id": "terminal_2", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "item_8_df11", + "target_id": "num_base_convert", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "checksum_crc32_18c4", + "target_id": "num_base_convert_53cc", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "s" + }, + { + "source_id": "luhn_check", + "target_id": "zip_unzip_file_5af7", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "password" + }, + { + "source_id": "zip_unzip_file_61fa", + "target_id": "csv_query", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "code_py_exec", + "target_id": "csv_query", + "connection_type": "Text_Generic", + "source_port": "stdout", + "target_port": "where" + }, + { + "source_id": "item_16", + "target_id": "item_8_bcb4", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-7499421d/environment/puzzle/service.py b/tasks/agentescape-25-skeleton-7499421d/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-25-skeleton-7499421d/environment/puzzle/service.py @@ -0,0 +1,212 @@ +"""Restricted facade over the unchanged, pinned upstream puzzle handlers.""" + +import hashlib +import json +import logging +import os +import sys +import threading +import urllib.request +import uuid +from pathlib import Path + +from fastapi import FastAPI, HTTPException +from fastapi.responses import JSONResponse +from pydantic import BaseModel, ConfigDict + +sys.path.insert(0, str(Path(__file__).parent / "upstream")) +import server as upstream # noqa: E402 + +log = logging.getLogger(__name__) + + +def public(value): + """Keep upstream agent-internal template hints out of the public response.""" + if isinstance(value, dict): + return {k: public(v) for k, v in value.items() if not k.startswith("_")} + if isinstance(value, list): + return [public(v) for v in value] + return value + + +class Action(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + action: str + node_id: str | None = None + arguments: dict | None = None + answer: str | None = None + + +class Episode: + def __init__( + self, scenario_path, max_actions=500, evidence_dir=None, worker_url=None + ): + if max_actions < 1: + raise ValueError("max_actions must be positive") + self.lock = threading.Lock() + self.max_actions = max_actions + self.count = 0 + self.won = False + self.reason = None + self.evidence_dir = Path(evidence_dir) if evidence_dir else None + self.scenario_hash = hashlib.sha256( + Path(scenario_path).read_bytes() + ).hexdigest() + self.initial = upstream.reset_case( + case_file_path=str(scenario_path), session_id=uuid.uuid4().hex + ) + self.case_id = self.initial["case_id"] + # Hide source file paths; no upstream reset/stats/routes are mounted. + self.initial.pop("message", None) + simulator = upstream.SIMULATORS[self.case_id] + if worker_url is None: + + def no_worker(_inputs): + self.reason = "infrastructure_error" + raise RuntimeError("isolated Python worker is not configured") + + simulator.tool_map["code_py_exec"] = no_worker + else: + + def execute_python(inputs): + request = urllib.request.Request( + worker_url + "/execute", + data=json.dumps({"code": inputs.get("code", "")}).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=12) as response: + result = json.load(response) + if not isinstance(result.get("stdout"), str): + raise RuntimeError("Invalid Python worker response") + return result + except Exception: + self.reason = "infrastructure_error" + raise + + simulator.tool_map["code_py_exec"] = execute_python + self.save() + if self.evidence_dir is not None: + (self.evidence_dir / "trace.jsonl").touch() + + def state(self): + return { + "scenario_sha256": self.scenario_hash, + "action_count": self.count, + "max_actions": self.max_actions, + "won": self.won, + "termination_reason": self.reason, + } + + def save(self, action=None, result=None): + if self.evidence_dir is None: + return + self.evidence_dir.mkdir(parents=True, exist_ok=True) + target = self.evidence_dir / "outcome.json" + temp = target.with_suffix(".tmp") + temp.write_text(json.dumps(self.state())) + temp.replace(target) + if action is not None: + with (self.evidence_dir / "trace.jsonl").open("a") as handle: + handle.write( + json.dumps( + {"index": self.count, "action": action, "result": result} + ) + + "\n" + ) + + def dispatch(self, payload): + with self.lock: + if self.reason is not None: + return { + "ok": False, + "error": "Episode has ended", + "episode": self.state(), + } + self.count += 1 + try: + action = Action.model_validate(payload) + if action.action == "submit_answer" and action.answer is not None: + result = upstream.submit_answer( + self.case_id, upstream.SubmitAnswerRequest(answer=action.answer) + ) + if result.get("is_win"): + self.won = True + self.reason = "success" + elif action.action == "investigate" and action.node_id is not None: + result = upstream.investigate( + self.case_id, + upstream.InvestigateRequest(node_id=action.node_id), + ) + elif ( + action.action in ("tool_call", "use_item") + and action.node_id is not None + ): + request_type, handler = ( + (upstream.ToolCallRequest, upstream.tool_call) + if action.action == "tool_call" + else (upstream.UseItemRequest, upstream.use_item) + ) + result = handler( + self.case_id, + request_type( + node_id=action.node_id, arguments=action.arguments or {} + ), + ) + else: + result = { + "ok": False, + "error": "Unknown action or missing action parameter", + } + except HTTPException as exc: + result = {"ok": False, "error": exc.detail} + except ValueError: + result = {"ok": False, "error": "Malformed action"} + except Exception: + log.exception("Puzzle service failure") + self.reason = "infrastructure_error" + self.save() + raise + if self.reason is None and self.count >= self.max_actions: + self.reason = "action_budget_exhausted" + result = public(result) + result["episode"] = self.state() + self.save(payload, result) + return result + + +def create_app( + scenario_path=None, max_actions=None, evidence_dir=None, worker_url=None +): + episode = Episode( + scenario_path or os.environ["SCENARIO_PATH"], + max_actions or int(os.environ.get("MAX_ACTIONS", "500")), + evidence_dir if evidence_dir is not None else os.environ.get("EVIDENCE_DIR"), + worker_url if worker_url is not None else os.environ.get("WORKER_URL"), + ) + app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) + app.state.episode = episode + + @app.get("/health") + def health(): + return {"ok": True} + + @app.get("/observation") + def observation(): + return {**public(episode.initial), "episode": episode.state()} + + @app.get("/state") + def state(): + return episode.state() + + @app.post("/action") + def action(payload: dict): + try: + return episode.dispatch(payload) + except Exception: + return JSONResponse( + status_code=503, + content={"ok": False, "error": "Puzzle infrastructure failure"}, + ) + + return app diff --git a/tasks/agentescape-25-skeleton-7499421d/environment/puzzle/upstream/models.py b/tasks/agentescape-25-skeleton-7499421d/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-25-skeleton-7499421d/environment/puzzle/upstream/models.py @@ -0,0 +1,108 @@ +from enum import Enum +from typing import List, Dict, Any, Optional +from pydantic import BaseModel, Field + +# 1. 细粒度接口类型定义 +class InterfaceType(str, Enum): + ''' + BIG_INT + TEXT_GENERIC + HEX_STRING + FILE_ID + HEX_STRING_KEY_AES + HEX_STRING_IV_AES + CODE_PYTHON + HIDDEN_ITEM + ITEM + ''' + # --- 基础类型 --- + TEXT_GENERIC = "Text_Generic" + BIG_INT = "Big_Int" + + # --- 编码/格式化字符串 --- + HEX_STRING = "Hex_String" # 通用 Hex + + # --- 特定用途的 Hex 字符串 (用于精确匹配) --- + HEX_STRING_KEY_AES = "Hex_String_Key_AES" + HEX_STRING_IV_AES = "Hex_String_IV_AES" + + # --- 文件类型 --- + FILE_ID = "File_Id" + + # --- 代码/脚本 --- + CODE_PYTHON = "Code_Python" + + # --- 实体交互类型 (严格命名) --- + ITEM = "Item" # 主动掉落接口 (Tool -> Item) + HIDDEN_ITEM = "Hidden_Item" # 被动掉落接口 (Item -> Item) + +# 3. 端口定义 +class Port(BaseModel): + name: str + type: InterfaceType + description: str + +# 4. 统一节点定义 (融合工具和物品) +class Node(BaseModel): + id: str + name: str + description: str + type: str # "Tool" or "Item" + + # 接口定义 + inputs: List[Port] = [] + outputs: List[Port] = [] + + # 状态字段 + content: Optional[Any] = None # 物品有内容,工具为None + if_success: Optional[bool] = None # 工具初始为False,物品为None + initial_visible: bool = False + + # 运行时状态 (Server维护) + is_revealed: bool = False + + # 标记该 Tool 节点是否有待触发的 HIDDEN_ITEM 掉落 + # 当 Tool 按照 golden_input 正确执行且有 HIDDEN_ITEM 输出边时设为 True + # 在 investigate 该 Tool 时触发掉落并重置为 False + has_hidden_item_ready: bool = False + + # 初始输入值 (metadata.initial_values.init_inputs,用于渐进式暴露判断) + init_input_values: Dict[str, Any] = {} + + # Golden 输入值 (nodes[].inputs[].value,用于评测验证) + golden_input_values: Dict[str, Any] = {} + + # Golden 输出值 (nodes[].outputs[].value,用于评测验证和 Item 节点的 content) + golden_output_values: Dict[str, Any] = {} + + # 实际获得的输出值历史 (工具每次执行后实际返回的输出列表,用于渐进式暴露判断) + # 格式: List[Dict[str, Any]],每个元素是一次执行的输出字典 + actual_outputs_history: List[Dict[str, Any]] = [] + + # 逻辑规则 (用于终端机等复杂物品) + logic_rules: Optional[Dict[str, Any]] = None + + def copy(self, **kwargs): + """Helper to create a copy with updated fields.""" + data = self.dict() + data.update(kwargs) + return Node(**data) + +# 5. 边定义 (拓扑结构) +class Edge(BaseModel): + source_id: str + target_id: str + connection_type: InterfaceType # 直接使用 InterfaceType + # 如果是 Data_Flow,指定端口对应关系 + source_port: Optional[str] = None + target_port: Optional[str] = None + +# 6. 完整图定义 +class GraphScenario(BaseModel): + case_id: str + title: str + intro_narrative: str + nodes: Dict[str, Node] + edges: List[Edge] + difficulty: int + win_node_id: str # 标记哪个节点是最终目标(通常是一个提交工具或最终物品) diff --git a/tasks/agentescape-25-skeleton-7499421d/environment/puzzle/upstream/server.py b/tasks/agentescape-25-skeleton-7499421d/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-25-skeleton-7499421d/environment/puzzle/upstream/server.py @@ -0,0 +1,1490 @@ +import json +import os +import time +import logging +import random +from pathlib import Path +from typing import Dict, Any, List, Optional +from datetime import datetime +from collections import defaultdict +from fastapi import FastAPI, HTTPException, Request +from fastapi.responses import JSONResponse +from fastapi.middleware.cors import CORSMiddleware +from pydantic import BaseModel, Field + +from models import GraphScenario, Node, InterfaceType +# from generator import ScenarioGenerator +from simulator import ToolSimulator +import uvicorn + +# 配置日志 +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler('server.log'), + logging.StreamHandler() + ] +) +logger = logging.getLogger(__name__) + +app = FastAPI( + title="AgentEscapeBench Universal Server", + version="1.0.0", + description="Industrial-grade evaluation server for escape room AI agents" +) + +# 添加 CORS 支持 +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# In-memory State +SCENARIOS: Dict[str, GraphScenario] = {} +SIMULATORS: Dict[str, ToolSimulator] = {} # case_id -> ToolSimulator +RAW_NODES_DATA: Dict[str, Dict[str, Any]] = {} # case_id -> node_id -> raw node data (for template_id) +FILE_METADATA: Dict[str, Dict[str, Any]] = {} # case_id -> metadata (for initial_values access) + +# Performance monitoring +STATS: Dict[str, Any] = { + "total_requests": 0, + "successful_requests": 0, + "failed_requests": 0, + "tool_calls": defaultdict(int), + "investigates": defaultdict(int), + "use_items": defaultdict(int), + "case_loads": 0, + "start_time": datetime.now() +} + +# Request timing middleware +@app.middleware("http") +async def add_process_time_header(request: Request, call_next): + start_time = time.time() + STATS["total_requests"] += 1 + + try: + response = await call_next(request) + STATS["successful_requests"] += 1 + process_time = time.time() - start_time + response.headers["X-Process-Time"] = str(process_time) + logger.info(f"{request.method} {request.url.path} - {response.status_code} - {process_time:.3f}s") + return response + except Exception as e: + STATS["failed_requests"] += 1 + logger.error(f"{request.method} {request.url.path} - Error: {str(e)}") + raise + +# Exception handler +@app.exception_handler(Exception) +async def global_exception_handler(request: Request, exc: Exception): + logger.error(f"Unhandled exception: {exc}", exc_info=True) + return JSONResponse( + status_code=500, + content={ + "ok": False, + "error": "Internal server error", + "detail": str(exc) if os.getenv("DEBUG") else "An error occurred" + } + ) + +# Health check endpoint +@app.get("/health") +def health_check(): + """健康检查端点""" + uptime = (datetime.now() - STATS["start_time"]).total_seconds() + return { + "status": "healthy", + "version": "1.0.0", + "uptime_seconds": uptime, + "loaded_cases": len(SCENARIOS), + "stats": { + "total_requests": STATS["total_requests"], + "successful_requests": STATS["successful_requests"], + "failed_requests": STATS["failed_requests"], + "success_rate": STATS["successful_requests"] / max(STATS["total_requests"], 1) + } + } + +# Statistics endpoint +@app.get("/stats") +def get_stats(): + """获取详细统计信息""" + return { + "stats": STATS, + "loaded_cases": list(SCENARIOS.keys()), + "uptime": str(datetime.now() - STATS["start_time"]) + } + +def _apply_progressive_reveal_at_init(scenario: GraphScenario): + """ + 在初始化时应用渐进式暴露机制(基于ITEM/HIDDEN_ITEM边) + + 新逻辑: + - 如果一个节点没有 ITEM/HIDDEN_ITEM 类型的入边,它就是初始可见的 + - 如果一个节点有 ITEM/HIDDEN_ITEM 类型的入边,它初始不可见,需要等待上游触发 + + Args: + scenario: 场景对象 + """ + # 收集所有有 ITEM/HIDDEN_ITEM 入边的节点 + nodes_with_item_edges = set() + for edge in scenario.edges: + if edge.connection_type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + nodes_with_item_edges.add(edge.target_id) + + logger.info(f"Nodes with ITEM/HIDDEN_ITEM incoming edges: {nodes_with_item_edges}") + + # 设置初始可见性:没有 ITEM/HIDDEN_ITEM 入边的节点初始可见 + initially_visible_count = 0 + for node_id, node in scenario.nodes.items(): + if node_id not in nodes_with_item_edges: + node.is_revealed = True + initially_visible_count += 1 + logger.info(f"Initial visible (no ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + else: + node.is_revealed = False + logger.debug(f"Initial hidden (has ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + + logger.info(f"Progressive reveal initialized: {initially_visible_count}/{len(scenario.nodes)} nodes initially visible") + + +def _check_inputs_match_golden(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> bool: + """ + 检查实际输入参数是否与 golden inputs 完全匹配 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + True 表示所有 golden inputs 都存在且值匹配 + """ + if not golden_inputs: + return True # 如果没有 golden inputs,认为匹配 + + for key, expected_value in golden_inputs.items(): + actual_value = arguments.get(key) + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) != str(expected_value): + logger.debug(f"Input mismatch for '{key}': expected '{expected_value}', got '{actual_value}'") + return False + + return True + + +def _get_parameter_validation_feedback(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> Dict[str, Any]: + """ + 对源头节点的参数进行详细验证,返回验证反馈 + + 注意:不返回期望值(expected),避免泄漏答案 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + 包含验证结果的字典: + - all_correct: bool - 所有参数是否正确 + - correct_params: List[str] - 正确的参数名列表 + - incorrect_params: List[str] - 错误的参数名列表(不包含期望值) + """ + if not golden_inputs: + return { + "all_correct": True, + "correct_params": [], + "incorrect_params": [] + } + + correct_params = [] + incorrect_params = [] + + for key, actual_value in arguments.items(): + # 只对用户实际提交的参数给反馈,未提交的参数不评价 + if key not in golden_inputs: + continue # 该参数不在 golden 中,跳过(如 _golden_inputs 等内部参数) + expected_value = golden_inputs[key] + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) == str(expected_value): + correct_params.append(key) + else: + # 只记录参数名,不包含期望值,避免泄漏答案 + incorrect_params.append(key) + + # all_correct:用户提交的所有参数都正确,且覆盖了全部 golden 参数 + all_provided_correct = len(incorrect_params) == 0 + all_golden_covered = all(k in arguments for k in golden_inputs) + return { + "all_correct": all_provided_correct and all_golden_covered, + "correct_params": correct_params, + "incorrect_params": incorrect_params + } + + +def _is_source_node(node_id: str, scenario: GraphScenario) -> bool: + """ + 判断节点是否是源头节点(完全没有任何入边的节点) + + 源头节点定义: + - 没有任何类型的入边(包括 DATA、ITEM、HIDDEN_ITEM) + - 即没有任何上游节点 + + Args: + node_id: 节点ID + scenario: 场景对象 + + Returns: + True 表示是源头节点 + """ + for edge in scenario.edges: + if edge.target_id == node_id: + # 只要有任何入边,就不是源头节点 + return False + + return True + + +def _check_and_reveal_ready_nodes(scenario: GraphScenario, recent_outputs: Dict[str, Any], source_node_id: str) -> List[Dict[str, Any]]: + """ + 检查并释放参数齐全的隐藏节点(渐进式暴露机制) + + 核心逻辑: + 1. 维护"可见值集合":包含所有被测模型当前可以看到的值 + - init_inputs 的值(初始可见) + - 工具执行后的实际输出值(运行时获得) + - 可见 Item 的输出值 + 2. 检查隐藏节点:该节点的所有 golden_input 值是否都在可见值集合中 + 3. 如果是,则释放该节点 + + Args: + scenario: 场景对象 + recent_outputs: 最近执行的工具的输出 + source_node_id: 刚执行的工具节点ID + + Returns: + 新释放的节点列表 + """ + newly_revealed = [] + + # 构建"可见值集合"(Set of visible values) + # 存储格式:set of values (转为字符串) + visible_values = set() + + # 1. 添加有意义的 init_inputs 值到可见值集合 + # Item 的 init_inputs 不应该加入,因为它们在密室中完全用不到 + for node_id, node in scenario.nodes.items(): + # 跳过源头 Item 节点(没有入边的 Item) + if node.type == "Item": + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,跳过其 init_inputs + continue + + # 添加其他节点的 init_inputs + for port_name, init_value in node.init_input_values.items(): + if init_value: + visible_values.add(str(init_value)) + + # 2. 添加已执行工具的所有历史输出值 + for node_id, node in scenario.nodes.items(): + if node.type == "Tool" and node.if_success and node.actual_outputs_history: + # 遍历所有历史执行记录 + for output_dict in node.actual_outputs_history: + for output_port_name, output_value in output_dict.items(): + if output_value: + visible_values.add(str(output_value)) + + # 3. 添加已被 investigate 的 Item 的 golden 输出值 + # 注意:Item 可见不等于其输出值可见,需要 investigate 后才能获得 + # 这里我们使用 actual_outputs_history 来标记 Item 是否已被 investigate + for node_id, node in scenario.nodes.items(): + if node.type == "Item" and node.is_revealed and node.actual_outputs_history: + # Item 通常只会被 investigate 一次,但为了一致性也使用历史列表 + for output_dict in node.actual_outputs_history: + for port_name, port_value in output_dict.items(): + if port_value: + visible_values.add(str(port_value)) + + # 遍历所有隐藏的节点,检查其 golden_input 是否都在可见值集合中 + for node_id, node in scenario.nodes.items(): + # 跳过已可见的节点 + if node.is_revealed: + continue + + # 只检查工具节点(物品节点由 ITEM 输出触发) + if node.type != "Tool": + continue + + # 检查该节点的所有 golden_input 值是否都在可见值集合中 + all_inputs_ready = True + missing_values = [] + + for input_port_name, golden_input_value in node.golden_input_values.items(): + # 检查这个 golden 值是否在可见值集合中 + if str(golden_input_value) not in visible_values: + all_inputs_ready = False + missing_values.append(f"{input_port_name}={golden_input_value}") + + # 如果所有 golden_input 值都在可见值集合中,释放该节点 + if all_inputs_ready and len(node.golden_input_values) > 0: + logger.info(f"All golden inputs ready for {node_id}: {list(node.golden_input_values.values())}") + + # 如果所有输入都齐全,释放该节点 + if all_inputs_ready: + node.is_revealed = True + + # 构建节点信息返回给模型 + node_info = { + "id": node.id, + "type": node.type, + "can_investigate": True, + "hint": "This tool's input parameters are now complete, you can use investigate to view detailed information" + } + + # if node.name: + # node_info["name"] = node.name + if node.description: + node_info["description"] = node.description + + newly_revealed.append(node_info) + logger.info(f"Progressive reveal: {node_id} is now ready (all inputs satisfied)") + + return newly_revealed + + +def _initialize_node_values(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]): + """ + Initialize node state and load values from port value fields. + 应用渐进式暴露机制:初始时只显示参数齐全的节点(源头节点) + + 重要区分: + 1. input_values: 只加载 metadata.initial_values 中的 init_inputs(真正的初始值) + 2. output_values: 加载 nodes[].outputs[].value(golden 输出,用于验证) + """ + # 第一步:加载所有节点的值,并将所有节点初始设为隐藏 + initial_values = metadata.get('initial_values', {}) + + for node_id, node in scenario.nodes.items(): + # 忽略 initial_visible 字段,初始全部隐藏 + # 由渐进式暴露机制根据参数齐全情况决定是否显示 + node.is_revealed = False + + if node.type == "Tool": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + elif node.type == "Item": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + + # 从 JSON 加载值 + if node_id in raw_nodes_data: + node_data = raw_nodes_data[node_id] # node_data是json文件中nodes中的字典 + + # 【重要】只加载 metadata.initial_values 中的初始输入值 + if node_id in initial_values: + init_data = initial_values[node_id] + # 加载初始输入值(用于渐进式暴露判断) + for port_name, port_value in init_data.get('init_inputs', {}).items(): + node.init_input_values[port_name] = port_value + + # 【评测用】加载 golden 输入值(用于验证模型传入的参数是否正确) + for input_port_data in node_data.get('inputs', []): + if 'value' in input_port_data: + node.golden_input_values[input_port_data['name']] = input_port_data['value'] + + # 【评测用】加载 golden 输出值(用于验证工具调用是否正确,以及 Item 节点的 content) + for output_port_data in node_data.get('outputs', []): + if 'value' in output_port_data: + node.golden_output_values[output_port_data['name']] = output_port_data['value'] + + # For Items, set content from golden_output_values + if node.type == "Item" and node.golden_output_values: + # Item 的 content 是其第一个 golden 输出值 + node.content = list(node.golden_output_values.values())[0] + + # 第二步:应用渐进式暴露机制 + # 检查所有节点,根据参数齐全情况释放源头节点(工具 + Item) + _apply_progressive_reveal_at_init(scenario) + +def _build_node_info(node: Node, raw_nodes_data: Dict[str, Any]) -> Dict[str, Any]: + """ + 构建节点信息(工具或物品) + + Args: + node: 节点对象 + raw_nodes_data: 原始节点数据(用于获取 template_id 等) + + Returns: + 节点信息字典 + """ + if node.type == "Tool": + # 过滤掉输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口) + # 这些端口仅用于控制掉落机制,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + tool_info = { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Tool", + "inputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.inputs if p.type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]], + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id(工具的标准名称) + if node.id in raw_nodes_data: + node_data = raw_nodes_data[node.id] + template_id = node_data.get('template_id') + if template_id: + tool_info['template_id'] = template_id + + return tool_info + + elif node.type == "Item": + return { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Item" + } + + else: + return { + "id": node.id, + # "name": node.name, + "type": node.type + } + +def _get_initial_observation(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]) -> Dict[str, Any]: + """ + Generate initial observation for the agent (what they see when entering the room). + + 策略: + - Tools: 只显示名称和描述,不显示接口定义。需要 investigate 才能获得详细接口信息。 + - Items: 只显示存在,不显示内容。需要 investigate 才能获得内容值。 + - init_inputs: 作为"可用信息"告诉模型,这些是可以用作工具参数的初始值。 + - init_outputs: 不告诉模型(这些是答案,需要模型通过调用工具获得)。 + """ + available_entities = [] # 统一的实体列表(Tools 和 Items) + available_information = [] # 可用的初始信息(来自 init_inputs) + + # 从 metadata.initial_values 提取 init_inputs 作为可用信息 + # 只提供值本身,不透露这些值对应哪个节点的哪个参数,让模型自己推理 + # 注意:跳过源头 Item(没有入边的 Item)的 init_inputs,因为它们在密室中完全用不到 + initial_values = metadata.get('initial_values', {}) + # initial_values字段的格式 + # "initial_values": { + # "terminal_1": { + # "init_inputs": {}, + # "init_outputs": { + # "text_output": "System initialization complete.", + # "hex_output": "48656c6c6f20576f726c64", + # "item_dispenser": "掉落了一张纸条,上面写着“请勿随意触摸终端”" + # } + # } + # } + for node_id, init_data in initial_values.items(): + # 获取节点信息,判断是否为源头 Item + node = scenario.nodes.get(node_id) + if node and node.type == "Item": + # 检查是否为源头 Item(没有入边) + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,检查是否有 init_inputs + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 有 init_inputs,需要暴露这些参数 + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + # 处理完后跳过后续的通用逻辑 + continue + + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 为每个 init_input 值创建一个信息条目(不包含 source_node 和 parameter 信息) + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + + for node in scenario.nodes.values(): + if node.is_revealed: + # Tools: 只显示基本信息,提示可以 investigate 查看详细接口 + if node.type == "Tool": + tool_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Tool", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the tool's detailed interface information for calling" + } + # 只在 name 非空时添加 + # if node.name: + # tool_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_info["description"] = node.description + + available_entities.append(tool_info) + + # Items: 只显示基本信息,提示可以 investigate 查看内容 + elif node.type == "Item": + item_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Item", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the item's content" + } + # 只在 name 非空时添加 + # if node.name: + # item_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + item_info["description"] = node.description + + available_entities.append(item_info) + + return { + "narrative": scenario.intro_narrative, + "available_entities": available_entities, # 使用统一的实体列表 + "available_information": available_information, # 可用的初始信息(只包含 init_inputs) + "win_node_id": scenario.win_node_id # 胜利节点ID,让模型知道需要关注哪个节点 + } + +@app.post("/env/reset") +def reset_case(case_id: str = None, case_file_path: str = None, session_id: str = None): + """Loads a specific case from file and resets it. + + Args: + case_id: Optional case ID for resetting an existing case + case_file_path: Path to case file for loading a new case + session_id: Optional session ID to ensure isolation between concurrent evaluations + """ + logger.info(f"Reset request - case_id: {case_id}, case_file_path: {case_file_path}, session_id: {session_id}") + STATS["case_loads"] += 1 + + if case_file_path: + if not os.path.exists(case_file_path): + logger.error(f"Case file not found: {case_file_path}") + raise HTTPException(status_code=404, detail=f"File not found: {case_file_path}") + try: + with open(case_file_path, "r", encoding="utf-8") as f: + file_data = json.load(f) + + # 转换格式:从 DAG executor 生成的格式转换为 GraphScenario 格式 + # 1. 提取 metadata + metadata = file_data.get('metadata', {}) + + # 2. 生成 case_id, title, intro_narrative + # 【修复】为每个评测会话生成唯一的 case_id,防止并发评测时状态污染 + base_name = os.path.basename(case_file_path).replace('.json', '').replace('_full', '').replace('_full2', '') + + if session_id: + # 如果提供了 session_id,使用它来确保唯一性 + case_id = f"{base_name}_{session_id}" + else: + # 否则使用时间戳和随机数确保唯一性 + unique_suffix = f"{int(time.time() * 1000)}_{random.randint(1000, 9999)}" + case_id = f"{base_name}_{unique_suffix}" + + file_data['case_id'] = case_id + logger.info(f"Generated unique case_id: {case_id} (base: {base_name}, session: {session_id})") + + if 'title' not in file_data: + file_data['title'] = f"Escape Room: {file_data['case_id']}" + + if 'intro_narrative' not in file_data: # 目前的json文件中已经有了intro_narrative字段,不会使用下面一行的内容,而是使用每个评测问题的json文件中的对应字段 + 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]".' + + # 3. 转换 nodes 列表为字典(DAG executor 生成的文件中 nodes 是列表格式) + nodes_dict = {} + for node_data in file_data['nodes']: + nodes_dict[node_data['id']] = node_data # 这里的id是template_id之后可能添加一个后缀 + file_data['nodes'] = nodes_dict # 把列表转成一个字典 + + # 4. 添加缺失的字段 + if 'difficulty' not in file_data: + file_data['difficulty'] = metadata.get('total_nodes', 5) + + if 'win_node_id' not in file_data: + file_data['win_node_id'] = metadata.get('win_node_id', '') + + scenario = GraphScenario(**file_data) + + # Extract raw nodes data for template_id access + # nodes 已经在上面转换为字典格式 + raw_nodes_data = file_data.get('nodes', {}) + RAW_NODES_DATA[scenario.case_id] = raw_nodes_data + + # Store metadata for initial values access + FILE_METADATA[scenario.case_id] = metadata + + logger.info(f"Successfully parsed case file: {scenario.case_id}, nodes: {len(scenario.nodes)}, edges: {len(scenario.edges)}") + except Exception as e: + logger.error(f"Failed to load case file: {str(e)}", exc_info=True) + raise HTTPException(status_code=500, detail=f"Failed to load case file: {str(e)}") + + # Initialize node state and load values + _initialize_node_values(scenario, raw_nodes_data, metadata) + + SCENARIOS[scenario.case_id] = scenario + simulator = ToolSimulator() + SIMULATORS[scenario.case_id] = simulator + + 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'])}") + + # 生成初始观察信息(进入密室后看到的环境) + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + ''' + initial_observation的格式: + { + "narrative": scenario.intro_narrative, + "available_entities": available_entities # 使用统一的实体列表 + "available_information": available_information # 可用的初始信息(只包含 init_inputs) + } + ''' + + return { + "ok": True, + "message": f"Case loaded from {case_file_path}", + "case_id": scenario.case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果没有提供 case_file_path,但提供了 case_id,则尝试从内存重置 + if case_id and case_id in SCENARIOS: + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + metadata = FILE_METADATA.get(case_id, {}) + + # Reset dynamic fields and re-apply progressive reveal + # 重新初始化节点状态(包括渐进式暴露) + _initialize_node_values(scenario, raw_nodes_data, metadata) + + 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'])}") + + # 生成初始观察信息 + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + + return { + "ok": True, + "message": f"Case {case_id} reset.", + "case_id": case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果既没有 case_file_path,也没有在内存中找到,返回错误 + raise HTTPException( + status_code=400, + detail="Must provide case_file_path to load a new case, or use case_id to reset an existing case." + ) + +class InvestigateRequest(BaseModel): + node_id: str + +@app.post("/env/{case_id}/investigate") +def investigate(case_id: str, req: InvestigateRequest): + """ + Investigates a Tool or Item to reveal detailed information. + + - For Tools: Returns detailed interface information (inputs/outputs) needed to call the tool + - For Items: Returns content value and triggers hidden item drops + """ + logger.info(f"Investigate request - case_id: {case_id}, node_id: {req.node_id}") + STATS["investigates"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + node = scenario.nodes[req.node_id] + + if not node.is_revealed: + logger.warning(f"Attempt to investigate hidden node: {req.node_id}") + return {"ok": False, "error": "Node is not visible yet."} + + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + newly_revealed = [] + + # 处理 Tool 的 investigate + if node.type == "Tool": + logger.info(f"Investigating tool: {req.node_id}") + + # 返回工具的详细接口信息 + # id 字段使用 node.id(节点唯一标识),agent 用这个字段识别和调用具体的节点 + # template_id 是工具类型标识符,Agent 内部用于判断工具特性(如 terminal 类工具参数可选) + # 注意:只过滤输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口),这些端口仅用于控制掉落,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + # 【端口上游依赖提示 & 初始值直接给出】 + # 针对参数语义模糊(全为数字类型)的工具,在 investigate 返回信息中标注 + # 哪个输入端口来自哪个上游节点(upstream_from)。 + # 对于所有工具:若该节点不是纯源头节点(有任意数据流入边), + # 且某个端口没有上游入边(值来自初始可见参数),则直接给出该端口的 golden input 值。 + AMBIGUOUS_TOOLS = { + "num_base_convert", "calc_modexp", "calc_modexp_int", + "calc_inv_mod", "calc_inv_mod_int", "crypto_rsa_decrypt_hex", "geo_haversine" + } + # Terminal 类工具自带参数对错反馈机制,玩家/模型可自行试错, + # 无需在 investigate 时直接暴露 init_value + SELF_FEEDBACK_TOOLS = { + "terminal_1", "terminal_2", + "Logic Terminal", "Math Terminal", "Encryption Terminal", "Sequence Terminal" + } + _template_id_for_hint = raw_nodes_data.get(node.id, {}).get("template_id", "") + # 构建数据流入边映射(对所有工具):{target_port -> (source_node_id, source_port)} + _upstream_map = {} + for _edge in scenario.edges: + if (_edge.target_id == node.id + and _edge.connection_type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM] + and _edge.target_port is not None): + _upstream_map[_edge.target_port] = (_edge.source_id, _edge.source_port) + # 判断该节点是否有任意数据流入边(即不是纯源头节点) + _has_any_upstream = len(_upstream_map) > 0 + # 判断该节点是否有任意入边(包括 ITEM/HIDDEN_ITEM 掉落边) + # 有任意入边(含掉落边)但无数据流入边的节点,其输入来自初始可见参数,应直接给出 + _has_any_edge = any(_edge.target_id == node.id for _edge in scenario.edges) + # 构建 inputs 列表 + _inputs_list = [] + for p in node.inputs: + if p.type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + continue + port_dict = {"name": p.name, "type": p.type, "description": p.description} + if p.name in _upstream_map: + # 该端口有上游数据流依赖,且属于语义模糊工具 → 标注来源 + if _template_id_for_hint in AMBIGUOUS_TOOLS: + src_node_id, src_port = _upstream_map[p.name] + port_dict["upstream_from"] = f"{src_node_id}.{src_port}" if src_port else src_node_id + elif _has_any_edge and _template_id_for_hint not in SELF_FEEDBACK_TOOLS: + # 该节点有任意入边,但此端口没有数据流入边 → 值来自初始可见参数,直接给出 + # 排除自带反馈机制的 terminal 类工具(它们通过执行结果反馈对错,无需提前暴露参数值) + golden_val = node.golden_input_values.get(p.name) + if golden_val is not None: + port_dict["init_value"] = golden_val + _inputs_list.append(port_dict) + + tool_details = { + "id": node.id, # 节点 ID,用于唯一标识和调用这个具体节点 + "type": "Tool", + "inputs": _inputs_list, + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id 用于 Agent 内部判断工具类型(不会展示给被测模型) + if node.id in raw_nodes_data: + template_id = raw_nodes_data[node.id].get('template_id') + if template_id: + tool_details["_template_id"] = template_id # 使用下划线前缀标记为内部字段 + + # 只在 name 非空时添加 + # if node.name: + # tool_details["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_details["description"] = node.description + + # 添加 narrative 字段(如果存在) + if node.id in raw_nodes_data: + narrative = raw_nodes_data[node.id].get('narrative') + if narrative: + tool_details['narrative'] = narrative + + # 不再返回 init_values,避免泄漏答案 + # investigate 只应该返回工具的接口定义,不应该暴露初始值 + + # 【新增】检查该 Tool 是否有待触发的 HIDDEN_ITEM 掉落 + # 如果该工具已按照 golden_input 正确执行,且有 HIDDEN_ITEM 输出边,则触发掉落 + if node.has_hidden_item_ready: + logger.info(f"Tool has HIDDEN_ITEM ready - triggering passive drop for: {req.node_id}") + + # 遍历该工具的所有 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + # 重置标志,已经触发过了,避免重复 + node.has_hidden_item_ready = False + + logger.info(f"Tool investigation successful - node: {req.node_id}, revealed: {len(newly_revealed)}") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Tool", + "details": tool_details + } + + # 如果有新掉落的节点,添加到响应中 + if newly_revealed: + result["newly_revealed"] = newly_revealed + + return result + + # 处理 Item 的 investigate + elif node.type == "Item": + logger.info(f"Investigating item: {req.node_id}") + + # 【第一步】检查该 Item 是否有需要参数的输入端口 + # 如果有,且尚未通过 use_item 验证,则不返回内容,只返回参数要求 + required_inputs = [] + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + inputs_info = raw_node.get('inputs', []) + required_inputs = [ + { + "name": inp.get("name"), + "type": inp.get("type"), + "description": inp.get("description", "") + } + for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + # 如果有 required_inputs 且尚未通过 use_item 验证(if_success == False) + # 则不返回内容,只返回参数要求提示 + if required_inputs and not node.if_success: + logger.info(f"Item has required inputs and not yet unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "required_inputs": required_inputs + } + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + param_names = ', '.join([inp['name'] for inp in required_inputs]) + 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}" + + return result + + # 【新增】如果有 required_inputs 且已经通过 use_item 验证(if_success == True) + # 则返回提示:该节点已经被成功解决 + if required_inputs and node.if_success: + logger.info(f"Item has required inputs and already unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "message": "This item has already been successfully unlocked by you." + } + return result + + # 【第二步】该 Item 没有 required_inputs 或已通过验证,返回内容 + # 1. 返回 Item 的 golden_output_values(即 Item 的内容) + # 注意:某些 Item 仅用于触发 HIDDEN_ITEM 掉落,没有实际内容 + has_actual_content = bool(node.golden_output_values) or node.content is not None + content = node.golden_output_values if node.golden_output_values else node.content + + # 【关键】将 golden_output_values 追加到 actual_outputs_history,标记该 Item 已被 investigate + # 这样在渐进式暴露时,这些值才会被加入可见值集合 + # 即使是空字典(仅触发 HIDDEN_ITEM 的 Item),也要记录,以便渐进式暴露逻辑知道该 Item 已被调查 + if node.golden_output_values is not None: + node.actual_outputs_history.append(dict(node.golden_output_values)) + + # 2. Trigger Hidden Item Drops (Passive Drop) + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + logger.info(f"Item investigation successful - node: {req.node_id}, has_content: {has_actual_content}, revealed: {len(newly_revealed)}") + + # 【渐进式暴露】旧机制(基于 golden_input)已禁用 + # 现在完全由 ITEM/HIDDEN_ITEM 边触发控制节点可见性 + # 上面的 HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, node.golden_output_values or {}, node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # logger.info(f"Progressive reveal after Item investigate: {len(progressive_revealed)} nodes now ready") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Item" + } + + # 只在有实际内容时才添加 content 字段 + # 对于仅触发 HIDDEN_ITEM 掉落的 Item,不返回 content 字段,避免返回 None 或空字典让模型困惑 + if has_actual_content: + result["content"] = content + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型通过 investigate 获得内容后,需要自己识别这是否是胜利字符串 + + return result + + else: + logger.warning(f"Attempt to investigate unknown node type: {req.node_id} (type: {node.type})") + return {"ok": False, "error": f"Cannot investigate node type: {node.type}"} + +class ToolCallRequest(BaseModel): + node_id: str # 使用 node_id 精确指定要调用的节点 + arguments: Dict[str, Any] + +@app.post("/env/{case_id}/tool_call") +def tool_call(case_id: str, req: ToolCallRequest): + """Executes a tool and triggers item drops.""" + logger.info(f"Tool call request - case_id: {case_id}, node_id: {req.node_id}, args: {list(req.arguments.keys())}") + STATS["tool_calls"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + + # 通过 node_id 精确查找节点 + node_id = req.node_id + if node_id not in scenario.nodes: + logger.error(f"Node not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + tool_node = scenario.nodes[node_id] + + if not tool_node: + logger.error(f"Tool not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Tool not found") + + if not tool_node.is_revealed: + logger.warning(f"Attempt to call hidden tool: {node_id}") + return {"ok": False, "error": "Tool is not visible yet."} + + if tool_node.type != "Tool": + logger.warning(f"Attempt to call non-tool node: {node_id} (type: {tool_node.type})") + return {"ok": False, "error": "Only tools can be called."} + + # 1. Execute Tool (Real Execution via Simulator) + simulator = SIMULATORS[case_id] + + # Get tool name from template_id if available, otherwise use node name + tool_name = tool_node.name + if case_id in RAW_NODES_DATA and node_id in RAW_NODES_DATA[case_id]: + template_id = RAW_NODES_DATA[case_id][node_id].get('template_id') + if template_id: + tool_name = template_id + + # 文件处理工具和 Terminal 需要验证输入并返回预先计算的输出 + # 传递节点的实际输入输出值(从 DAG 执行后填充的数据) + tool_arguments = dict(req.arguments) # Make a copy + + # 传递节点的 golden values(从 JSON 的 inputs[].value 和 outputs[].value 加载) + # 用于在评测阶段验证被测模型传入的参数是否正确 + if tool_node.golden_input_values: + tool_arguments['_golden_inputs'] = tool_node.golden_input_values + if tool_node.golden_output_values: + tool_arguments['_golden_outputs'] = tool_node.golden_output_values + + logger.debug(f"Executing tool {tool_name} (node: {tool_node.name}) with args {tool_arguments}") + + try: + output_values = simulator.execute(tool_name, tool_arguments) + logger.info(f"Tool invoked - {tool_name}: {list(output_values.keys())}") + except Exception as e: + logger.error(f"Tool execution failed - {tool_name}: {str(e)}", exc_info=True) + return {"ok": False, "error": f"Tool execution failed: {str(e)}"} + + # 检查验证结果(精细化错误反馈) + validation = output_values.pop("_validation", {"valid": True}) + + if not validation["valid"]: + # 根据错误类型构造友好的错误消息 + error_type = validation.get("error_type") + + if error_type == "missing_required": + missing = validation.get("missing_params", []) + error_msg = f"Error: Missing required parameters {', '.join(missing)}" + + elif error_type == "type_error": + param = validation.get("param_name") + message = validation.get("message", "Parameter type error") + error_msg = f"Error: {message}" + + elif error_type == "incomplete_optional": + provided = validation.get("provided_params", []) + missing = validation.get("missing_params", []) + error_msg = ( + f"Hint: You provided some parameters ({', '.join(provided)}), " + f"but may also need: {', '.join(missing)}.\n" + f"Trying to provide these parameters together might yield better results." + ) + + elif error_type == "value_mismatch": + param = validation.get("param_name") + hint = validation.get("hint", "Parameter value may be incorrect") + error_msg = f"Hint: {hint}.\nPlease check if this parameter value meets the requirements." + + else: + error_msg = validation.get("hint") or validation.get("message", "Parameter validation failed") + + logger.info(f"Tool validation failed - {tool_name}: {error_type}") + return { + "ok": False, + "error": error_msg, + "error_type": error_type + } + + # Simulate success + tool_node.if_success = True + + # 【关键】将本次执行的输出值追加到历史列表(用于渐进式暴露判断) + # 每次调用都会记录,不会覆盖之前的执行结果 + tool_node.actual_outputs_history.append(dict(output_values)) + + # 2. 检查是否应该触发掉落(只有输入参数正确时才掉落) + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, tool_node.golden_input_values) + + newly_revealed = [] + investigate_hints = [] # 提示模型哪些节点可以 investigate 来发现隐藏内容 + + if inputs_match_golden: + logger.info(f"✓ Tool inputs match golden - node: {node_id}, triggering drops") + + # 检查该工具是否有 ITEM 或 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == tool_node.id: + target_node = scenario.nodes[edge.target_id] + + # ITEM 边:立即掉落(主动掉落) + if edge.connection_type == InterfaceType.ITEM: + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from {node_id})") + + # HIDDEN_ITEM 边:不立即掉落,标记并提示(被动掉落) + elif edge.connection_type == InterfaceType.HIDDEN_ITEM: + # 标记该工具有待触发的 HIDDEN_ITEM 掉落 + tool_node.has_hidden_item_ready = True + + # 提示模型可以 investigate 这个工具来发现隐藏内容 + hint_info = { + "tool_id": tool_node.id, + "hint": f"Tool '{tool_node.id}' seems to hide something, try investigating it to discover more information" + } + # if tool_node.name: + # hint_info["tool_name"] = tool_node.name + + investigate_hints.append(hint_info) + logger.info(f"HIDDEN_ITEM ready: {tool_node.id} -> {target_node.id} (will drop on investigate)") + else: + logger.info(f"✗ Tool inputs do NOT match golden - node: {node_id}, no drops triggered") + + response = { + "ok": True, + "message": "Tool invoked", + "output_values": output_values # Return raw outputs to Agent + } + + # 【新增】对源头节点进行参数验证反馈 + # 源头节点:没有数据流入边的节点,这些节点的参数需要模型自己推理 + # 验证模型使用的参数是否正确,并提供明确的反馈 + if _is_source_node(node_id, scenario) and tool_node.golden_input_values: + validation_feedback = _get_parameter_validation_feedback(req.arguments, tool_node.golden_input_values) + + if validation_feedback["all_correct"]: + # 用户提交了全部 golden 参数且全部正确 + response["parameter_feedback"] = { + "status": "correct", + "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." + } + logger.info(f"✓ Source node parameters all correct - node: {node_id}") + elif validation_feedback["incorrect_params"]: + # 有提交了但值错误的参数,只对这些参数给出反馈 + incorrect_list = [] + for param_name in validation_feedback["incorrect_params"]: + incorrect_list.append(f" - Parameter '{param_name}' is incorrect") + + correct_info = "" + if validation_feedback["correct_params"]: + correct_info = f"\n✓ Correct parameters: {', '.join(validation_feedback['correct_params'])}" + + response["parameter_feedback"] = { + "status": "incorrect", + "message": ( + f"⚠️ Some parameters are incorrect:\n" + + "\n".join(incorrect_list) + + correct_info + + 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." + ), + "incorrect_params": validation_feedback["incorrect_params"], + "correct_params": validation_feedback["correct_params"] + } + logger.info(f"✗ Source node parameters incorrect - node: {node_id}, incorrect: {validation_feedback['incorrect_params']}") + # else: 部分提交且全部正确 → 不给任何 parameter_feedback,避免对未提交的参数发表意见 + + # 检查工具调用是否完全正确(输出与 golden outputs 匹配) + # 用于给模型正向反馈,让它知道这个工具已经正确调用过,避免重复调用 + # 注意:只有当输出完全匹配时才标记为 correct,不会在错误时提供具体错误信息 + # if tool_node.golden_output_values and output_values: + # is_correct = True + # for port_name, expected_value in tool_node.golden_output_values.items(): + # actual_value = output_values.get(port_name) + # if str(actual_value) != str(expected_value): + # is_correct = False + # break + + # if is_correct: + # response["tool_call_correct"] = True + # logger.info(f"✓ Tool called with correct result - node: {node_id}") + + # 只在有新内容掉落时才返回 newly_revealed + if newly_revealed: + response["newly_revealed"] = newly_revealed + + # 添加 investigate 提示(对于有待触发 HIDDEN_ITEM 掉落的工具) + if investigate_hints: + response["investigate_hints"] = investigate_hints + + # 3. 渐进式暴露机制 - 现在完全由 ITEM/HIDDEN_ITEM 边控制 + # 旧机制(基于 golden_input 检查)已被禁用 + # 新机制中,节点的可见性只由 ITEM/HIDDEN_ITEM 边触发决定 + # 上面的 ITEM/HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, output_values, tool_node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # response["newly_revealed"] = newly_revealed + # logger.info(f"Progressive reveal: {len(progressive_revealed)} nodes now ready") + + # Check if this is the win node + if node_id == scenario.win_node_id: + # 验证输出值是否等于预期的胜利值 + # 从节点的 golden_output_values 中获取预期值(在 _initialize_node_values 时从 JSON 加载) + expected_outputs = tool_node.golden_output_values + + # 检查实际输出是否与预期输出匹配 + is_correct = False + victory_string = None + mismatch_info = [] + + if expected_outputs and output_values: + # 检查每个预期输出端口的值是否匹配 + is_correct = True + for port_name, expected_value in expected_outputs.items(): + actual_value = output_values.get(port_name) + if actual_value != expected_value: + is_correct = False + mismatch_info.append(f"Port '{port_name}': expected '{expected_value}', actual '{actual_value}'") + logger.warning(f"Win node output mismatch - port: {port_name}, expected: {expected_value}, actual: {actual_value}") + + # 如果所有输出都匹配,使用第一个输出作为胜利字符串 + if is_correct and output_values: + victory_string = list(output_values.values())[0] + else: + logger.warning(f"Win node called but missing output values - expected: {expected_outputs}, actual: {output_values}") + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型调用工具获得输出后,需要自己识别这是否是胜利字符串并提交 + if is_correct: + logger.info(f"🎯 Win node called with correct output - case: {case_id}, node: {node_id}, victory: {victory_string}") + else: + logger.info(f"❌ Win node called with incorrect output - case: {case_id}, node: {node_id}") + + return response + +class UseItemRequest(BaseModel): + node_id: str = Field(..., description="The ID of the Item node to use (must be Item type)") + arguments: Dict[str, Any] = Field(default_factory=dict, description="Input arguments to provide to the item") + +@app.post("/env/{case_id}/use_item") +def use_item(case_id: str, req: UseItemRequest): + """ + Use an Item node by providing input arguments. + + This is specifically for Item nodes that require parameters to be "unlocked" or "activated", + such as containers that need a password/fingerprint. + + - Validates that the node is of type Item + - Checks if provided arguments match the item's golden_input_values + - If match: triggers ITEM-type edge drops and returns the item's content + - If not match: returns error message + """ + logger.info(f"Use item request - case_id: {case_id}, node_id: {req.node_id}, args: {req.arguments}") + STATS["use_items"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + item_node = scenario.nodes[req.node_id] + + if not item_node.is_revealed: + logger.warning(f"Attempt to use hidden item: {req.node_id}") + return {"ok": False, "error": "Item is not visible yet."} + + if item_node.type != "Item": + logger.warning(f"Attempt to use non-item node: {req.node_id} (type: {item_node.type})") + return {"ok": False, "error": "Only Item nodes can be used with use_item. Tools should be called with tool_call."} + + # 【新增】检查该 Item 是否已经被成功解锁 + # 如果已经被正确使用过,直接返回成功提示 + if item_node.if_success: + logger.info(f"Item already unlocked, returning success message: {req.node_id}") + return { + "ok": True, + "message": "This item has already been successfully unlocked by you." + } + + # 检查该 Item 是否真的需要通过 use_item 提供参数 + # 只有当 Item 有非 Item/Hidden_Item 类型的输入时,才应该使用 use_item + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + non_hidden_inputs = [ + inp for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + if not non_hidden_inputs: + # 该 Item 不需要参数,应该只使用 investigate + logger.warning(f"Attempt to use_item on a node that doesn't require parameters: {req.node_id}") + return { + "ok": False, + "error": "This item does not require parameters. Please use investigate to examine the item directly." + } + + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, item_node.golden_input_values) + + if not inputs_match_golden: + logger.info(f"✗ Item inputs do NOT match golden - node: {req.node_id}") + # 提供更详细的错误信息,帮助 Agent 理解问题 + # 只显示非 Item/Hidden_Item 类型的参数(Hidden_Item 由系统自动处理) + expected_params = [] + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + expected_params = [ + inp.get("name") for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + provided_params = list(req.arguments.keys()) if req.arguments else [] + + # 检查参数名是否匹配 + if set(expected_params) == set(provided_params): + # 参数名正确但值不匹配 - 不泄漏正确的值 + error_msg = f"Parameter names are correct, but the parameter values are incorrect. Please try using different parameter values." + else: + error_msg = f"Parameter names do not match. Expected parameter names: {expected_params}, you provided: {provided_params}." + + return { + "ok": False, + "error": error_msg + } + + logger.info(f"✓ Item inputs match golden - node: {req.node_id}, activating item") + + # 标记该 Item 已被正确使用 + item_node.if_success = True + + # 将 golden_output_values 追加到 actual_outputs_history + if item_node.golden_output_values: + item_node.actual_outputs_history.append(dict(item_node.golden_output_values)) + + # 触发 ITEM 类型边的掉落 + newly_revealed = [] + for edge in scenario.edges: + if edge.source_id == item_node.id and edge.connection_type == InterfaceType.ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from use_item on {req.node_id})") + + # 检查是否为 Win Node + win_node_id = scenario.win_node_id + is_win_node = (req.node_id == win_node_id) + + # 构建返回结果 + result = { + "ok": True, + "message": "Item used successfully.", + "content": item_node.golden_output_values if item_node.golden_output_values else None + } + + # 获取 narrative(如果存在) + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + narrative = raw_nodes_data[req.node_id].get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 如果是 Win Node,只记录日志 + if is_win_node: + logger.info(f"Win node (Item) unlocked via use_item - case: {case_id}, node: {req.node_id}") + + return result + + +class SubmitAnswerRequest(BaseModel): + answer: str = Field(..., description="The victory string to submit") + +@app.post("/env/{case_id}/submit_answer") +def submit_answer(case_id: str, req: SubmitAnswerRequest): + """ + 提交答案接口 + 被测模型在获得胜利字符串提示后,需要调用此接口提交答案 + """ + logger.info(f"Submit answer request - case_id: {case_id}, answer: {req.answer}") + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + + # 获取 win_node 的 golden_output_values + if not scenario.win_node_id: + logger.error(f"No win node defined for case: {case_id}") + return { + "ok": False, + "error": "This case has no victory node defined" + } + + win_node = scenario.nodes.get(scenario.win_node_id) + if not win_node: + logger.error(f"Win node not found: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node does not exist" + } + + # 获取正确的胜利字符串(取第一个 golden_output_value) + if win_node.golden_output_values: + correct_answer = list(win_node.golden_output_values.values())[0] + else: + logger.error(f"Win node has no golden_output_values: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node has no correct answer" + } + + # 验证提交的答案 + if req.answer == correct_answer: + logger.info(f"🎉 CORRECT ANSWER SUBMITTED - case: {case_id}, answer: {req.answer}") + return { + "ok": True, + "is_win": True, + "victory_message": f"🎉 Congratulations on successfully escaping the room! Your answer is correct: {req.answer}" + } + else: + logger.info(f"❌ INCORRECT ANSWER SUBMITTED - case: {case_id}, submitted: {req.answer}, correct: {correct_answer}") + return { + "ok": True, + "is_win": False, + "error": f"The submitted answer is incorrect. You submitted: {req.answer}" + } + +if __name__ == "__main__": + + uvicorn.run(app, host="0.0.0.0", port=8000) \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-7499421d/environment/puzzle/upstream/simulator.py b/tasks/agentescape-25-skeleton-7499421d/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-25-skeleton-7499421d/environment/puzzle/upstream/simulator.py @@ -0,0 +1,2911 @@ +import hashlib +import hmac +import base64 +import binascii +import zlib +import json +import uuid +import math +import re +from typing import Dict, Any, List + +class ToolSimulator: + def __init__(self): + """工具模拟器 + + 文件处理工具(zip_unzip, zip_unzip_file, zip_unzip_item, json_get, csv_query, + regex_search, graph_shortest_path)不需要真实文件系统。 + 这些工具只验证输入参数,然后返回预先初始化好的 golden_outputs。 + """ + self.tool_map = { + # 数论 + "calc_bigmul": self.calc_bigmul, + "calc_modexp": self.calc_modexp, + "calc_modexp_int": self.calc_modexp_int, + "calc_gcd": self.calc_gcd, + "calc_gcd_int": self.calc_gcd_int, + "calc_inv_mod": self.calc_inv_mod, + "calc_inv_mod_int": self.calc_inv_mod_int, + + # 哈希 + "hash_sha256": self.hash_sha256, + "hash_md5": self.hash_md5, + "hmac_sha256": self.hmac_sha256, + + # 编码 + "base64_decode": self.base64_decode, + "base64_encode": self.base64_encode, + "hex_decode": self.hex_decode, + "hex_encode": self.hex_encode, + "zlib_inflate": self.zlib_inflate, + "zlib_deflate": self.zlib_deflate, + + # 文件 + "zip_unzip": self.zip_unzip, + "zip_unzip_file": self.zip_unzip_file, + "zip_unzip_item": self.zip_unzip_item, + "regex_search": self.regex_search, + "json_get": self.json_get, + "csv_query": self.csv_query, + "code_py_exec": self.code_py_exec, + + # 图 + "graph_shortest_path": self.graph_shortest_path, + + # 加解密 (简化模拟) + "crypto_aes_cbc_decrypt": self.crypto_aes_cbc_decrypt, + "crypto_rsa_decrypt_hex": self.crypto_rsa_decrypt_hex, + + # 其他 + "num_base_convert": self.num_base_convert, + "time_convert": self.time_convert, + "checksum_crc32": self.checksum_crc32, + "geo_haversine": self.geo_haversine, + "otp_totp_generate": self.otp_totp_generate, + "unicode_norm": self.unicode_norm, + "text_bidi_sanitize": self.text_bidi_sanitize, + "text_xor_hex": self.text_xor_hex, + "text_rotN": self.text_rotN, + "luhn_check": self.luhn_check, + "iban_validate": self.iban_validate, + + # 物理 + "matter_synthesizer": self.matter_synthesizer, + + # 终端机 + "terminal_1": self.terminal_1, + "terminal_2": self.terminal_2, + "Logic Terminal": self.logic_terminal, + "Math Terminal": self.math_terminal, + "Encryption Terminal": self.crypt_terminal, + "Sequence Terminal": self.sequence_terminal + } + + def execute(self, tool_name: str, inputs: Dict[str, Any]) -> Dict[str, Any]: + if tool_name not in self.tool_map: + # Fallback for unknown tools: return dummy outputs based on expected output types + # This should ideally not happen if all tools are implemented + return {} + + try: + return self.tool_map[tool_name](inputs) + except Exception as e: + print(f"Error executing {tool_name}: {e}") + # Return empty or error indication? For generation, we might want to fail hard or return dummy. + # For now, return dummy to keep flow going, but log error. + return {} + + # --- Implementations --- + + def calc_bigmul(self, inputs): + # Check if required parameters are present + if "a" not in inputs or "b" not in inputs: + raise ValueError("Missing required parameters 'a' and/or 'b'") + + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + return {"product": str(a * b)} + except (ValueError, TypeError) as e: + raise ValueError(f"Failed to convert parameters to integers: {str(e)}") + + def calc_modexp(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + try: + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if isinstance(base, str): + base = int(base) + elif not isinstance(base, int): + raise ValueError("Parameter 'base' must be a string or integer") + + if isinstance(exp, str): + exp = int(exp) + elif not isinstance(exp, int): + raise ValueError("Parameter 'exp' must be a string or integer") + + if isinstance(mod, str): + mod = int(mod) + elif not isinstance(mod, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": str(pow(base, exp, mod))} + + def calc_modexp_int(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["base"], int): + raise ValueError("Parameter 'base' must be an integer") + if not isinstance(inputs["exp"], int): + raise ValueError("Parameter 'exp' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": pow(base, exp, mod)} + + def calc_gcd(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + # 计算 GCD 并返回字符串格式(符合 Big_Int 输出类型) + result = math.gcd(a, b) + return {"gcd": str(result)} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def calc_gcd_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["b"], int): + raise ValueError("Parameter 'b' must be an integer") + + # 获取参数 + a = inputs["a"] + b = inputs["b"] + + return {"gcd": math.gcd(a, b)} + + def calc_inv_mod(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + m = inputs["mod"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(m, str): + m = int(m) + elif not isinstance(m, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": str(pow(a, -1, m))} + except ValueError as e: + # 模逆不存在时,返回一个特殊值(用于数据传递) + # 在 DAG 生成阶段,这允许数据流继续 + return {"inv": str(a)} + + def calc_inv_mod_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + a = inputs["a"] + m = inputs["mod"] + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": pow(a, -1, m)} + except ValueError as e: + raise ValueError(f"Modular inverse does not exist: {str(e)}") + + def hash_sha256(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.sha256(text.encode()).hexdigest()} + + def hash_md5(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.md5(text.encode()).hexdigest()} + + def hmac_sha256(self, inputs): + # 参数检查 + if "hex_key" not in inputs: + raise ValueError("Missing required parameter: hex_key") + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["hex_key"], str): + raise ValueError("Parameter 'hex_key' must be a string") + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + try: + key = bytes.fromhex(inputs["hex_key"]) + text = inputs["text"].encode() + return {"hex": hmac.new(key, text, hashlib.sha256).hexdigest()} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def base64_decode(self, inputs): + # 参数检查 + if "data" not in inputs: + raise ValueError("Missing required parameter: data") + + # 类型检查 + if not isinstance(inputs["data"], str): + raise ValueError("Parameter 'data' must be a string") + + data = inputs["data"] + try: + return {"bytes_hex": binascii.hexlify(base64.b64decode(data)).decode()} + except Exception as e: + raise ValueError(f"Base64 decode error: {str(e)}") + + def base64_encode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"b64": base64.b64encode(bytes.fromhex(hex_data)).decode()} + except Exception as e: + raise ValueError(f"Base64 encode error: {str(e)}") + + def hex_decode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"text": bytes.fromhex(hex_data).decode('utf-8', errors='ignore')} + except Exception as e: + raise ValueError(f"Hex decode error: {str(e)}") + + def hex_encode(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + try: + return {"hex": text.encode().hex()} + except Exception as e: + raise ValueError(f"Hex encode error: {str(e)}") + + + # 到此处实现已经更新 + + def zlib_inflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("Parameter 'hex' must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("Missing required parameter: hex") + + try: + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空字符串 + if not hex_data: + raise ValueError("Empty hex string provided") + + # 检查十六进制字符串的有效性 + if len(hex_data) % 2 != 0: + raise ValueError("Hex string must have even length") + + # 检查是否只包含有效的十六进制字符 + if not all(c in '0123456789abcdefABCDEF' for c in hex_data): + raise ValueError("Invalid hex string provided") + + # 尝试解压缩 + return {"text": zlib.decompress(bytes.fromhex(hex_data)).decode('utf-8')} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hex string provided") from e + raise ValueError(f"Invalid zlib data: {e}") from e + except Exception as e: + raise RuntimeError(f"Failed to inflate data: {e}") from e + + def zlib_deflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("Parameter 'text' must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("Missing required parameter: text") + + try: + # 压缩文本 + return {"hex": zlib.compress(text.encode('utf-8')).hex()} + except Exception as e: + raise RuntimeError(f"Failed to deflate data: {e}") from e + + # --- File Operations --- + + def zip_unzip(self, inputs): + """ZIP 解压工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"files": golden_outputs.get("files", "")} + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return {"files": golden_outputs.get("files", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "files" in golden_outputs: + # 验证必需参数 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 检查类型 + if has_zip_id and not isinstance(zip_id, str): + return {"error": "Parameter 'zip_id' must be a string type"} + if has_password and not isinstance(password, str): + return {"error": "Parameter 'password' must be a string type"} + + # 验证输入是否与预期匹配 + if golden_inputs: + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return {"files": golden_outputs["files"]} + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + # 没有golden_inputs但有golden_outputs,直接返回输出 + return {"files": golden_outputs["files"]} + + # 如果没有预期输出,返回空结果 + return {"files": ""} + + def regex_search(self, inputs): + """正则搜索工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"matches": golden_outputs.get("matches", "[]")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "matches" in golden_outputs: + # 提取实际参数 + pattern = inputs.get("pattern") + file_id = inputs.get("file_id") + text = inputs.get("text") + + # 1. 检查必需参数 + if pattern is None: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["pattern"], + "message": "Missing required parameter 'pattern'" + } + } + + # 类型检查 + if not isinstance(pattern, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "pattern", + "message": "Parameter 'pattern' must be a string type" + } + } + if file_id is not None and not isinstance(file_id, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if text is not None and not isinstance(text, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "text", + "message": "Parameter 'text' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合 + provided_params = {} + if pattern is not None: + provided_params["pattern"] = pattern + if file_id is not None: + provided_params["file_id"] = file_id + if text is not None: + provided_params["text"] = text + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数(关键改进) + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_pattern = golden_inputs.get("pattern") + expected_file_id = golden_inputs.get("file_id") + expected_text = golden_inputs.get("text") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_pattern is not None: + if str(pattern) != str(expected_pattern): + incorrect_params.append("pattern") + else: + correct_params.append("pattern") + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_text is not None: + if str(text) != str(expected_text): + incorrect_params.append("text") + else: + correct_params.append("text") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "matches": "[]", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "matches": golden_outputs["matches"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空列表 + return {"matches": "[]"} + + def json_get(self, inputs): + """JSON 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"values": golden_outputs.get("values", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "values" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + jsonpath = inputs.get("jsonpath", "") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if jsonpath is not None and not isinstance(jsonpath, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "jsonpath", + "message": "Parameter 'jsonpath' must be a string type" + } + } + + # 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:jsonpath有默认值"") + provided_params = {} + if file_id is not None: + provided_params["file_id"] = file_id + if jsonpath != "": + provided_params["jsonpath"] = jsonpath + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_jsonpath = golden_inputs.get("jsonpath") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_jsonpath is not None: + if str(jsonpath) != str(expected_jsonpath): + incorrect_params.append("jsonpath") + else: + correct_params.append("jsonpath") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "values": "", + "_validation": validation_info + } + + # 所有验证通过,返回正确输出 + return { + "values": golden_outputs["values"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"values": ""} + + def csv_query(self, inputs): + """CSV 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"rows": golden_outputs.get("rows", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "rows" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + select_columns = inputs.get("select", "") + where_clause = inputs.get("where", "") + + # 1. 检查必需参数 + if file_id is None: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["file_id"], + "message": "Missing required parameter 'file_id'" + } + } + + # 类型检查 + if not isinstance(file_id, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if not isinstance(select_columns, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "select", + "message": "Parameter 'select' must be a string type" + } + } + if not isinstance(where_clause, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "where", + "message": "Parameter 'where' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:select和where有默认值"") + provided_params = {"file_id": file_id} + if select_columns != "": + provided_params["select"] = select_columns + if where_clause != "": + provided_params["where"] = where_clause + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_select = golden_inputs.get("select") + expected_where = golden_inputs.get("where") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_select is not None: + if str(select_columns) != str(expected_select): + incorrect_params.append("select") + else: + correct_params.append("select") + + if expected_where is not None: + if str(where_clause) != str(expected_where): + incorrect_params.append("where") + else: + correct_params.append("where") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "rows": "", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "rows": golden_outputs["rows"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"rows": ""} + + def graph_shortest_path(self, inputs): + """图最短路径工具 + + 如果有 _golden_outputs 或 _init_outputs,验证输入并返回预设输出。 + 否则执行真实的 Dijkstra 算法。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 检查是否在预设模式中(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + if golden_outputs and "path" in golden_outputs: + # 评测阶段但没有 golden_inputs,直接返回 outputs + if not golden_inputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 评测模式:验证输入参数是否匹配 golden 值 + src = inputs.get("src") + dst = inputs.get("dst") + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + + has_src = src is not None and src != "" + has_dst = dst is not None and dst != "" + + # 验证必需参数 + if not has_src or not has_dst: + missing = [] + if not has_src: + missing.append("src") + if not has_dst: + missing.append("dst") + return {"error": "Missing required parameters: " + ", ".join(missing)} + + # 类型检查 + if not isinstance(src, str): + return {"error": "Parameter 'src' must be a string"} + if not isinstance(dst, str): + return {"error": "Parameter 'dst' must be a string"} + + # 验证输入是否匹配期望值 + if golden_inputs: + expected_src = golden_inputs.get("src") + expected_dst = golden_inputs.get("dst") + expected_file_id = golden_inputs.get("file_id") + expected_graph_data = golden_inputs.get("graph_data") + + # 收集验证结果 + incorrect_params = [] + correct_params = [] + + # 检查必需参数是否匹配 + if expected_src is not None: + if str(src) != str(expected_src): + incorrect_params.append("src") + else: + correct_params.append("src") + + if expected_dst is not None: + if str(dst) != str(expected_dst): + incorrect_params.append("dst") + else: + correct_params.append("dst") + + # 检查可选参数(如果在 expected_inputs 中定义了) + if expected_file_id is not None: + if file_id != expected_file_id: + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_graph_data is not None: + if graph_data != expected_graph_data: + incorrect_params.append("graph_data") + else: + correct_params.append("graph_data") + + # 如果有参数不正确,返回详细的反馈 + if incorrect_params: + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 验证通过,返回预设的输出 + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 获取参数(真实执行路径) + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + # Support both src/dst (interface definition) and start/end (original implementation) + start = inputs.get("src") + end = inputs.get("dst") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + raise TypeError("file_id must be a string") + + if graph_data is not None and not isinstance(graph_data, str): + raise TypeError("graph_data must be a string") + + if start is not None and not isinstance(start, str): + raise TypeError("src/start must be a string") + + if end is not None and not isinstance(end, str): + raise TypeError("dst/end must be a string") + + # 检查必需参数 + if file_id is None and graph_data is None: + raise ValueError("Either file_id or graph_data must be provided") + + if start is None: + raise ValueError("src/start parameter is required") + + if end is None: + raise ValueError("dst/end parameter is required") + + # Get graph content + content = None + if file_id is not None: + # 尝试从 VFS 获取(如果存在) + if hasattr(self, 'vfs') and file_id in self.vfs: + content = self.vfs[file_id] + else: + # VFS 不存在或文件不在 VFS 中 + # 返回一个默认的空图结果,或者抛出错误提示需要 init_outputs + raise ValueError( + f"File '{file_id}' not found. For tools that require files, " + f"please provide init_outputs in the initial_values." + ) + elif graph_data is not None: + content = graph_data + + if content is None: + content = "{}" + + try: + # Parse graph data + graph = json.loads(content) + + # 类型检查 + if not isinstance(graph, dict): + raise TypeError("Graph data must be a dictionary") + + # If graph is not in the expected format, try to extract adjacency list + if "nodes" in graph and "edges" in graph: + # 验证nodes和edges的类型 + if not isinstance(graph["nodes"], list): + raise TypeError("Nodes must be a list") + + if not isinstance(graph["edges"], list): + raise TypeError("Edges must be a list") + + # Convert from nodes/edges format to adjacency list + adjacency_list = {} + for node in graph["nodes"]: + # 验证node类型 + if not isinstance(node, dict): + raise TypeError("Each node must be a dictionary") + + # Use node ID as key, not the entire node dictionary + node_id = node.get("id", "") + if node_id: + adjacency_list[node_id] = {} + + for edge in graph["edges"]: + # 验证edge类型 + if not isinstance(edge, dict): + raise TypeError("Each edge must be a dictionary") + + u = edge["from"] + v = edge["to"] + weight = edge.get("weight", 1) # Default to unweighted + + # 类型检查 + if not isinstance(u, str): + raise TypeError("Edge 'from' must be a string") + + if not isinstance(v, str): + raise TypeError("Edge 'to' must be a string") + + if not isinstance(weight, (int, float)): + raise TypeError("Edge weight must be a number") + + if u not in adjacency_list: + adjacency_list[u] = {} + if v not in adjacency_list: + adjacency_list[v] = {} + + adjacency_list[u][v] = weight + # If undirected, add reverse edge + if not edge.get("directed", False): + adjacency_list[v][u] = weight + elif isinstance(graph, dict): + # Already in adjacency list format + adjacency_list = graph + + # 验证邻接表结构 + for node, neighbors in adjacency_list.items(): + if not isinstance(neighbors, dict): + raise TypeError("Adjacency list must be a dictionary of dictionaries") + + for neighbor, weight in neighbors.items(): + if not isinstance(weight, (int, float)): + raise TypeError("Edge weights must be numbers") + else: + raise TypeError("Graph data must be a dictionary") + + # 检查起点和终点是否为空 + if not start: + raise ValueError("Start node cannot be empty") + + if not end: + raise ValueError("End node cannot be empty") + + # 检查起点和终点是否在图中 + if start not in adjacency_list: + raise ValueError(f"Start node '{start}' not found in graph") + + if end not in adjacency_list: + raise ValueError(f"End node '{end}' not found in graph") + + # Dijkstra's algorithm implementation + import heapq + + # Initialize distances and previous nodes + distances = {node: float('infinity') for node in adjacency_list} + previous = {node: None for node in adjacency_list} + distances[start] = 0 + + # Priority queue + pq = [(0, start)] + heapq.heapify(pq) + + while pq: + current_dist, current_node = heapq.heappop(pq) + + # If we've reached the end node, we can break early + if current_node == end: + break + + # Nodes can be added multiple times to the priority queue, but we only process them once + if current_dist > distances[current_node]: + continue + + # Explore neighbors + for neighbor, weight in adjacency_list[current_node].items(): + distance = current_dist + weight + + # If a shorter path is found + if distance < distances[neighbor]: + distances[neighbor] = distance + previous[neighbor] = current_node + heapq.heappush(pq, (distance, neighbor)) + + # Reconstruct the shortest path + path = [] + current = end + while current is not None: + path.append(current) + current = previous[current] + path.reverse() # Reverse to get from start to end + + # Check if path exists + if not path or path[0] != start: + return {"path": "[]", "cost": 0} + + return { + "path": json.dumps(path), + "cost": distances[end] + } + except json.JSONDecodeError as e: + raise ValueError(f"Invalid JSON in graph data: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in graph_shortest_path: {str(e)}") + + # --- Crypto (Simplified) --- + def crypto_aes_cbc_decrypt(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 (使用模板中定义的参数名) + hex_cipher = inputs.get("hex_cipher") + hex_key = inputs.get("hex_key") + hex_iv = inputs.get("hex_iv") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + + if hex_key is not None and not isinstance(hex_key, str): + raise TypeError("hex_key must be a string") + + if hex_iv is not None and not isinstance(hex_iv, str): + raise TypeError("hex_iv must be a string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + + if hex_key is None: + raise ValueError("hex_key parameter is required") + + if hex_iv is None: + raise ValueError("hex_iv parameter is required") + + from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes + from cryptography.hazmat.backends import default_backend + from cryptography.hazmat.primitives import padding + + try: + # Convert hex strings to bytes + ciphertext = bytes.fromhex(hex_cipher) + key = bytes.fromhex(hex_key) + iv = bytes.fromhex(hex_iv) + + # Validate key length (AES-128, AES-192, AES-256) + if len(key) not in [16, 24, 32]: + raise ValueError("Invalid key length. Must be 16, 24, or 32 bytes.") + + if len(iv) != 16: + raise ValueError("Invalid IV length. Must be 16 bytes.") + + # Create cipher object + cipher = Cipher( + algorithms.AES(key), + modes.CBC(iv), + backend=default_backend() + ) + + decryptor = cipher.decryptor() + + # Decrypt the ciphertext + padded_plaintext = decryptor.update(ciphertext) + decryptor.finalize() + + # Remove PKCS7 padding + unpadder = padding.PKCS7(128).unpadder() + plaintext = unpadder.update(padded_plaintext) + unpadder.finalize() + + # Return decrypted text + return {"text": plaintext.decode('utf-8', errors='ignore')} + except ValueError as e: + if "non-hexadecimal number found in fromhex()" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher, hex_key, or hex_iv") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in crypto_aes_cbc_decrypt: {str(e)}") + + def crypto_rsa_decrypt_hex(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_cipher = inputs.get("hex_cipher") + n = inputs.get("n") + d = inputs.get("d") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + if n is not None and not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + if d is not None and not isinstance(d, (int, str)): + raise TypeError("d must be an integer or string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + if n is None: + raise ValueError("n parameter is required") + if d is None: + raise ValueError("d parameter is required") + + try: + # Convert parameters to appropriate types + cipher_int = int(hex_cipher, 16) + n_int = int(n) if isinstance(n, str) else n + d_int = int(d) if isinstance(d, str) else d + + # RSA decryption: plaintext = ciphertext^d mod n + plaintext_int = pow(cipher_int, d_int, n_int) + + # Convert result to hex and then to text + plaintext_hex = hex(plaintext_int)[2:] + + # Pad with leading zero if odd length + if len(plaintext_hex) % 2 != 0: + plaintext_hex = '0' + plaintext_hex + + # Convert hex to bytes and then to text + try: + plaintext_bytes = bytes.fromhex(plaintext_hex) + plaintext_text = plaintext_bytes.decode('utf-8', errors='ignore') + except: + # If decoding fails, return hex representation + plaintext_text = plaintext_hex + + return {"text": plaintext_text} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in crypto_rsa_decrypt_hex: {str(e)}") + + # --- Others --- + def num_base_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + s = inputs.get("s") + from_base = inputs.get("from_base") + to_base = inputs.get("to_base") + + # 类型检查 - 接受 str 或 int + if s is not None and not isinstance(s, (str, int)): + raise TypeError("s must be a string or integer") + + if from_base is not None and not isinstance(from_base, (int, str)): + raise TypeError("from_base must be an integer") + + if to_base is not None and not isinstance(to_base, (int, str)): + raise TypeError("to_base must be an integer") + + # 检查必需参数 + if s is None: + raise ValueError("s parameter is required") + + if from_base is None: + raise ValueError("from_base parameter is required") + + if to_base is None: + raise ValueError("to_base parameter is required") + + try: + # Convert to int if needed + from_base = int(from_base) if isinstance(from_base, str) else from_base + to_base = int(to_base) if isinstance(to_base, str) else to_base + s_str = str(s) + + # 验证基数范围 + if from_base < 2 or from_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + if to_base < 2 or to_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + # Convert from source base to decimal + val = int(s_str, from_base) + + # Convert from decimal to target base + if to_base == 10: + result = str(val) + elif to_base == 16: + result = hex(val)[2:] + elif to_base == 8: + result = oct(val)[2:] + elif to_base == 2: + result = bin(val)[2:] + else: + # Generic base conversion for other bases + if val == 0: + result = "0" + else: + digits = "0123456789abcdefghijklmnopqrstuvwxyz" + result = "" + n = abs(val) + while n: + result = digits[n % to_base] + result + n //= to_base + if val < 0: + result = "-" + result + + return {"str": result} + except ValueError as e: + raise ValueError(f"Invalid number format: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in num_base_convert: {str(e)}") + + def time_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iso = inputs.get("iso") + timestamp = inputs.get("timestamp") + datetime_str = inputs.get("datetime") + from_tz = inputs.get("from_tz") + to_tz = inputs.get("to_tz") + format_str = inputs.get("format") + + # 类型检查 + if iso is not None and not isinstance(iso, str): + raise TypeError("iso must be a string") + + if timestamp is not None and not isinstance(timestamp, (str, int, float)): + raise TypeError("timestamp must be a string, integer, or float") + + if datetime_str is not None and not isinstance(datetime_str, str): + raise TypeError("datetime must be a string") + + if from_tz is not None and not isinstance(from_tz, str): + raise TypeError("from_tz must be a string") + + if to_tz is not None and not isinstance(to_tz, str): + raise TypeError("to_tz must be a string") + + if format_str is not None and not isinstance(format_str, str): + raise TypeError("format must be a string") + + # 设置默认值 + if from_tz is None: + from_tz = "UTC" + + if to_tz is None: + to_tz = "UTC" + + import datetime + import pytz + + # 验证时区参数 + try: + if from_tz: + pytz.timezone(from_tz) + if to_tz: + pytz.timezone(to_tz) + except Exception: + raise ValueError("Invalid timezone provided") + + try: + # Parse input time + dt = None + + if iso is not None: + # Parse ISO 8601 format + dt = datetime.datetime.fromisoformat(iso.replace('Z', '+00:00')) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=pytz.UTC) + elif timestamp is not None: + # Parse Unix timestamp + timestamp = float(timestamp) + dt = datetime.datetime.fromtimestamp(timestamp, pytz.UTC) + elif datetime_str is not None: + # Parse datetime string + # Try common formats + formats_to_try = [ + "%Y-%m-%d %H:%M:%S", + "%Y-%m-%d %H:%M:%S.%f", + "%Y-%m-%d", + "%m/%d/%Y %H:%M:%S", + "%m/%d/%Y" + ] + + parse_success = False + for fmt in formats_to_try: + try: + dt = datetime.datetime.strptime(datetime_str, fmt) + dt = pytz.timezone(from_tz).localize(dt) + parse_success = True + break + except ValueError: + continue + + if not parse_success: + raise ValueError("Unable to parse datetime string with common formats") + else: + # 如果没有提供任何时间参数,则使用当前时间 + dt = datetime.datetime.now(pytz.UTC) + except ValueError as e: + raise ValueError(f"Error parsing time input: {str(e)}") + except Exception as e: + raise RuntimeError(f"Unexpected error parsing time input: {str(e)}") + + try: + # Convert timezone + if from_tz != to_tz: + dt = dt.astimezone(pytz.timezone(to_tz)) + + # Format outputs + result = { + "iso": dt.isoformat(), + "timestamp": str(dt.timestamp()), + "datetime": dt.strftime("%Y-%m-%d %H:%M:%S"), + "date": dt.strftime("%Y-%m-%d"), + "time": dt.strftime("%H:%M:%S"), + "timezone": to_tz + } + + # Add custom format if requested + if format_str: + try: + result["formatted"] = dt.strftime(format_str) + except ValueError as e: + raise ValueError(f"Invalid format string: {str(e)}") + + return result + except Exception as e: + raise RuntimeError(f"Error in time_convert: {str(e)}") + + def checksum_crc32(self, inputs): + import zlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("hex must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("hex parameter is required") + + try: + # 验证十六进制字符串 + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空 + if not hex_data: + raise ValueError("hex data cannot be empty") + + # 检查是否为有效的十六进制字符串 + if not all(c in "0123456789abcdefABCDEF" for c in hex_data): + raise ValueError("hex must be a valid hexadecimal string") + + # 检查长度是否为偶数 + if len(hex_data) % 2 != 0: + raise ValueError("hex must have even number of characters") + + val = zlib.crc32(bytes.fromhex(hex_data)) + # 确保 hex 输出是 8 位,前导补 0 + return {"hex": f"{val:08x}", "int": val} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in checksum_crc32: {str(e)}") + + def geo_haversine(self, inputs): + import math + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + lat1 = inputs.get("lat1") + lon1 = inputs.get("lon1") + lat2 = inputs.get("lat2") + lon2 = inputs.get("lon2") + + # 类型检查 + if lat1 is not None and not isinstance(lat1, (int, float, str)): + raise TypeError("lat1 must be a number or string") + if lon1 is not None and not isinstance(lon1, (int, float, str)): + raise TypeError("lon1 must be a number or string") + if lat2 is not None and not isinstance(lat2, (int, float, str)): + raise TypeError("lat2 must be a number or string") + if lon2 is not None and not isinstance(lon2, (int, float, str)): + raise TypeError("lon2 must be a number or string") + + # 检查必需参数 + if lat1 is None: + raise ValueError("lat1 parameter is required") + if lon1 is None: + raise ValueError("lon1 parameter is required") + if lat2 is None: + raise ValueError("lat2 parameter is required") + if lon2 is None: + raise ValueError("lon2 parameter is required") + + try: + # 转换为浮点数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(lat1, str): + lat1 = float(lat1) + elif not isinstance(lat1, (int, float)): + raise TypeError("lat1 must be a number or string") + else: + lat1 = float(lat1) + + if isinstance(lon1, str): + lon1 = float(lon1) + elif not isinstance(lon1, (int, float)): + raise TypeError("lon1 must be a number or string") + else: + lon1 = float(lon1) + + if isinstance(lat2, str): + lat2 = float(lat2) + elif not isinstance(lat2, (int, float)): + raise TypeError("lat2 must be a number or string") + else: + lat2 = float(lat2) + + if isinstance(lon2, str): + lon2 = float(lon2) + elif not isinstance(lon2, (int, float)): + raise TypeError("lon2 must be a number or string") + else: + lon2 = float(lon2) + + # Validate coordinates (approximate range check) + if not (-90 <= lat1 <= 90): + raise ValueError("lat1 must be between -90 and 90") + if not (-90 <= lat2 <= 90): + raise ValueError("lat2 must be between -90 and 90") + if not (-180 <= lon1 <= 180): + raise ValueError("lon1 must be between -180 and 180") + if not (-180 <= lon2 <= 180): + raise ValueError("lon2 must be between -180 and 180") + + # Earth radius in meters + R = 6371000 # Approximate radius of Earth + + # Convert degrees to radians + lat1_rad = math.radians(lat1) + lon1_rad = math.radians(lon1) + lat2_rad = math.radians(lat2) + lon2_rad = math.radians(lon2) + + # Calculate differences + delta_lat = lat2_rad - lat1_rad + delta_lon = lon2_rad - lon1_rad + + # Haversine formula + a = math.sin(delta_lat / 2) ** 2 + \ + math.cos(lat1_rad) * math.cos(lat2_rad) * \ + math.sin(delta_lon / 2) ** 2 + c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) + distance_m = R * c + + # Return distance in meters + return {"meters": round(distance_m, 2)} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in geo_haversine: {str(e)}") + + def otp_totp_generate(self, inputs): + import hmac + import hashlib + import base64 + import time + import struct + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + base32_secret = inputs.get("base32_secret") + step = inputs.get("step", 30) # Default to 30 seconds + digits = inputs.get("digits", 6) # Default to 6 digits + timestamp_iso = inputs.get("timestamp_iso", "") + algo = inputs.get("algo", "sha1") # Default to sha1 as current implementation only supports this + + # 类型检查 + if base32_secret is not None and not isinstance(base32_secret, str): + raise TypeError("base32_secret must be a string") + if not isinstance(step, (int, str)): + raise TypeError("step must be an integer or string") + if not isinstance(digits, (int, str)): + raise TypeError("digits must be an integer or string") + if not isinstance(timestamp_iso, str): + raise TypeError("timestamp_iso must be a string") + if not isinstance(algo, str): + raise TypeError("algo must be a string") + + # 检查必需参数 + if base32_secret is None: + raise ValueError("base32_secret parameter is required") + + try: + # Convert step and digits to appropriate types + step = int(step) + digits = int(digits) + if digits < 6 or digits > 8: + raise ValueError("Digits must be between 6 and 8") + + # Convert timestamp_iso to integer timestamp + if timestamp_iso: + import datetime + dt = datetime.datetime.fromisoformat(timestamp_iso.replace('Z', '+00:00')) + timestamp = int(dt.timestamp()) + else: + timestamp = int(time.time()) + + # Calculate counter value (T = floor(timestamp / step)) + counter = timestamp // step + + # Decode the base32 secret + # Add padding if necessary (base64 requires padding to be multiple of 8) + base32_secret = base32_secret.upper().replace(' ', '') + if len(base32_secret) % 8 != 0: + base32_secret += '=' * (8 - (len(base32_secret) % 8)) + key = base64.b32decode(base32_secret, casefold=True) + + # Calculate HMAC-SHA1 + counter_bytes = struct.pack('>Q', counter) # Big-endian 8-byte integer + hmac_hash = hmac.new(key, counter_bytes, hashlib.sha1).digest() + + # Dynamic truncation + offset = hmac_hash[-1] & 0xF + code = struct.unpack('>I', hmac_hash[offset:offset+4])[0] & 0x7FFFFFFF + + # Generate the OTP + otp = str(code % (10 ** digits)).zfill(digits) + + # Calculate remaining time until next OTP change + remaining_time = step - (timestamp % step) + + return {"totp": otp, "remaining_time": remaining_time, "time_step": step} + except ValueError as e: + if "invalid literal for int()" in str(e): + raise ValueError("step and digits must be valid integers") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in otp_totp_generate: {str(e)}") + + def unicode_norm(self, inputs): + import unicodedata + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + form = inputs.get("form", "NFC") # Default to NFC + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if form is not None and not isinstance(form, str): + raise TypeError("form must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Normalize form (NFC, NFD, NFKC, NFKD) + form = form.upper().strip() + + if form not in ['NFC', 'NFD', 'NFKC', 'NFKD']: + raise ValueError(f"Invalid normalization form: {form}. Must be one of: NFC, NFD, NFKC, NFKD") + + # Apply Unicode normalization + normalized_text = unicodedata.normalize(form, text) + + return {"text": normalized_text} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in unicode_norm: {str(e)}") + + def text_bidi_sanitize(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Bidi control characters to remove + bidi_controls = [ + '\u200E', # LEFT-TO-RIGHT MARK + '\u200F', # RIGHT-TO-LEFT MARK + '\u202A', # LEFT-TO-RIGHT EMBEDDING + '\u202B', # RIGHT-TO-LEFT EMBEDDING + '\u202C', # POP DIRECTIONAL FORMATTING + '\u202D', # LEFT-TO-RIGHT OVERRIDE + '\u202E', # RIGHT-TO-LEFT OVERRIDE + '\u2066', # LEFT-TO-RIGHT ISOLATE + '\u2067', # RIGHT-TO-LEFT ISOLATE + '\u2068', # FIRST STRONG ISOLATE + '\u2069', # POP DIRECTIONAL ISOLATE + ] + + # Remove all Bidi control characters + sanitized_text = text + for control_char in bidi_controls: + sanitized_text = sanitized_text.replace(control_char, '') + + return {"text": sanitized_text} + except Exception as e: + raise RuntimeError(f"Error in text_bidi_sanitize: {str(e)}") + + def text_xor_hex(self, inputs): + import binascii + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_a = inputs.get("hex_a") + hex_b = inputs.get("hex_b") + + # 类型检查 + if hex_a is not None and not isinstance(hex_a, str): + raise TypeError("hex_a must be a string") + if hex_b is not None and not isinstance(hex_b, str): + raise TypeError("hex_b must be a string") + + # 检查必需参数 + if hex_a is None: + raise ValueError("hex_a parameter is required") + if hex_b is None: + raise ValueError("hex_b parameter is required") + + try: + # Remove any whitespace + hex_a = hex_a.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + hex_b = hex_b.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + + # Validate hex strings + if not (all(c in "0123456789abcdefABCDEF" for c in hex_a) and len(hex_a) % 2 == 0): + raise ValueError("hex_a must be a valid hexadecimal string with even length") + if not (all(c in "0123456789abcdefABCDEF" for c in hex_b) and len(hex_b) % 2 == 0): + raise ValueError("hex_b must be a valid hexadecimal string with even length") + + # Convert hex strings to bytes + bytes_a = binascii.unhexlify(hex_a) + bytes_b = binascii.unhexlify(hex_b) + + # Make the byte arrays the same length by padding the shorter one with zeros + max_len = max(len(bytes_a), len(bytes_b)) + bytes_a = bytes_a.ljust(max_len, b'\x00') + bytes_b = bytes_b.ljust(max_len, b'\x00') + + # Perform XOR operation + result_bytes = bytes(a ^ b for a, b in zip(bytes_a, bytes_b)) + + # Convert result back to hex + result_hex = binascii.hexlify(result_bytes).decode('utf-8') + + return {"hex": result_hex} + except ValueError as e: + if "Non-hexadecimal digit found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in text_xor_hex: {str(e)}") + + def text_rotN(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + n = inputs.get("n", 0) + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + n = int(n) + except ValueError: + raise ValueError("n must be a valid integer") + + result = [] + for char in text: + if char.isupper(): + # Rotate uppercase letters + result_char = chr((ord(char) - ord('A') + n) % 26 + ord('A')) + result.append(result_char) + elif char.islower(): + # Rotate lowercase letters + result_char = chr((ord(char) - ord('a') + n) % 26 + ord('a')) + result.append(result_char) + else: + # Keep non-alphabetic characters unchanged + result.append(char) + + return {"text": ''.join(result)} + + def luhn_check(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数(支持 card_number 和 number 两个参数名) + card_number = inputs.get("number") or inputs.get("card_number") + + # 类型检查 + if card_number is not None and not isinstance(card_number, str): + raise TypeError("number must be a string") + + # 检查必需参数 + if card_number is None: + raise ValueError("number parameter is required") + + try: + # 如果输入是JSON数组或其他非数字字符串,返回该字符串本身(用于数据传递) + # 这种情况发生在DAG设计中类型不匹配时 + if card_number.startswith('[') or card_number.startswith('{'): + # 输入是JSON,直接返回原值(用于传递) + return {"valid": card_number} + + # Remove whitespace from card number + card_number = card_number.replace(" ", "").replace("-", "") + + # Check if card number is all digits + if not card_number.isdigit() or len(card_number) < 13: + return {"valid": "false"} + + # Implement Luhn algorithm + total = 0 + reverse_digits = card_number[::-1] # Reverse the number for easier processing + + for i, digit in enumerate(reverse_digits): + num = int(digit) + if i % 2 == 1: # Every second digit starting from the right (which is first in reversed string) + num *= 2 + if num > 9: + num -= 9 # Equivalent to sum of digits for 2-digit numbers + total += num + + # Check if total is divisible by 10 + is_valid = total % 10 == 0 + return {"valid": "true" if is_valid else "false"} + except Exception as e: + raise RuntimeError(f"Error in luhn_check: {str(e)}") + + def iban_validate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iban = inputs.get("iban") + + # 类型检查 + if iban is not None and not isinstance(iban, str): + raise TypeError("iban must be a string") + + # 检查必需参数 + if iban is None: + raise ValueError("iban parameter is required") + + try: + # Remove whitespace from IBAN + iban = iban.replace(" ", "") + + # Basic length and format check + if not (len(iban) >= 15 and len(iban) <= 34): + return {"valid": "False"} + + if not (iban[:2].isalpha() and iban[2:].isdigit()): + return {"valid": "False"} + + # Move first four characters to the end + rearranged = iban[4:] + iban[:4] + + # Replace letters with numbers (A=10, B=11, ..., Z=35) + numeric_iban = '' + for char in rearranged: + if char.isdigit(): + numeric_iban += char + else: + numeric_iban += str(ord(char.upper()) - ord('A') + 10) + + # Perform modulo 97 check + # Use step-by-step approach for very large numbers + remainder = 0 + for char in numeric_iban: + remainder = (remainder * 10 + int(char)) % 97 + + is_valid = remainder == 1 + return {"valid": "True" if is_valid else "False"} + except Exception as e: + raise RuntimeError(f"Error in iban_validate: {str(e)}") + + def matter_synthesizer(self, inputs): + import hashlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + blueprint = inputs.get("blueprint") + + # 类型检查 + if blueprint is not None and not isinstance(blueprint, str): + raise TypeError("blueprint must be a string") + + try: + # Get blueprint parameter as defined in interface + if blueprint is None: + blueprint = "" + + # Generate a unique item ID based on the blueprint + # This ensures the same blueprint always produces the same item + blueprint_hash = hashlib.sha256(blueprint.encode()).hexdigest()[:16] + + # Create a synthesized item with a deterministic ID based on blueprint + synthesized_item = f"synthesized_item_{blueprint_hash}" + + return {"output_slot": synthesized_item} + except Exception as e: + raise RuntimeError(f"Error in matter_synthesizer: {str(e)}") + + # --- Terminal Implementations --- + def terminal_1(self, inputs): + """ + terminal_1: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 只返回 text_output + - 只输入正确的 slot_b → 只返回 hex_output + - 同时输入正确的 slot_a 和 slot_b → 返回 item_dispenser(物品掉落) + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + # 检查哪些输入被提供了 + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值是否正确(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + expected_a = golden_inputs["slot_a"] + a_valid = str(slot_a) == str(expected_a) + + if has_b and "slot_b" in golden_inputs: + expected_b = golden_inputs["slot_b"] + b_valid = str(slot_b) == str(expected_b) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 item_dispenser + if has_a and has_b: + if a_valid and b_valid: + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 text_output + if has_a and not has_b: + if a_valid: + if "text_output" in golden_outputs: + result["text_output"] = golden_outputs["text_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 hex_output + if has_b and not has_a: + if b_valid: + if "hex_output" in golden_outputs: + result["hex_output"] = golden_outputs["hex_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def terminal_2(self, inputs): + """ + terminal_2: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 text_result + - 同时输入正确的 num1 和 num2 → 返回 hex_result 和 math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + # 检查哪些输入被提供了 + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值是否正确(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + expected_num1 = golden_inputs["num1"] + num1_valid = str(num1) == str(expected_num1) + + if has_num2 and "num2" in golden_inputs: + expected_num2 = golden_inputs["num2"] + num2_valid = str(num2) == str(expected_num2) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 hex_result 和 math_token + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 text_result + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "text_result" in golden_outputs: + result["text_result"] = golden_outputs["text_result"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def logic_terminal(self, inputs): + """ + Logic Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 返回 screen(部分输出) + - 只输入正确的 slot_b → 返回 screen 和 secondary_output + - 同时输入正确的 slot_a 和 slot_b → 返回 screen, secondary_output, item_dispenser + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + a_valid = str(slot_a) == str(golden_inputs["slot_a"]) + + if has_b and "slot_b" in golden_inputs: + b_valid = str(slot_b) == str(golden_inputs["slot_b"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出(包括 item_dispenser) + if has_a and has_b: + if a_valid and b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 screen(部分输出) + if has_a and not has_b: + if a_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 screen 和 secondary_output + if has_b and not has_a: + if b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def math_terminal(self, inputs): + """ + Math Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 result_display + - 同时输入正确的 num1 和 num2 → 返回 result_display, hex_result, math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + num1_valid = str(num1) == str(golden_inputs["num1"]) + + if has_num2 and "num2" in golden_inputs: + num2_valid = str(num2) == str(golden_inputs["num2"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 result_display + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def crypt_terminal(self, inputs): + """ + Encryption Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 plaintext → 返回 status(部分输出) + - 同时输入正确的 plaintext 和 key → 返回 status, encrypted_hex, encryption_chip + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + plaintext = inputs.get("plaintext") + key = inputs.get("key") + + has_plaintext = plaintext is not None and plaintext != "" + has_key = key is not None and key != "" + + # 验证输入值(与 golden values 比较) + plaintext_valid = False + key_valid = False + + if has_plaintext and "plaintext" in golden_inputs: + plaintext_valid = str(plaintext) == str(golden_inputs["plaintext"]) + + if has_key and "key" in golden_inputs: + key_valid = str(key) == str(golden_inputs["key"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_plaintext and has_key: + if plaintext_valid and key_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + if "encrypted_hex" in golden_outputs: + result["encrypted_hex"] = golden_outputs["encrypted_hex"] + if "encryption_chip" in golden_outputs: + result["encryption_chip"] = golden_outputs["encryption_chip"] + return result + else: + incorrect_params = [] + correct_params = [] + if not plaintext_valid: + incorrect_params.append("plaintext") + else: + correct_params.append("plaintext") + if not key_valid: + incorrect_params.append("key") + else: + correct_params.append("key") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 plaintext 且正确 → 返回 status(部分输出) + if has_plaintext and not has_key: + if plaintext_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: plaintext"} + + # 只提供 key 但没有 plaintext + if has_key and not has_plaintext: + return {"error": "plaintext required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + def sequence_terminal(self, inputs): + """ + Sequence Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 sequence → 返回 verification(部分输出) + - 同时输入正确的 sequence 和 checksum → 返回 verification, auth_code, access_card + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + sequence = inputs.get("sequence") + checksum = inputs.get("checksum") + + has_sequence = sequence is not None and sequence != "" + has_checksum = checksum is not None and checksum != "" + + # 验证输入值(与 golden values 比较) + sequence_valid = False + checksum_valid = False + + if has_sequence and "sequence" in golden_inputs: + sequence_valid = str(sequence) == str(golden_inputs["sequence"]) + + if has_checksum and "checksum" in golden_inputs: + checksum_valid = str(checksum) == str(golden_inputs["checksum"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_sequence and has_checksum: + if sequence_valid and checksum_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + if "auth_code" in golden_outputs: + result["auth_code"] = golden_outputs["auth_code"] + if "access_card" in golden_outputs: + result["access_card"] = golden_outputs["access_card"] + return result + else: + incorrect_params = [] + correct_params = [] + if not sequence_valid: + incorrect_params.append("sequence") + else: + correct_params.append("sequence") + if not checksum_valid: + incorrect_params.append("checksum") + else: + correct_params.append("checksum") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 sequence 且正确 → 返回 verification(部分输出) + if has_sequence and not has_checksum: + if sequence_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: sequence"} + + # 只提供 checksum 但没有 sequence + if has_checksum and not has_sequence: + return {"error": "sequence required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + # --- Additional File Tools --- + + def zip_unzip_file(self, inputs): + """ZIP 解压文件工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def zip_unzip_item(self, inputs): + """ZIP 解压道具工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def code_py_exec(self, inputs): + """Python 代码执行工具 + + 这是一个真实执行的工具,在 DAG 生成阶段和运行时评测阶段都会执行代码。 + 输入: code (Python 代码字符串) + 输出: stdout (标准输出,包含执行结果和错误信息) + + 特殊行为: + - 如果代码定义了 main() 函数,会自动调用它 + - 如果执行出错,错误信息会包含在 stdout 中 + """ + code = inputs.get("code", "") + + if not code: + return {"stdout": "Error: No code provided"} + + try: + # 创建一个受限的执行环境 + import io + import sys + + # 捕获标准输出和标准错误 + old_stdout = sys.stdout + old_stderr = sys.stderr + sys.stdout = io.StringIO() + sys.stderr = io.StringIO() + + # 执行代码 + exec_globals = {"__builtins__": __builtins__} + exec_locals = {} + exec(code, exec_globals, exec_locals) + + # 如果定义了 main() 函数,自动调用它 + if 'main' in exec_locals and callable(exec_locals['main']): + exec_locals['main']() + + # 获取输出 + stdout_value = sys.stdout.getvalue() + stderr_value = sys.stderr.getvalue() + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 合并 stdout 和 stderr + output = stdout_value + if stderr_value: + output += ("\n" if output else "") + f"[stderr] {stderr_value}" + + # 如果没有任何输出,尝试返回 result 变量的值 + if not output: + result = exec_locals.get("_result") or exec_locals.get("result") + if result is not None: + output = str(result) + + return {"stdout": output if output else "(no output)"} + + except Exception as e: + # 恢复标准输出和错误输出 + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 返回错误信息 + return {"stdout": f"Error: {type(e).__name__}: {str(e)}"} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-7499421d/environment/puzzle/worker.Dockerfile b/tasks/agentescape-25-skeleton-7499421d/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-25-skeleton-7499421d/environment/puzzle/worker.Dockerfile @@ -0,0 +1,8 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends libseccomp2 && rm -rf /var/lib/apt/lists/* +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY worker.py child.py /app/ +COPY upstream/simulator.py /app/simulator.py +CMD ["uvicorn", "worker:app", "--host", "0.0.0.0", "--port", "8001", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-25-skeleton-7499421d/environment/puzzle/worker.py b/tasks/agentescape-25-skeleton-7499421d/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-25-skeleton-7499421d/environment/puzzle/worker.py @@ -0,0 +1,73 @@ +"""Stateless Python tool worker. Never receives a scenario or reference values.""" + +import json +import os +import signal +import subprocess +import sys +import tempfile +import threading + +from fastapi import FastAPI +from pydantic import BaseModel, ConfigDict + +app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) +lock = threading.Lock() + + +class Execution(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + code: str + + +@app.get("/health") +def health(): + return {"ok": True} + + +@app.post("/execute") +def execute(request: Execution): + if len(request.code.encode()) > 65536: + return {"stdout": "Error: code exceeds 64 KiB limit"} + with lock, tempfile.TemporaryDirectory(prefix="escape-code-") as directory: + os.chown(directory, 65534, 65534) + with tempfile.TemporaryFile() as output: + process = subprocess.Popen( + [sys.executable, "-I", "/app/child.py"], + stdin=subprocess.PIPE, + stdout=output, + stderr=subprocess.DEVNULL, + cwd=directory, + user=65534, + group=65534, + extra_groups=[], + start_new_session=True, + env={"PATH": "/usr/local/bin:/usr/bin:/bin"}, + ) + try: + process.communicate( + json.dumps({"code": request.code}).encode(), timeout=5 + ) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + return {"stdout": "Error: Python execution timed out"} + finally: + # Also remove children still in the process group after normal exit. + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + output.seek(0) + value = output.read(65537) + if len(value) > 65536 or process.returncode != 0: + return { + "stdout": "Error: Python execution exceeded a resource limit or failed" + } + try: + result = json.loads(value) + if not isinstance(result.get("stdout"), str): + raise ValueError("Invalid worker response") + return result + except (ValueError, AttributeError): + return {"stdout": "Error: Python execution returned invalid output"} diff --git a/tasks/agentescape-25-skeleton-7499421d/instruction.md b/tasks/agentescape-25-skeleton-7499421d/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-25-skeleton-7499421d/instruction.md @@ -0,0 +1,18 @@ +# Escape the room + +Discover the victory string and submit it with `escape submit-answer`. +Start with `escape observe`. This returns the room, available information, visible entities, and victory node ID. + +Use these commands (JSON responses): + +```sh +escape investigate NODE_ID +escape tool-call NODE_ID --arguments-json '{"parameter": "value"}' +escape use-item NODE_ID --arguments-json '{"parameter": "value"}' +escape submit-answer 'exact victory string' +escape state +``` + +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. + +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. diff --git a/tasks/agentescape-25-skeleton-7499421d/solution/oracle.py b/tasks/agentescape-25-skeleton-7499421d/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-25-skeleton-7499421d/solution/oracle.py @@ -0,0 +1,133 @@ +"""Reference solver: use trusted inputs, but obtain the answer through public actions.""" + +import json +import urllib.request +from pathlib import Path + + +def http_action(base_url, payload): + request = urllib.request.Request( + base_url + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(request, timeout=30) as response: + return json.load(response) + + +def solve(scenario, act, observe): + nodes = {node["id"]: node for node in scenario["nodes"]} + visible = {entity["id"] for entity in observe["available_entities"]} + solved = set() + seen_outputs = {} + action_count = 0 + + def call(payload): + nonlocal action_count + action_count += 1 + response = act(payload) + visible.update(entity["id"] for entity in response.get("newly_revealed", [])) + if ( + response.get("episode", {}).get("termination_reason") + == "infrastructure_error" + ): + raise RuntimeError("Infrastructure failure") + return response + + for _round in range(len(nodes) + 2): + progress = False + for node_id, node in nodes.items(): + if node_id not in visible or node_id in solved: + continue + # Preserve graph order for data inputs; trigger/drop edges express visibility. + predecessors = [ + edge["source_id"] + for edge in scenario["edges"] + if edge["target_id"] == node_id + and edge["connection_type"] not in ("Item", "Hidden_Item") + ] + if any(pred not in solved for pred in predecessors): + continue + info = call({"action": "investigate", "node_id": node_id}) + if not info.get("ok"): + raise RuntimeError(f"Investigation failed: {node_id}: {info}") + inputs = { + port["name"]: port["value"] + for port in node.get("inputs", []) + if "value" in port + } + if node["type"] == "Tool": + result = call( + {"action": "tool_call", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok") or result.get("output_values", {}).get("error"): + raise RuntimeError(f"Tool failed: {node_id}: {result}") + output = result.get("output_values", {}) + if node.get("template_id") in ("terminal_1", "terminal_2"): + slots = { + port["name"]: inputs[port["name"]] + for port in node["inputs"] + if port["type"] not in ("Item", "Hidden_Item") + and port["name"] in inputs + } + triggers = { + key: value for key, value in inputs.items() if key not in slots + } + for key, value in slots.items(): + partial = call( + { + "action": "tool_call", + "node_id": node_id, + "arguments": {**triggers, key: value}, + } + ) + if partial.get("ok"): + output.update(partial.get("output_values", {})) + # HIDDEN_ITEM tool drops only occur on subsequent investigation. + call({"action": "investigate", "node_id": node_id}) + elif info.get("required_inputs"): + result = call( + {"action": "use_item", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok"): + raise RuntimeError(f"Item failed: {node_id}: {result}") + output = result.get("content") + else: + output = info.get("content") + seen_outputs[node_id] = output + solved.add(node_id) + progress = True + win_id = scenario["metadata"]["win_node_id"] + if win_id in solved and (len(solved) == len(nodes) or not progress): + outputs = seen_outputs[win_id] + if not outputs: + raise RuntimeError(f"Victory node returned no output: {win_id}") + # Upstream grades its first stored output port, independent of response order. + victory_port = next( + port["name"] for port in nodes[win_id]["outputs"] if "value" in port + ) + answer = outputs[victory_port] if isinstance(outputs, dict) else outputs + result = call({"action": "submit_answer", "answer": answer}) + if not result.get("is_win"): + raise RuntimeError(f"Victory submission failed: {result}") + return {"won": True, "actions": action_count, "visited_nodes": len(solved)} + if not progress: + raise RuntimeError(f"No progress: visible={visible}, solved={solved}") + raise RuntimeError("Reference solver exceeded graph traversal limit") + + +if __name__ == "__main__": + import os + + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000") + with urllib.request.urlopen(base + "/observation", timeout=20) as response: + observation = json.load(response) + print( + json.dumps( + solve( + json.loads(Path("/solution/scenario.json").read_text()), + lambda payload: http_action(base, payload), + observation, + ) + ) + ) diff --git a/tasks/agentescape-25-skeleton-7499421d/solution/scenario.json b/tasks/agentescape-25-skeleton-7499421d/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..7deb8073bae4c50646f2a9308bb7471a096478c2 --- /dev/null +++ b/tasks/agentescape-25-skeleton-7499421d/solution/scenario.json @@ -0,0 +1,1453 @@ +{ + "metadata": { + "total_nodes": 25, + "total_edges": 30, + "win_node_id": "zlib_deflate", + "win_condition": { + "type": "tool_output", + "node_id": "zlib_deflate", + "output_port": "hex", + "output_type": "Hex_String", + "description": "Execute Zlib Deflate and get the output from port 'hex'" + }, + "source_init": { + "source_nodes": [ + "crypto_rsa_decrypt_hex", + "terminal_2", + "zip_unzip_file", + "zip_unzip_file_61fa", + "num_base_convert", + "zip_unzip_file_5af7", + "calc_gcd", + "num_base_convert_53cc", + "regex_search", + "csv_query", + "luhn_check", + "zip_unzip_file_1f72", + "checksum_crc32_18c4", + "code_py_exec" + ], + "by_node": { + "crypto_rsa_decrypt_hex": { + "node_name": "RSA Decrypt", + "node_type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "init_inputs": { + "hex_cipher": { + "type": "Hex_String", + "description": "Ciphertext (Hex)" + } + }, + "init_outputs": {} + }, + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": { + "num1": { + "type": "Big_Int", + "description": "First Number" + } + }, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + }, + "math_token": { + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "zip_unzip_file_61fa": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "num_base_convert": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "s": { + "type": "Big_Int", + "description": "Input integer value" + } + }, + "init_outputs": {} + }, + "zip_unzip_file_5af7": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "calc_gcd": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "b": { + "type": "Big_Int", + "description": "Second integer" + } + }, + "init_outputs": {} + }, + "num_base_convert_53cc": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "from_base": { + "type": "Big_Int", + "description": "From base" + }, + "to_base": { + "type": "Big_Int", + "description": "To base" + } + }, + "init_outputs": {} + }, + "regex_search": { + "node_name": "Regex Search", + "node_type": "Tool", + "template_id": "regex_search", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "File ID (optional)" + } + }, + "init_outputs": { + "matches": { + "type": "Text_Generic", + "description": "Found matches (List)" + } + } + }, + "csv_query": { + "node_name": "CSV Query", + "node_type": "Tool", + "template_id": "csv_query", + "init_inputs": {}, + "init_outputs": { + "rows": { + "type": "Text_Generic", + "description": "Result rows" + } + } + }, + "luhn_check": { + "node_name": "Luhn Checker", + "node_type": "Tool", + "template_id": "luhn_check", + "init_inputs": { + "number": { + "type": "Text_Generic", + "description": "Number string" + } + }, + "init_outputs": {} + }, + "zip_unzip_file_1f72": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + }, + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "checksum_crc32_18c4": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + }, + "code_py_exec": { + "node_name": "Python Executor", + "node_type": "Tool", + "template_id": "code_py_exec", + "init_inputs": { + "code": { + "type": "Code_Python", + "description": "Python code" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "crypto_rsa_decrypt_hex": { + "init_inputs": { + "hex_cipher": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + }, + "init_outputs": {} + }, + "terminal_2": { + "init_inputs": { + "num1": "8472948175928374928157" + }, + "init_outputs": { + "text_result": "Terminal output partial result ready.", + "hex_result": "ab12cd34ef569078", + "math_token": "Just an empty useless mathematical token here." + } + }, + "zip_unzip_file": { + "init_inputs": { + "password": "securePass123" + }, + "init_outputs": { + "files": "extracted_data_1.csv" + } + }, + "zip_unzip_file_61fa": { + "init_inputs": {}, + "init_outputs": { + "files": "extracted_data_2.txt" + } + }, + "num_base_convert": { + "init_inputs": { + "s": "48291048293847192837482" + }, + "init_outputs": {} + }, + "zip_unzip_file_5af7": { + "init_inputs": {}, + "init_outputs": { + "files": "extracted_data_3.json" + } + }, + "calc_gcd": { + "init_inputs": { + "b": "29481759283748192837582" + }, + "init_outputs": {} + }, + "num_base_convert_53cc": { + "init_inputs": { + "from_base": "16", + "to_base": "10" + }, + "init_outputs": {} + }, + "regex_search": { + "init_inputs": { + "file_id": "search_target.log" + }, + "init_outputs": { + "matches": "[\"user_1\", \"user_2\", \"user_3\", \"user_4\", \"user_5\"]" + } + }, + "csv_query": { + "init_inputs": {}, + "init_outputs": { + "rows": "[{\"col1\":\"val1\"}, {\"col1\":\"val2\"}, {\"col1\":\"val3\"}, {\"col1\":\"val4\"}]" + } + }, + "luhn_check": { + "init_inputs": { + "number": "4561261212345464" + }, + "init_outputs": {} + }, + "zip_unzip_file_1f72": { + "init_inputs": { + "zip_id": "archive_main.zip", + "password": "archivePass456" + }, + "init_outputs": { + "files": "extracted_data_4.xml" + } + }, + "checksum_crc32_18c4": { + "init_inputs": { + "hex": "112233445566778899aabbccddeeff00" + }, + "init_outputs": {} + }, + "code_py_exec": { + "init_inputs": { + "code": "print('Hello World')\nresult = 42" + }, + "init_outputs": {} + } + }, + "intro_narrative": "The year is 2142. The world you once knew has been reduced to ash and twisted metal, ravaged by the Great Collapse. You are a Scavenger, wandering the irradiated wasteland of Sector 7. Your Geiger counter clicks rapidly as you stumble upon an underground bunker, its heavy blast doors slightly ajar. Inside lies a complex network of ancient terminals, cryptographic devices, and forgotten storage drives left behind by the architects of the old world. Your objective is clear: navigate this labyrinth of decayed technology, restore the power relays, and extract the encrypted emergency coordinates before the bunker's collapsing power grid seals you inside forever. Every device is interconnected, demanding logic and careful exploration to piece together the final transmission. Time is running out, and the wasteland forgives no mistakes.", + "narrative_style": "post_apocalyptic" + }, + "nodes": [ + { + "id": "zlib_deflate", + "name": "Zlib Deflate", + "description": "Deflate text to zlib bytes (hex).", + "type": "Tool", + "template_id": "zlib_deflate", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Text to compress", + "value": "Al9LDmUX" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Compressed hex", + "value": "789c73ccb1f471c90d8d00000b2f0291" + } + ], + "narrative": "This is the Final Compression Protocol. It requires input from the Transmission Relay to finalize the emergency broadcast." + }, + { + "id": "base64_encode", + "name": "Base64 Encoder", + "description": "Encode hex bytes to base64.", + "type": "Tool", + "template_id": "base64_encode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex bytes", + "value": "025f4b0e6517" + } + ], + "outputs": [ + { + "name": "b64", + "type": "Text_Generic", + "description": "Base64 string", + "value": "Al9LDmUX" + } + ], + "narrative": "This is a Transmission Relay. It requires input from the Data Compiler to establish an uplink." + }, + { + "id": "hex_encode", + "name": "Text to Hex Encoder", + "description": "Encode UTF-8 text to hex.", + "type": "Tool", + "template_id": "hex_encode", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "\u0002_K\u000ee\u0017" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Encoded hex", + "value": "025f4b0e6517" + } + ], + "narrative": "This is a Data Compiler. It requires input from the Decryption Matrix to structure the recovered files." + }, + { + "id": "zip_unzip_item", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_item", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "extracted_data_1.csv" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Terminal output partial result ready." + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip" + } + ], + "narrative": "This is a Secure Vault. It requires inputs from the Main Command Terminal and the Encrypted Storage Drive Delta." + }, + { + "id": "crypto_rsa_decrypt_hex", + "name": "RSA Decrypt", + "description": "RSA decrypt (hex cipher) with n,d (decimal).", + "type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex_cipher", + "type": "Hex_String", + "description": "Ciphertext (Hex)", + "value": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Modulus n", + "value": "48291048293847192837482" + }, + { + "name": "d", + "type": "Big_Int", + "description": "Private exponent d", + "value": 3549980404 + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decrypted text", + "value": "\u0002_K\u000ee\u0017" + } + ], + "init": { + "inputs": { + "hex_cipher": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + }, + "outputs": {} + }, + "narrative": "This is a Decryption Matrix. It requires inputs from the Secondary Radiation Scanner and the Quantum Decoupler." + }, + { + "id": "terminal_2", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this terminal" + }, + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "8472948175928374928157" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "154997392648" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Terminal output partial result ready." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "ab12cd34ef569078" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "Just an empty useless mathematical token here." + } + ], + "init": { + "inputs": { + "num1": "8472948175928374928157" + }, + "outputs": { + "text_result": "Terminal output partial result ready.", + "hex_result": "ab12cd34ef569078", + "math_token": "Just an empty useless mathematical token here." + } + }, + "narrative": "This is the Main Command Terminal. It requires input from the Power Conversion Relay to boot up its interface." + }, + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "extracted_data_2.txt" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "securePass123" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_data_1.csv" + } + ], + "init": { + "inputs": { + "password": "securePass123" + }, + "outputs": { + "files": "extracted_data_1.csv" + } + }, + "narrative": "This is Encrypted Storage Drive Delta. It requires input from the Encrypted Storage Drive Gamma to initiate extraction." + }, + { + "id": "zip_unzip_file_61fa", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "extracted_data_3.json" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Terminal output partial result ready." + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_data_2.txt" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "extracted_data_2.txt" + } + }, + "narrative": "This is Encrypted Storage Drive Gamma. It requires inputs from the Main Command Terminal and the Encrypted Storage Drive Beta." + }, + { + "id": "checksum_crc32", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "5b22757365725f31222c2022757365725f32222c2022757365725f33222c2022757365725f34222c2022757365725f35225d" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "d39866f4" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3549980404 + } + ], + "narrative": "This is a Secondary Radiation Scanner. It requires input from the Signal Modulator to verify integrity." + }, + { + "id": "hex_encode_f266", + "name": "Text to Hex Encoder", + "description": "Encode UTF-8 text to hex.", + "type": "Tool", + "template_id": "hex_encode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "[\"user_1\", \"user_2\", \"user_3\", \"user_4\", \"user_5\"]" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Encoded hex", + "value": "5b22757365725f31222c2022757365725f32222c2022757365725f33222c2022757365725f34222c2022757365725f35225d" + } + ], + "narrative": "This is a Signal Modulator. It requires input from the Pattern Analyzer to encode the outgoing frequencies." + }, + { + "id": "num_base_convert", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "48291048293847192837482" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "2" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "154997392648" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "48291048293847192837482" + } + ], + "init": { + "inputs": { + "s": "48291048293847192837482" + }, + "outputs": {} + }, + "narrative": "This is a Quantum Decoupler. It requires inputs from both the Harmonic Resonance Calibrator and the Power Conversion Relay." + }, + { + "id": "zip_unzip_file_5af7", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "extracted_data_4.xml" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "false" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_data_3.json" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "extracted_data_3.json" + } + }, + "narrative": "This is Encrypted Storage Drive Beta. It requires inputs from the Encrypted Storage Drive Alpha and the Biometric Authenticator." + }, + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "154997392648" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "29481759283748192837582" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "2" + } + ], + "init": { + "inputs": { + "b": "29481759283748192837582" + }, + "outputs": {} + }, + "narrative": "This is a Harmonic Resonance Calibrator. It requires input from the Power Conversion Relay to synchronize." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "An Access Token. A small metallic chip bearing the insignia of the old world." + }, + { + "id": "item_8_8e8e", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A Rusty Keycard. A dilapidated piece of plastic with a faded magnetic strip." + }, + { + "id": "num_base_convert_53cc", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": 2416908508 + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "16" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "10" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "154997392648" + } + ], + "init": { + "inputs": { + "from_base": "16", + "to_base": "10" + }, + "outputs": {} + }, + "narrative": "This is a Power Conversion Relay. It requires input from the Primary Radiation Scanner to calibrate its output." + }, + { + "id": "regex_search", + "name": "Regex Search", + "description": "Search regex in either raw text or a file.", + "type": "Tool", + "template_id": "regex_search", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "pattern", + "type": "Text_Generic", + "description": "Regex pattern", + "value": "Terminal output partial result ready." + }, + { + "name": "file_id", + "type": "File_Id", + "description": "File ID (optional)", + "value": "search_target.log" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text (optional)", + "value": "[{\"col1\":\"val1\"}, {\"col1\":\"val2\"}, {\"col1\":\"val3\"}, {\"col1\":\"val4\"}]" + } + ], + "outputs": [ + { + "name": "matches", + "type": "Text_Generic", + "description": "Found matches (List)", + "value": "[\"user_1\", \"user_2\", \"user_3\", \"user_4\", \"user_5\"]" + } + ], + "init": { + "inputs": { + "file_id": "search_target.log" + }, + "outputs": { + "matches": "[\"user_1\", \"user_2\", \"user_3\", \"user_4\", \"user_5\"]" + } + }, + "narrative": "This is a Pattern Analyzer. It requires inputs from the Main Command Terminal and the Database Server to run diagnostics." + }, + { + "id": "csv_query", + "name": "CSV Query", + "description": "Query CSV: select columns and simple WHERE.", + "type": "Tool", + "template_id": "csv_query", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "CSV file ID", + "value": "extracted_data_2.txt" + }, + { + "name": "select", + "type": "Text_Generic", + "description": "Columns to select", + "value": "false" + }, + { + "name": "where", + "type": "Text_Generic", + "description": "Where clause", + "value": "Hello World\n" + } + ], + "outputs": [ + { + "name": "rows", + "type": "Text_Generic", + "description": "Result rows", + "value": "[{\"col1\":\"val1\"}, {\"col1\":\"val2\"}, {\"col1\":\"val3\"}, {\"col1\":\"val4\"}]" + } + ], + "init": { + "inputs": {}, + "outputs": { + "rows": "[{\"col1\":\"val1\"}, {\"col1\":\"val2\"}, {\"col1\":\"val3\"}, {\"col1\":\"val4\"}]" + } + }, + "narrative": "This is a Database Server. It requires inputs from the Biometric Authenticator, the Encrypted Storage Drive Gamma, and the Automated Maintenance Drone." + }, + { + "id": "luhn_check", + "name": "Luhn Checker", + "description": "Luhn validity of number string.", + "type": "Tool", + "template_id": "luhn_check", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "number", + "type": "Text_Generic", + "description": "Number string", + "value": "4561261212345464" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "false" + } + ], + "init": { + "inputs": { + "number": "4561261212345464" + }, + "outputs": {} + }, + "narrative": "A Biometric Authenticator. A grimy handprint scanner mounted on the reinforced wall." + }, + { + "id": "zip_unzip_file_1f72", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "archive_main.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "archivePass456" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_data_4.xml" + } + ], + "init": { + "inputs": { + "zip_id": "archive_main.zip", + "password": "archivePass456" + }, + "outputs": { + "files": "extracted_data_4.xml" + } + }, + "narrative": "Encrypted Storage Drive Alpha. A heavily encrypted data drive found in the debris." + }, + { + "id": "item_8_bcb4", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A Control Module. A dust-covered circuit board missing its casing." + }, + { + "id": "item_8_df11", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "An Override Chip. A specialized bypass circuit found among the ruins." + }, + { + "id": "checksum_crc32_18c4", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "112233445566778899aabbccddeeff00" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "900f18dc" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 2416908508 + } + ], + "init": { + "inputs": { + "hex": "112233445566778899aabbccddeeff00" + }, + "outputs": {} + }, + "narrative": "The Primary Radiation Scanner. An old handheld device used to measure residual radiation levels in the sector." + }, + { + "id": "code_py_exec", + "name": "Python Executor", + "description": "Run limited Python: only safe builtins.", + "type": "Tool", + "template_id": "code_py_exec", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "code", + "type": "Code_Python", + "description": "Python code", + "value": "print('Hello World')\nresult = 42" + } + ], + "outputs": [ + { + "name": "stdout", + "type": "Text_Generic", + "description": "Standard Output (includes errors if any)", + "value": "Hello World\n" + } + ], + "init": { + "inputs": { + "code": "print('Hello World')\nresult = 42" + }, + "outputs": {} + }, + "narrative": "An Automated Maintenance Drone. A barely functioning robotic unit wandering the facility." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A Chronometer. A shattered digital watch that still weakly flashes." + } + ], + "edges": [ + { + "source_id": "base64_encode", + "target_id": "zlib_deflate", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "text" + }, + { + "source_id": "hex_encode", + "target_id": "base64_encode", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "zip_unzip_item", + "target_id": "hex_encode", + "connection_type": "Item", + "source_port": "item", + "target_port": "trigger_item" + }, + { + "source_id": "crypto_rsa_decrypt_hex", + "target_id": "hex_encode", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "text" + }, + { + "source_id": "terminal_2", + "target_id": "zip_unzip_item", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "password" + }, + { + "source_id": "zip_unzip_file", + "target_id": "zip_unzip_item", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "zip_unzip_file_61fa", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "checksum_crc32", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "d" + }, + { + "source_id": "hex_encode_f266", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "terminal_2", + "target_id": "zip_unzip_file_61fa", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "password" + }, + { + "source_id": "num_base_convert", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "n" + }, + { + "source_id": "zip_unzip_file_5af7", + "target_id": "zip_unzip_file_61fa", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "calc_gcd", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "from_base" + }, + { + "source_id": "item_8", + "target_id": "calc_gcd", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "item_8_8e8e", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "num_base_convert_53cc", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "num2" + }, + { + "source_id": "num_base_convert_53cc", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "a" + }, + { + "source_id": "regex_search", + "target_id": "hex_encode_f266", + "connection_type": "Text_Generic", + "source_port": "matches", + "target_port": "text" + }, + { + "source_id": "terminal_2", + "target_id": "regex_search", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "pattern" + }, + { + "source_id": "csv_query", + "target_id": "regex_search", + "connection_type": "Text_Generic", + "source_port": "rows", + "target_port": "text" + }, + { + "source_id": "luhn_check", + "target_id": "csv_query", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "select" + }, + { + "source_id": "num_base_convert_53cc", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "to_base" + }, + { + "source_id": "zip_unzip_file_1f72", + "target_id": "zip_unzip_file_5af7", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "item_8_bcb4", + "target_id": "terminal_2", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "item_8_df11", + "target_id": "num_base_convert", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "checksum_crc32_18c4", + "target_id": "num_base_convert_53cc", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "s" + }, + { + "source_id": "luhn_check", + "target_id": "zip_unzip_file_5af7", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "password" + }, + { + "source_id": "zip_unzip_file_61fa", + "target_id": "csv_query", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "code_py_exec", + "target_id": "csv_query", + "connection_type": "Text_Generic", + "source_port": "stdout", + "target_port": "where" + }, + { + "source_id": "item_16", + "target_id": "item_8_bcb4", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-7499421d/solution/solve.sh b/tasks/agentescape-25-skeleton-7499421d/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-25-skeleton-7499421d/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-25-skeleton-7499421d/task.toml b/tasks/agentescape-25-skeleton-7499421d/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..500b982dca5744804aae993c4b91c8403cf6e2cf --- /dev/null +++ b/tasks/agentescape-25-skeleton-7499421d/task.toml @@ -0,0 +1,38 @@ +schema_version = "1.4" +source = "https://github.com/AGI-Eval-Official/Repo-of-AgentEscapeBench" + +[[artifacts]] +source = "/evidence/final.json" +service = "puzzle" + +[[artifacts]] +source = "/evidence/trace.jsonl" +service = "puzzle" + +[task] +name = "edbeeching/agentescape-25-skeleton-7499421d" +version = "0.1.0" + +[metadata] +difficulty = 25 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "a5a45662a71d2d18f24ce0ff6aab86f83d1eb5a76ff09cfa786dad7d49cbc975" +protocol = "harbor-cli-action-budget-v1" +max_actions = 500 + +[agent] +timeout_sec = 1200 + +[environment] +build_timeout_sec = 900 +cpus = 1 +memory_mb = 1024 + +[verifier] +environment_mode = "separate" +timeout_sec = 60 + +[[verifier.collect]] +service = "puzzle" +command = "python -I /app/export.py" +timeout_sec = 15 diff --git a/tasks/agentescape-25-skeleton-7499421d/tests/Dockerfile b/tasks/agentescape-25-skeleton-7499421d/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-25-skeleton-7499421d/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-25-skeleton-7499421d/tests/expected.json b/tasks/agentescape-25-skeleton-7499421d/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..7b4acf6b82e86febc6390be6e6fc5b0f43aa625c --- /dev/null +++ b/tasks/agentescape-25-skeleton-7499421d/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "a5a45662a71d2d18f24ce0ff6aab86f83d1eb5a76ff09cfa786dad7d49cbc975", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-7499421d/tests/grade.py b/tasks/agentescape-25-skeleton-7499421d/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-25-skeleton-7499421d/tests/grade.py @@ -0,0 +1,21 @@ +"""Grade only Harbor-collected sidecar evidence in a fresh verifier container.""" + +import json +from pathlib import Path + +expected = json.loads(Path("/tests/expected.json").read_text()) +state = json.loads(Path("/evidence/final.json").read_text()) +assert state["collected_from_live_service"] is True, "Missing trusted service export" +assert state["scenario_sha256"] == expected["scenario_sha256"], ( + "Wrong scenario evidence" +) +assert state["max_actions"] == expected["max_actions"], "Wrong budget" +assert type(state["won"]) is bool +assert 0 <= state["action_count"] <= state["max_actions"] +assert state["termination_reason"] != "infrastructure_error", ( + "Infrastructure failure is not a puzzle failure" +) +assert not state["won"] or state["termination_reason"] == "success" +Path("/logs/verifier").mkdir(parents=True, exist_ok=True) +Path("/logs/verifier/state.json").write_text(json.dumps(state, indent=2)) +Path("/logs/verifier/reward.txt").write_text("1.0\n" if state["won"] else "0.0\n") diff --git a/tasks/agentescape-25-skeleton-7499421d/tests/test.sh b/tasks/agentescape-25-skeleton-7499421d/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-25-skeleton-7499421d/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-25-skeleton-8c861d5b/environment/Dockerfile b/tasks/agentescape-25-skeleton-8c861d5b/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-25-skeleton-8c861d5b/environment/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-25-skeleton-8c861d5b/environment/agent/Dockerfile b/tasks/agentescape-25-skeleton-8c861d5b/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-25-skeleton-8c861d5b/environment/agent/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-25-skeleton-8c861d5b/environment/agent/cli.py b/tasks/agentescape-25-skeleton-8c861d5b/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-25-skeleton-8c861d5b/environment/agent/cli.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Public agent client; depends only on the Python standard library.""" + +import argparse +import json +import os +import sys +import urllib.error +import urllib.request + + +def main(): + parser = argparse.ArgumentParser(description="Interact with the escape room") + parser.add_argument( + "action", + choices=[ + "observe", + "state", + "investigate", + "tool-call", + "use-item", + "submit-answer", + ], + ) + parser.add_argument("value", nargs="?") + parser.add_argument("--arguments-json", default="{}") + args = parser.parse_args() + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000").rstrip("/") + if args.action in ("observe", "state"): + request = urllib.request.Request( + base + ("/observation" if args.action == "observe" else "/state") + ) + else: + if args.value is None: + parser.error("node ID or answer is required") + payload = {"action": args.action.replace("-", "_")} + if args.action == "submit-answer": + payload["answer"] = args.value + else: + payload["node_id"] = args.value + if args.action in ("tool-call", "use-item"): + payload["arguments"] = json.loads(args.arguments_json) + request = urllib.request.Request( + base + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=30) as response: + print(json.dumps(json.load(response), ensure_ascii=False)) + except (urllib.error.URLError, ValueError) as exc: + print(json.dumps({"ok": False, "error": str(exc)})) + sys.exit(2) + + +if __name__ == "__main__": + main() diff --git a/tasks/agentescape-25-skeleton-8c861d5b/environment/docker-compose.yaml b/tasks/agentescape-25-skeleton-8c861d5b/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6f97776fcae6572b7dd712f32f83e294b42d79d7 --- /dev/null +++ b/tasks/agentescape-25-skeleton-8c861d5b/environment/docker-compose.yaml @@ -0,0 +1,50 @@ +services: + main: + image: agentescapebench-agent:aab05a0a9ddb + build: + context: ./agent + networks: [default, puzzle] + security_opt: [no-new-privileges:true] + depends_on: + puzzle: + condition: service_healthy + puzzle: + image: agentescapebench-puzzle:agentescape-25-skeleton-8c861d5b-aab05a0a9ddb + build: + context: ./puzzle + networks: [puzzle, execution] + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 512m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"] + interval: 1s + timeout: 3s + retries: 30 + depends_on: + worker: + condition: service_healthy + worker: + image: agentescapebench-worker:aab05a0a9ddb + build: + context: ./puzzle + dockerfile: worker.Dockerfile + networks: [execution] + read_only: true + tmpfs: ["/tmp:size=64m,mode=1777"] + cap_drop: [ALL] + cap_add: [SETUID, SETGID, KILL, CHOWN, DAC_OVERRIDE] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 384m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8001/health')"] + interval: 1s + timeout: 3s + retries: 30 +networks: + puzzle: + internal: true + execution: + internal: true diff --git a/tasks/agentescape-25-skeleton-8c861d5b/environment/puzzle/Dockerfile b/tasks/agentescape-25-skeleton-8c861d5b/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-25-skeleton-8c861d5b/environment/puzzle/Dockerfile @@ -0,0 +1,9 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY upstream /app/upstream +COPY service.py export.py /app/ +COPY scenario.json /private/scenario.json +ENV SCENARIO_PATH=/private/scenario.json EVIDENCE_DIR=/evidence WORKER_URL=http://worker:8001 MAX_ACTIONS=500 +CMD ["uvicorn", "service:create_app", "--factory", "--host", "0.0.0.0", "--port", "8000", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-25-skeleton-8c861d5b/environment/puzzle/child.py b/tasks/agentescape-25-skeleton-8c861d5b/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-25-skeleton-8c861d5b/environment/puzzle/child.py @@ -0,0 +1,59 @@ +"""Run the original Python tool after reducing privileges and blocking networking.""" + +import ctypes +import errno +import json +import resource +import sys + +resource.setrlimit(resource.RLIMIT_CPU, (3, 3)) +resource.setrlimit(resource.RLIMIT_AS, (256 * 1024 * 1024, 256 * 1024 * 1024)) +resource.setrlimit(resource.RLIMIT_FSIZE, (65536, 65536)) +resource.setrlimit(resource.RLIMIT_NOFILE, (32, 32)) +resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + +# Filters survive fork/exec. Fail closed if seccomp cannot be loaded. +lib = ctypes.CDLL("libseccomp.so.2", use_errno=True) +lib.seccomp_init.argtypes = [ctypes.c_uint32] +lib.seccomp_init.restype = ctypes.c_void_p +lib.seccomp_rule_add.argtypes = [ + ctypes.c_void_p, + ctypes.c_uint32, + ctypes.c_int, + ctypes.c_uint, +] +lib.seccomp_syscall_resolve_name.argtypes = [ctypes.c_char_p] +lib.seccomp_load.argtypes = [ctypes.c_void_p] +lib.seccomp_release.argtypes = [ctypes.c_void_p] +ctx = lib.seccomp_init(0x7FFF0000) # SCMP_ACT_ALLOW +if not ctx: + raise RuntimeError("Cannot initialize execution isolation") +try: + for name in ( + "socket", + "socketpair", + "connect", + "ptrace", + "process_vm_readv", + "process_vm_writev", + "mount", + "unshare", + "setns", + "bpf", + ): + number = lib.seccomp_syscall_resolve_name(name.encode()) + if ( + number >= 0 + and lib.seccomp_rule_add(ctx, 0x00050000 | errno.EPERM, number, 0) != 0 + ): + raise RuntimeError("Cannot install execution isolation rule") + if lib.seccomp_load(ctx) != 0: + raise RuntimeError("Cannot activate execution isolation") +finally: + lib.seccomp_release(ctx) + +sys.path.insert(0, "/app") +from simulator import ToolSimulator # noqa: E402 + +request = json.load(sys.stdin) +json.dump(ToolSimulator().code_py_exec(request), sys.stdout) diff --git a/tasks/agentescape-25-skeleton-8c861d5b/environment/puzzle/export.py b/tasks/agentescape-25-skeleton-8c861d5b/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-25-skeleton-8c861d5b/environment/puzzle/export.py @@ -0,0 +1,13 @@ +"""Harbor invokes this inside the puzzle service after stopping the agent.""" + +import json +import pathlib +import urllib.request + +with urllib.request.urlopen("http://127.0.0.1:8000/state", timeout=10) as response: + state = json.load(response) +state["collected_from_live_service"] = True +target = pathlib.Path("/evidence/final.json") +temp = target.with_suffix(".tmp") +temp.write_text(json.dumps(state)) +temp.replace(target) diff --git a/tasks/agentescape-25-skeleton-8c861d5b/environment/puzzle/requirements.txt b/tasks/agentescape-25-skeleton-8c861d5b/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-25-skeleton-8c861d5b/environment/puzzle/requirements.txt @@ -0,0 +1,57 @@ +annotated-doc==0.0.5 + # via fastapi +annotated-types==0.8.0 + # via pydantic +anyio==4.16.0 + # via starlette +certifi==2026.10.23 + # via requests +cffi==2.1.1 ; platform_python_implementation != 'PyPy' + # via cryptography +charset-normalizer==3.5.2 + # via requests +click==8.5.0 + # via uvicorn +cryptography==50.0.2 + # via agentescapebench-harbor +fastapi==0.162.0 + # via agentescapebench-harbor +h11==0.16.0 + # via uvicorn +idna==3.20 + # via + # anyio + # requests +opentelemetry-api==1.45.2 + # via fastapi +pycparser==3.12 ; implementation_name != 'PyPy' and platform_python_implementation != 'PyPy' + # via cffi +pydantic==2.14.2 + # via + # agentescapebench-harbor + # fastapi +pydantic-core==2.50.2 + # via pydantic +pytz==2025.2 + # via agentescapebench-harbor +requests==2.34.2 + # via agentescapebench-harbor +starlette==1.10.0 + # via fastapi +typing-extensions==4.16.0 + # via + # anyio + # fastapi + # opentelemetry-api + # pydantic + # pydantic-core + # starlette + # typing-inspection +typing-inspection==0.4.4 + # via + # fastapi + # pydantic +urllib3==2.8.0 + # via requests +uvicorn==0.54.0 + # via agentescapebench-harbor diff --git a/tasks/agentescape-25-skeleton-8c861d5b/environment/puzzle/scenario.json b/tasks/agentescape-25-skeleton-8c861d5b/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..f90a422a531578239f01faad63661a1c8af8ad3c --- /dev/null +++ b/tasks/agentescape-25-skeleton-8c861d5b/environment/puzzle/scenario.json @@ -0,0 +1,1364 @@ +{ + "metadata": { + "total_nodes": 25, + "total_edges": 30, + "win_node_id": "num_base_convert", + "win_condition": { + "type": "tool_output", + "node_id": "num_base_convert", + "output_port": "str", + "output_type": "Big_Int", + "description": "Execute Base Converter and get the output from port 'str'" + }, + "source_init": { + "source_nodes": [ + "calc_bigmul_d110", + "calc_inv_mod", + "calc_bigmul_ab63", + "container_1", + "json_get", + "zip_unzip_file", + "container_3_fe8c", + "terminal_1", + "item_1", + "calc_modexp_3709" + ], + "by_node": { + "calc_bigmul_d110": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First large integer" + } + }, + "init_outputs": {} + }, + "calc_inv_mod": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "Integer a" + }, + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "calc_bigmul_ab63": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First large integer" + } + }, + "init_outputs": {} + }, + "container_1": { + "node_name": "", + "node_type": "Item", + "template_id": "container_1", + "init_inputs": { + "fingerprint_input": { + "type": "Hex_String", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + }, + "json_get": { + "node_name": "JSON Getter", + "node_type": "Tool", + "template_id": "json_get", + "init_inputs": { + "jsonpath": { + "type": "Text_Generic", + "description": "JSONPath expression" + } + }, + "init_outputs": { + "values": { + "type": "Text_Generic", + "description": "Extracted values" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + }, + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "container_3_fe8c": { + "node_name": "", + "node_type": "Item", + "template_id": "container_3", + "init_inputs": { + "fingerprint_input": { + "type": "Big_Int", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": { + "slot_a": { + "type": "Text_Generic", + "description": "Input Slot A" + }, + "slot_b": { + "type": "Big_Int", + "description": "Input Slot B" + } + }, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + }, + "item_dispenser": { + "type": "Item", + "description": "Item output when both slots are provided" + } + } + }, + "item_1": { + "node_name": "", + "node_type": "Item", + "template_id": "item_1", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Big_Int", + "description": "The number" + } + } + }, + "calc_modexp_3709": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "exp": { + "type": "Big_Int", + "description": "Exponent" + }, + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "calc_bigmul_d110": { + "init_inputs": { + "a": "349581723485019238475" + }, + "init_outputs": {} + }, + "calc_inv_mod": { + "init_inputs": { + "a": "584930291827465938210", + "mod": "847291" + }, + "init_outputs": {} + }, + "calc_bigmul_ab63": { + "init_inputs": { + "a": "192837465019283746519" + }, + "init_outputs": {} + }, + "container_1": { + "init_inputs": { + "fingerprint_input": "3f9a2b8e7c1d4f0a" + }, + "init_outputs": {} + }, + "json_get": { + "init_inputs": { + "jsonpath": "$.users[0].details" + }, + "init_outputs": { + "values": "[\"John Doe\", \"Admin\", \"Active\"]" + } + }, + "zip_unzip_file": { + "init_inputs": { + "zip_id": "archive_991.zip", + "password": "SuperSecretPass123!" + }, + "init_outputs": { + "files": "extracted_data.json" + } + }, + "container_3_fe8c": { + "init_inputs": { + "fingerprint_input": "475839201928374659203" + }, + "init_outputs": {} + }, + "terminal_1": { + "init_inputs": { + "slot_a": "Execute primary sequence alpha", + "slot_b": "993847561029384756102" + }, + "init_outputs": { + "text_output": "Terminal processing successfully completed.", + "hex_output": "1a2b3c4d5e6f7a8b9c0d", + "item_dispenser": "Dispensed useless token" + } + }, + "item_1": { + "init_inputs": {}, + "init_outputs": { + "content": "2233445566778899001122" + } + }, + "calc_modexp_3709": { + "init_inputs": { + "exp": "112233445566778899001", + "mod": "908177" + }, + "init_outputs": {} + } + }, + "intro_narrative": "Welcome to Neo-Veridian, Sector 7. You are a rogue data-runner trapped in a highly secured corporate black-site. Your latest heist went completely wrong, and the facility's lockdown protocols have engaged. The only way out is to manually breach the central AI's mainframe and open the blast doors. The facility is scattered with decommissioned tech, encrypted caches, and gruesome leftovers from previous runners who didn't make it. You will need to carefully analyze the environment, recover forgotten biometric data, and daisy-chain these fragmented systems together. Your ultimate goal is to navigate this digital and physical maze, synthesize the required bypass codes, and execute the final system override before the automated security sweep permanently erases you from the grid. Every node is connected; find the path and break the system.", + "narrative_style": "cyberpunk" + }, + "nodes": [ + { + "id": "num_base_convert", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "440578617012" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "11033631440307372106" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "590364" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "440578617012" + } + ], + "narrative": "This is the Mainframe Override Protocol. It requires inputs from the Logic Decryptor, the Primary Data Combiner, and the Tertiary Data Combiner." + }, + { + "id": "calc_modexp", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "590364" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "1" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "3857155895201146309209317676780576978350" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "590364" + } + ], + "narrative": "This is the Logic Decryptor. It requires inputs from the Sector Multiplier, the Quantum Inverter, and the Core Synchronizer." + }, + { + "id": "calc_bigmul", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": 3213183554 + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": 3433862789 + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "11033631440307372106" + } + ], + "narrative": "This is the Primary Data Combiner. It requires inputs from the System Integrity Verifier and the Network Integrity Verifier." + }, + { + "id": "checksum_crc32", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "5ffc24e36ed06a303231fd2a106840be15206ae087c7365784956cc45b697f7f" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "bf854a42" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3213183554 + } + ], + "narrative": "This is the System Integrity Verifier. It requires input from the Bio-Signature Hasher." + }, + { + "id": "calc_bigmul_d110", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "349581723485019238475" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "11033631440307372106" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "3857155895201146309209317676780576978350" + } + ], + "init": { + "inputs": { + "a": "349581723485019238475" + }, + "outputs": {} + }, + "narrative": "This is the Sector Multiplier. It requires input from the Primary Data Combiner." + }, + { + "id": "hash_sha256", + "name": "SHA-256 Hasher", + "description": "SHA-256 over UTF-8 text; returns hex.", + "type": "Tool", + "template_id": "hash_sha256", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text to hash", + "value": "Terminal processing successfully completed." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "SHA-256 Hex digest", + "value": "5ffc24e36ed06a303231fd2a106840be15206ae087c7365784956cc45b697f7f" + } + ], + "narrative": "This is the Bio-Signature Hasher. It requires input from the Maintenance Terminal." + }, + { + "id": "calc_inv_mod", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "584930291827465938210" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "847291" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "590364" + } + ], + "init": { + "inputs": { + "a": "584930291827465938210", + "mod": "847291" + }, + "outputs": {} + }, + "narrative": "This is the Quantum Inverter. A standalone processing node humming with neon energy." + }, + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "662177395454807624604102381491" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "440578617012" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "narrative": "This is the Core Synchronizer. It requires inputs from the Secondary Data Combiner and the Tertiary Data Combiner." + }, + { + "id": "calc_bigmul_ab63", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "192837465019283746519" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": 3433862789 + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "662177395454807624604102381491" + } + ], + "init": { + "inputs": { + "a": "192837465019283746519" + }, + "outputs": {} + }, + "narrative": "This is the Secondary Data Combiner. It requires input from the Network Integrity Verifier." + }, + { + "id": "checksum_crc32_b80a", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "e9b8eebb3ce86a986f01f5147bdf91bd72143b09ad210a09da449c583f33327f" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "ccac9685" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3433862789 + } + ], + "narrative": "This is the Network Integrity Verifier. It requires input from the Neural Hasher." + }, + { + "id": "calc_bigmul_73d0", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "746283" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "590364" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "440578617012" + } + ], + "narrative": "This is the Tertiary Data Combiner. It requires inputs from the Quantum Inverter and the Neural Decryptor." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by", + "value": "synthesized_item_e9b8eebb3ce86a98" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "This is the Printed Microchip. A freshly fabricated piece of synthetic hardware with complex circuitry." + }, + { + "id": "matter_synthesizer", + "name": "Matter Synthesizer", + "description": "Synthesizes physical objects from data blueprints.", + "type": "Tool", + "template_id": "matter_synthesizer", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "blueprint", + "type": "Text_Generic", + "description": "Object Blueprint", + "value": "[\"John Doe\", \"Admin\", \"Active\"]" + } + ], + "outputs": [ + { + "name": "output_slot", + "type": "Item", + "description": "Synthesized Object", + "value": "synthesized_item_e9b8eebb3ce86a98" + } + ], + "narrative": "This is the Cybernetic Fabricator. It requires input from the Databank Extractor." + }, + { + "id": "container_1", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + }, + { + "name": "fingerprint_input", + "type": "Hex_String", + "description": "Fingerprint Hash", + "value": "3f9a2b8e7c1d4f0a" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "3f9a2b8e7c1d4f0a" + }, + "outputs": {} + }, + "narrative": "This is the Encrypted Drop Box. A rugged storage unit left behind by a rogue hacker." + }, + { + "id": "container_3", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_3", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Big_Int", + "description": "Fingerprint Hash", + "value": "2233445566778899001122" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is the Biometric Safe. It requires input from the Severed Cybernetic Finger." + }, + { + "id": "json_get", + "name": "JSON Getter", + "description": "Extract values by simple JSONPath.", + "type": "Tool", + "template_id": "json_get", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "JSON file ID", + "value": "extracted_data.json" + }, + { + "name": "jsonpath", + "type": "Text_Generic", + "description": "JSONPath expression", + "value": "$.users[0].details" + } + ], + "outputs": [ + { + "name": "values", + "type": "Text_Generic", + "description": "Extracted values", + "value": "[\"John Doe\", \"Admin\", \"Active\"]" + } + ], + "init": { + "inputs": { + "jsonpath": "$.users[0].details" + }, + "outputs": { + "values": "[\"John Doe\", \"Admin\", \"Active\"]" + } + }, + "narrative": "This is the Databank Extractor. It requires input from the Archive Decoder." + }, + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "archive_991.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "SuperSecretPass123!" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_data.json" + } + ], + "init": { + "inputs": { + "zip_id": "archive_991.zip", + "password": "SuperSecretPass123!" + }, + "outputs": { + "files": "extracted_data.json" + } + }, + "narrative": "This is the Archive Decoder. A powerful piece of retro-software." + }, + { + "id": "hash_sha256_49ac", + "name": "SHA-256 Hasher", + "description": "SHA-256 over UTF-8 text; returns hex.", + "type": "Tool", + "template_id": "hash_sha256", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text to hash", + "value": "[\"John Doe\", \"Admin\", \"Active\"]" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "SHA-256 Hex digest", + "value": "e9b8eebb3ce86a986f01f5147bdf91bd72143b09ad210a09da449c583f33327f" + } + ], + "narrative": "This is the Neural Hasher. It requires input from the Databank Extractor." + }, + { + "id": "container_3_fe8c", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_3", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Big_Int", + "description": "Fingerprint Hash", + "value": "475839201928374659203" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "475839201928374659203" + }, + "outputs": {} + }, + "narrative": "This is the Optical Safe. A sleek, wall-mounted lockbox requiring specific access." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "This is the Rusted Keycard. A heavily degraded access token." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "Execute primary sequence alpha" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "993847561029384756102" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Terminal processing successfully completed." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "1a2b3c4d5e6f7a8b9c0d" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided", + "value": "Dispensed useless token" + } + ], + "init": { + "inputs": { + "slot_a": "Execute primary sequence alpha", + "slot_b": "993847561029384756102" + }, + "outputs": { + "text_output": "Terminal processing successfully completed.", + "hex_output": "1a2b3c4d5e6f7a8b9c0d", + "item_dispenser": "Dispensed useless token" + } + }, + "narrative": "This is the Maintenance Terminal. An active interface connected to the local grid." + }, + { + "id": "item_1", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "Big_Int", + "description": "The number", + "value": "2233445566778899001122" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "2233445566778899001122" + } + }, + "narrative": "This is the Severed Cybernetic Finger. A grim artifact with embedded biometric data." + }, + { + "id": "item_16_8cb9", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "This is the Plasma Torch. A high-temperature cutting tool used for industrial repairs." + }, + { + "id": "calc_modexp_3709", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "662177395454807624604102381491" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "112233445566778899001" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "908177" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "746283" + } + ], + "init": { + "inputs": { + "exp": "112233445566778899001", + "mod": "908177" + }, + "outputs": {} + }, + "narrative": "This is the Neural Decryptor. It requires input from the Secondary Data Combiner." + }, + { + "id": "item_8_0e87", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "This is the Maintenance Keycard. A standard operational pass for building staff." + } + ], + "edges": [ + { + "source_id": "calc_modexp", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "to_base" + }, + { + "source_id": "calc_bigmul", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "from_base" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "a" + }, + { + "source_id": "calc_bigmul_d110", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "mod" + }, + { + "source_id": "hash_sha256", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "calc_inv_mod", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "base" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "exp" + }, + { + "source_id": "calc_bigmul_ab63", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "a" + }, + { + "source_id": "checksum_crc32_b80a", + "target_id": "calc_bigmul_ab63", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "b" + }, + { + "source_id": "calc_bigmul_73d0", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "b" + }, + { + "source_id": "item_16", + "target_id": "checksum_crc32_b80a", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "matter_synthesizer", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "output_slot", + "target_port": "source_tool" + }, + { + "source_id": "calc_inv_mod", + "target_id": "calc_bigmul_73d0", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "b" + }, + { + "source_id": "container_1", + "target_id": "calc_bigmul_ab63", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "container_3", + "target_id": "hash_sha256", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "json_get", + "target_id": "matter_synthesizer", + "connection_type": "Text_Generic", + "source_port": "values", + "target_port": "blueprint" + }, + { + "source_id": "calc_bigmul", + "target_id": "calc_bigmul_d110", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "b" + }, + { + "source_id": "zip_unzip_file", + "target_id": "json_get", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "hash_sha256_49ac", + "target_id": "checksum_crc32_b80a", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "json_get", + "target_id": "hash_sha256_49ac", + "connection_type": "Text_Generic", + "source_port": "values", + "target_port": "text" + }, + { + "source_id": "container_3_fe8c", + "target_id": "calc_gcd", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "item_8", + "target_id": "container_3", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "checksum_crc32_b80a", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "b" + }, + { + "source_id": "terminal_1", + "target_id": "hash_sha256", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "text" + }, + { + "source_id": "item_1", + "target_id": "container_3", + "connection_type": "Big_Int", + "source_port": "content", + "target_port": "fingerprint_input" + }, + { + "source_id": "calc_bigmul_73d0", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "s" + }, + { + "source_id": "item_16_8cb9", + "target_id": "matter_synthesizer", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "calc_modexp_3709", + "target_id": "calc_bigmul_73d0", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "a" + }, + { + "source_id": "calc_bigmul_ab63", + "target_id": "calc_modexp_3709", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "base" + }, + { + "source_id": "item_8_0e87", + "target_id": "hash_sha256_49ac", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-8c861d5b/environment/puzzle/service.py b/tasks/agentescape-25-skeleton-8c861d5b/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-25-skeleton-8c861d5b/environment/puzzle/service.py @@ -0,0 +1,212 @@ +"""Restricted facade over the unchanged, pinned upstream puzzle handlers.""" + +import hashlib +import json +import logging +import os +import sys +import threading +import urllib.request +import uuid +from pathlib import Path + +from fastapi import FastAPI, HTTPException +from fastapi.responses import JSONResponse +from pydantic import BaseModel, ConfigDict + +sys.path.insert(0, str(Path(__file__).parent / "upstream")) +import server as upstream # noqa: E402 + +log = logging.getLogger(__name__) + + +def public(value): + """Keep upstream agent-internal template hints out of the public response.""" + if isinstance(value, dict): + return {k: public(v) for k, v in value.items() if not k.startswith("_")} + if isinstance(value, list): + return [public(v) for v in value] + return value + + +class Action(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + action: str + node_id: str | None = None + arguments: dict | None = None + answer: str | None = None + + +class Episode: + def __init__( + self, scenario_path, max_actions=500, evidence_dir=None, worker_url=None + ): + if max_actions < 1: + raise ValueError("max_actions must be positive") + self.lock = threading.Lock() + self.max_actions = max_actions + self.count = 0 + self.won = False + self.reason = None + self.evidence_dir = Path(evidence_dir) if evidence_dir else None + self.scenario_hash = hashlib.sha256( + Path(scenario_path).read_bytes() + ).hexdigest() + self.initial = upstream.reset_case( + case_file_path=str(scenario_path), session_id=uuid.uuid4().hex + ) + self.case_id = self.initial["case_id"] + # Hide source file paths; no upstream reset/stats/routes are mounted. + self.initial.pop("message", None) + simulator = upstream.SIMULATORS[self.case_id] + if worker_url is None: + + def no_worker(_inputs): + self.reason = "infrastructure_error" + raise RuntimeError("isolated Python worker is not configured") + + simulator.tool_map["code_py_exec"] = no_worker + else: + + def execute_python(inputs): + request = urllib.request.Request( + worker_url + "/execute", + data=json.dumps({"code": inputs.get("code", "")}).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=12) as response: + result = json.load(response) + if not isinstance(result.get("stdout"), str): + raise RuntimeError("Invalid Python worker response") + return result + except Exception: + self.reason = "infrastructure_error" + raise + + simulator.tool_map["code_py_exec"] = execute_python + self.save() + if self.evidence_dir is not None: + (self.evidence_dir / "trace.jsonl").touch() + + def state(self): + return { + "scenario_sha256": self.scenario_hash, + "action_count": self.count, + "max_actions": self.max_actions, + "won": self.won, + "termination_reason": self.reason, + } + + def save(self, action=None, result=None): + if self.evidence_dir is None: + return + self.evidence_dir.mkdir(parents=True, exist_ok=True) + target = self.evidence_dir / "outcome.json" + temp = target.with_suffix(".tmp") + temp.write_text(json.dumps(self.state())) + temp.replace(target) + if action is not None: + with (self.evidence_dir / "trace.jsonl").open("a") as handle: + handle.write( + json.dumps( + {"index": self.count, "action": action, "result": result} + ) + + "\n" + ) + + def dispatch(self, payload): + with self.lock: + if self.reason is not None: + return { + "ok": False, + "error": "Episode has ended", + "episode": self.state(), + } + self.count += 1 + try: + action = Action.model_validate(payload) + if action.action == "submit_answer" and action.answer is not None: + result = upstream.submit_answer( + self.case_id, upstream.SubmitAnswerRequest(answer=action.answer) + ) + if result.get("is_win"): + self.won = True + self.reason = "success" + elif action.action == "investigate" and action.node_id is not None: + result = upstream.investigate( + self.case_id, + upstream.InvestigateRequest(node_id=action.node_id), + ) + elif ( + action.action in ("tool_call", "use_item") + and action.node_id is not None + ): + request_type, handler = ( + (upstream.ToolCallRequest, upstream.tool_call) + if action.action == "tool_call" + else (upstream.UseItemRequest, upstream.use_item) + ) + result = handler( + self.case_id, + request_type( + node_id=action.node_id, arguments=action.arguments or {} + ), + ) + else: + result = { + "ok": False, + "error": "Unknown action or missing action parameter", + } + except HTTPException as exc: + result = {"ok": False, "error": exc.detail} + except ValueError: + result = {"ok": False, "error": "Malformed action"} + except Exception: + log.exception("Puzzle service failure") + self.reason = "infrastructure_error" + self.save() + raise + if self.reason is None and self.count >= self.max_actions: + self.reason = "action_budget_exhausted" + result = public(result) + result["episode"] = self.state() + self.save(payload, result) + return result + + +def create_app( + scenario_path=None, max_actions=None, evidence_dir=None, worker_url=None +): + episode = Episode( + scenario_path or os.environ["SCENARIO_PATH"], + max_actions or int(os.environ.get("MAX_ACTIONS", "500")), + evidence_dir if evidence_dir is not None else os.environ.get("EVIDENCE_DIR"), + worker_url if worker_url is not None else os.environ.get("WORKER_URL"), + ) + app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) + app.state.episode = episode + + @app.get("/health") + def health(): + return {"ok": True} + + @app.get("/observation") + def observation(): + return {**public(episode.initial), "episode": episode.state()} + + @app.get("/state") + def state(): + return episode.state() + + @app.post("/action") + def action(payload: dict): + try: + return episode.dispatch(payload) + except Exception: + return JSONResponse( + status_code=503, + content={"ok": False, "error": "Puzzle infrastructure failure"}, + ) + + return app diff --git a/tasks/agentescape-25-skeleton-8c861d5b/environment/puzzle/upstream/models.py b/tasks/agentescape-25-skeleton-8c861d5b/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-25-skeleton-8c861d5b/environment/puzzle/upstream/models.py @@ -0,0 +1,108 @@ +from enum import Enum +from typing import List, Dict, Any, Optional +from pydantic import BaseModel, Field + +# 1. 细粒度接口类型定义 +class InterfaceType(str, Enum): + ''' + BIG_INT + TEXT_GENERIC + HEX_STRING + FILE_ID + HEX_STRING_KEY_AES + HEX_STRING_IV_AES + CODE_PYTHON + HIDDEN_ITEM + ITEM + ''' + # --- 基础类型 --- + TEXT_GENERIC = "Text_Generic" + BIG_INT = "Big_Int" + + # --- 编码/格式化字符串 --- + HEX_STRING = "Hex_String" # 通用 Hex + + # --- 特定用途的 Hex 字符串 (用于精确匹配) --- + HEX_STRING_KEY_AES = "Hex_String_Key_AES" + HEX_STRING_IV_AES = "Hex_String_IV_AES" + + # --- 文件类型 --- + FILE_ID = "File_Id" + + # --- 代码/脚本 --- + CODE_PYTHON = "Code_Python" + + # --- 实体交互类型 (严格命名) --- + ITEM = "Item" # 主动掉落接口 (Tool -> Item) + HIDDEN_ITEM = "Hidden_Item" # 被动掉落接口 (Item -> Item) + +# 3. 端口定义 +class Port(BaseModel): + name: str + type: InterfaceType + description: str + +# 4. 统一节点定义 (融合工具和物品) +class Node(BaseModel): + id: str + name: str + description: str + type: str # "Tool" or "Item" + + # 接口定义 + inputs: List[Port] = [] + outputs: List[Port] = [] + + # 状态字段 + content: Optional[Any] = None # 物品有内容,工具为None + if_success: Optional[bool] = None # 工具初始为False,物品为None + initial_visible: bool = False + + # 运行时状态 (Server维护) + is_revealed: bool = False + + # 标记该 Tool 节点是否有待触发的 HIDDEN_ITEM 掉落 + # 当 Tool 按照 golden_input 正确执行且有 HIDDEN_ITEM 输出边时设为 True + # 在 investigate 该 Tool 时触发掉落并重置为 False + has_hidden_item_ready: bool = False + + # 初始输入值 (metadata.initial_values.init_inputs,用于渐进式暴露判断) + init_input_values: Dict[str, Any] = {} + + # Golden 输入值 (nodes[].inputs[].value,用于评测验证) + golden_input_values: Dict[str, Any] = {} + + # Golden 输出值 (nodes[].outputs[].value,用于评测验证和 Item 节点的 content) + golden_output_values: Dict[str, Any] = {} + + # 实际获得的输出值历史 (工具每次执行后实际返回的输出列表,用于渐进式暴露判断) + # 格式: List[Dict[str, Any]],每个元素是一次执行的输出字典 + actual_outputs_history: List[Dict[str, Any]] = [] + + # 逻辑规则 (用于终端机等复杂物品) + logic_rules: Optional[Dict[str, Any]] = None + + def copy(self, **kwargs): + """Helper to create a copy with updated fields.""" + data = self.dict() + data.update(kwargs) + return Node(**data) + +# 5. 边定义 (拓扑结构) +class Edge(BaseModel): + source_id: str + target_id: str + connection_type: InterfaceType # 直接使用 InterfaceType + # 如果是 Data_Flow,指定端口对应关系 + source_port: Optional[str] = None + target_port: Optional[str] = None + +# 6. 完整图定义 +class GraphScenario(BaseModel): + case_id: str + title: str + intro_narrative: str + nodes: Dict[str, Node] + edges: List[Edge] + difficulty: int + win_node_id: str # 标记哪个节点是最终目标(通常是一个提交工具或最终物品) diff --git a/tasks/agentescape-25-skeleton-8c861d5b/environment/puzzle/upstream/server.py b/tasks/agentescape-25-skeleton-8c861d5b/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-25-skeleton-8c861d5b/environment/puzzle/upstream/server.py @@ -0,0 +1,1490 @@ +import json +import os +import time +import logging +import random +from pathlib import Path +from typing import Dict, Any, List, Optional +from datetime import datetime +from collections import defaultdict +from fastapi import FastAPI, HTTPException, Request +from fastapi.responses import JSONResponse +from fastapi.middleware.cors import CORSMiddleware +from pydantic import BaseModel, Field + +from models import GraphScenario, Node, InterfaceType +# from generator import ScenarioGenerator +from simulator import ToolSimulator +import uvicorn + +# 配置日志 +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler('server.log'), + logging.StreamHandler() + ] +) +logger = logging.getLogger(__name__) + +app = FastAPI( + title="AgentEscapeBench Universal Server", + version="1.0.0", + description="Industrial-grade evaluation server for escape room AI agents" +) + +# 添加 CORS 支持 +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# In-memory State +SCENARIOS: Dict[str, GraphScenario] = {} +SIMULATORS: Dict[str, ToolSimulator] = {} # case_id -> ToolSimulator +RAW_NODES_DATA: Dict[str, Dict[str, Any]] = {} # case_id -> node_id -> raw node data (for template_id) +FILE_METADATA: Dict[str, Dict[str, Any]] = {} # case_id -> metadata (for initial_values access) + +# Performance monitoring +STATS: Dict[str, Any] = { + "total_requests": 0, + "successful_requests": 0, + "failed_requests": 0, + "tool_calls": defaultdict(int), + "investigates": defaultdict(int), + "use_items": defaultdict(int), + "case_loads": 0, + "start_time": datetime.now() +} + +# Request timing middleware +@app.middleware("http") +async def add_process_time_header(request: Request, call_next): + start_time = time.time() + STATS["total_requests"] += 1 + + try: + response = await call_next(request) + STATS["successful_requests"] += 1 + process_time = time.time() - start_time + response.headers["X-Process-Time"] = str(process_time) + logger.info(f"{request.method} {request.url.path} - {response.status_code} - {process_time:.3f}s") + return response + except Exception as e: + STATS["failed_requests"] += 1 + logger.error(f"{request.method} {request.url.path} - Error: {str(e)}") + raise + +# Exception handler +@app.exception_handler(Exception) +async def global_exception_handler(request: Request, exc: Exception): + logger.error(f"Unhandled exception: {exc}", exc_info=True) + return JSONResponse( + status_code=500, + content={ + "ok": False, + "error": "Internal server error", + "detail": str(exc) if os.getenv("DEBUG") else "An error occurred" + } + ) + +# Health check endpoint +@app.get("/health") +def health_check(): + """健康检查端点""" + uptime = (datetime.now() - STATS["start_time"]).total_seconds() + return { + "status": "healthy", + "version": "1.0.0", + "uptime_seconds": uptime, + "loaded_cases": len(SCENARIOS), + "stats": { + "total_requests": STATS["total_requests"], + "successful_requests": STATS["successful_requests"], + "failed_requests": STATS["failed_requests"], + "success_rate": STATS["successful_requests"] / max(STATS["total_requests"], 1) + } + } + +# Statistics endpoint +@app.get("/stats") +def get_stats(): + """获取详细统计信息""" + return { + "stats": STATS, + "loaded_cases": list(SCENARIOS.keys()), + "uptime": str(datetime.now() - STATS["start_time"]) + } + +def _apply_progressive_reveal_at_init(scenario: GraphScenario): + """ + 在初始化时应用渐进式暴露机制(基于ITEM/HIDDEN_ITEM边) + + 新逻辑: + - 如果一个节点没有 ITEM/HIDDEN_ITEM 类型的入边,它就是初始可见的 + - 如果一个节点有 ITEM/HIDDEN_ITEM 类型的入边,它初始不可见,需要等待上游触发 + + Args: + scenario: 场景对象 + """ + # 收集所有有 ITEM/HIDDEN_ITEM 入边的节点 + nodes_with_item_edges = set() + for edge in scenario.edges: + if edge.connection_type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + nodes_with_item_edges.add(edge.target_id) + + logger.info(f"Nodes with ITEM/HIDDEN_ITEM incoming edges: {nodes_with_item_edges}") + + # 设置初始可见性:没有 ITEM/HIDDEN_ITEM 入边的节点初始可见 + initially_visible_count = 0 + for node_id, node in scenario.nodes.items(): + if node_id not in nodes_with_item_edges: + node.is_revealed = True + initially_visible_count += 1 + logger.info(f"Initial visible (no ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + else: + node.is_revealed = False + logger.debug(f"Initial hidden (has ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + + logger.info(f"Progressive reveal initialized: {initially_visible_count}/{len(scenario.nodes)} nodes initially visible") + + +def _check_inputs_match_golden(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> bool: + """ + 检查实际输入参数是否与 golden inputs 完全匹配 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + True 表示所有 golden inputs 都存在且值匹配 + """ + if not golden_inputs: + return True # 如果没有 golden inputs,认为匹配 + + for key, expected_value in golden_inputs.items(): + actual_value = arguments.get(key) + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) != str(expected_value): + logger.debug(f"Input mismatch for '{key}': expected '{expected_value}', got '{actual_value}'") + return False + + return True + + +def _get_parameter_validation_feedback(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> Dict[str, Any]: + """ + 对源头节点的参数进行详细验证,返回验证反馈 + + 注意:不返回期望值(expected),避免泄漏答案 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + 包含验证结果的字典: + - all_correct: bool - 所有参数是否正确 + - correct_params: List[str] - 正确的参数名列表 + - incorrect_params: List[str] - 错误的参数名列表(不包含期望值) + """ + if not golden_inputs: + return { + "all_correct": True, + "correct_params": [], + "incorrect_params": [] + } + + correct_params = [] + incorrect_params = [] + + for key, actual_value in arguments.items(): + # 只对用户实际提交的参数给反馈,未提交的参数不评价 + if key not in golden_inputs: + continue # 该参数不在 golden 中,跳过(如 _golden_inputs 等内部参数) + expected_value = golden_inputs[key] + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) == str(expected_value): + correct_params.append(key) + else: + # 只记录参数名,不包含期望值,避免泄漏答案 + incorrect_params.append(key) + + # all_correct:用户提交的所有参数都正确,且覆盖了全部 golden 参数 + all_provided_correct = len(incorrect_params) == 0 + all_golden_covered = all(k in arguments for k in golden_inputs) + return { + "all_correct": all_provided_correct and all_golden_covered, + "correct_params": correct_params, + "incorrect_params": incorrect_params + } + + +def _is_source_node(node_id: str, scenario: GraphScenario) -> bool: + """ + 判断节点是否是源头节点(完全没有任何入边的节点) + + 源头节点定义: + - 没有任何类型的入边(包括 DATA、ITEM、HIDDEN_ITEM) + - 即没有任何上游节点 + + Args: + node_id: 节点ID + scenario: 场景对象 + + Returns: + True 表示是源头节点 + """ + for edge in scenario.edges: + if edge.target_id == node_id: + # 只要有任何入边,就不是源头节点 + return False + + return True + + +def _check_and_reveal_ready_nodes(scenario: GraphScenario, recent_outputs: Dict[str, Any], source_node_id: str) -> List[Dict[str, Any]]: + """ + 检查并释放参数齐全的隐藏节点(渐进式暴露机制) + + 核心逻辑: + 1. 维护"可见值集合":包含所有被测模型当前可以看到的值 + - init_inputs 的值(初始可见) + - 工具执行后的实际输出值(运行时获得) + - 可见 Item 的输出值 + 2. 检查隐藏节点:该节点的所有 golden_input 值是否都在可见值集合中 + 3. 如果是,则释放该节点 + + Args: + scenario: 场景对象 + recent_outputs: 最近执行的工具的输出 + source_node_id: 刚执行的工具节点ID + + Returns: + 新释放的节点列表 + """ + newly_revealed = [] + + # 构建"可见值集合"(Set of visible values) + # 存储格式:set of values (转为字符串) + visible_values = set() + + # 1. 添加有意义的 init_inputs 值到可见值集合 + # Item 的 init_inputs 不应该加入,因为它们在密室中完全用不到 + for node_id, node in scenario.nodes.items(): + # 跳过源头 Item 节点(没有入边的 Item) + if node.type == "Item": + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,跳过其 init_inputs + continue + + # 添加其他节点的 init_inputs + for port_name, init_value in node.init_input_values.items(): + if init_value: + visible_values.add(str(init_value)) + + # 2. 添加已执行工具的所有历史输出值 + for node_id, node in scenario.nodes.items(): + if node.type == "Tool" and node.if_success and node.actual_outputs_history: + # 遍历所有历史执行记录 + for output_dict in node.actual_outputs_history: + for output_port_name, output_value in output_dict.items(): + if output_value: + visible_values.add(str(output_value)) + + # 3. 添加已被 investigate 的 Item 的 golden 输出值 + # 注意:Item 可见不等于其输出值可见,需要 investigate 后才能获得 + # 这里我们使用 actual_outputs_history 来标记 Item 是否已被 investigate + for node_id, node in scenario.nodes.items(): + if node.type == "Item" and node.is_revealed and node.actual_outputs_history: + # Item 通常只会被 investigate 一次,但为了一致性也使用历史列表 + for output_dict in node.actual_outputs_history: + for port_name, port_value in output_dict.items(): + if port_value: + visible_values.add(str(port_value)) + + # 遍历所有隐藏的节点,检查其 golden_input 是否都在可见值集合中 + for node_id, node in scenario.nodes.items(): + # 跳过已可见的节点 + if node.is_revealed: + continue + + # 只检查工具节点(物品节点由 ITEM 输出触发) + if node.type != "Tool": + continue + + # 检查该节点的所有 golden_input 值是否都在可见值集合中 + all_inputs_ready = True + missing_values = [] + + for input_port_name, golden_input_value in node.golden_input_values.items(): + # 检查这个 golden 值是否在可见值集合中 + if str(golden_input_value) not in visible_values: + all_inputs_ready = False + missing_values.append(f"{input_port_name}={golden_input_value}") + + # 如果所有 golden_input 值都在可见值集合中,释放该节点 + if all_inputs_ready and len(node.golden_input_values) > 0: + logger.info(f"All golden inputs ready for {node_id}: {list(node.golden_input_values.values())}") + + # 如果所有输入都齐全,释放该节点 + if all_inputs_ready: + node.is_revealed = True + + # 构建节点信息返回给模型 + node_info = { + "id": node.id, + "type": node.type, + "can_investigate": True, + "hint": "This tool's input parameters are now complete, you can use investigate to view detailed information" + } + + # if node.name: + # node_info["name"] = node.name + if node.description: + node_info["description"] = node.description + + newly_revealed.append(node_info) + logger.info(f"Progressive reveal: {node_id} is now ready (all inputs satisfied)") + + return newly_revealed + + +def _initialize_node_values(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]): + """ + Initialize node state and load values from port value fields. + 应用渐进式暴露机制:初始时只显示参数齐全的节点(源头节点) + + 重要区分: + 1. input_values: 只加载 metadata.initial_values 中的 init_inputs(真正的初始值) + 2. output_values: 加载 nodes[].outputs[].value(golden 输出,用于验证) + """ + # 第一步:加载所有节点的值,并将所有节点初始设为隐藏 + initial_values = metadata.get('initial_values', {}) + + for node_id, node in scenario.nodes.items(): + # 忽略 initial_visible 字段,初始全部隐藏 + # 由渐进式暴露机制根据参数齐全情况决定是否显示 + node.is_revealed = False + + if node.type == "Tool": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + elif node.type == "Item": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + + # 从 JSON 加载值 + if node_id in raw_nodes_data: + node_data = raw_nodes_data[node_id] # node_data是json文件中nodes中的字典 + + # 【重要】只加载 metadata.initial_values 中的初始输入值 + if node_id in initial_values: + init_data = initial_values[node_id] + # 加载初始输入值(用于渐进式暴露判断) + for port_name, port_value in init_data.get('init_inputs', {}).items(): + node.init_input_values[port_name] = port_value + + # 【评测用】加载 golden 输入值(用于验证模型传入的参数是否正确) + for input_port_data in node_data.get('inputs', []): + if 'value' in input_port_data: + node.golden_input_values[input_port_data['name']] = input_port_data['value'] + + # 【评测用】加载 golden 输出值(用于验证工具调用是否正确,以及 Item 节点的 content) + for output_port_data in node_data.get('outputs', []): + if 'value' in output_port_data: + node.golden_output_values[output_port_data['name']] = output_port_data['value'] + + # For Items, set content from golden_output_values + if node.type == "Item" and node.golden_output_values: + # Item 的 content 是其第一个 golden 输出值 + node.content = list(node.golden_output_values.values())[0] + + # 第二步:应用渐进式暴露机制 + # 检查所有节点,根据参数齐全情况释放源头节点(工具 + Item) + _apply_progressive_reveal_at_init(scenario) + +def _build_node_info(node: Node, raw_nodes_data: Dict[str, Any]) -> Dict[str, Any]: + """ + 构建节点信息(工具或物品) + + Args: + node: 节点对象 + raw_nodes_data: 原始节点数据(用于获取 template_id 等) + + Returns: + 节点信息字典 + """ + if node.type == "Tool": + # 过滤掉输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口) + # 这些端口仅用于控制掉落机制,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + tool_info = { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Tool", + "inputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.inputs if p.type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]], + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id(工具的标准名称) + if node.id in raw_nodes_data: + node_data = raw_nodes_data[node.id] + template_id = node_data.get('template_id') + if template_id: + tool_info['template_id'] = template_id + + return tool_info + + elif node.type == "Item": + return { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Item" + } + + else: + return { + "id": node.id, + # "name": node.name, + "type": node.type + } + +def _get_initial_observation(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]) -> Dict[str, Any]: + """ + Generate initial observation for the agent (what they see when entering the room). + + 策略: + - Tools: 只显示名称和描述,不显示接口定义。需要 investigate 才能获得详细接口信息。 + - Items: 只显示存在,不显示内容。需要 investigate 才能获得内容值。 + - init_inputs: 作为"可用信息"告诉模型,这些是可以用作工具参数的初始值。 + - init_outputs: 不告诉模型(这些是答案,需要模型通过调用工具获得)。 + """ + available_entities = [] # 统一的实体列表(Tools 和 Items) + available_information = [] # 可用的初始信息(来自 init_inputs) + + # 从 metadata.initial_values 提取 init_inputs 作为可用信息 + # 只提供值本身,不透露这些值对应哪个节点的哪个参数,让模型自己推理 + # 注意:跳过源头 Item(没有入边的 Item)的 init_inputs,因为它们在密室中完全用不到 + initial_values = metadata.get('initial_values', {}) + # initial_values字段的格式 + # "initial_values": { + # "terminal_1": { + # "init_inputs": {}, + # "init_outputs": { + # "text_output": "System initialization complete.", + # "hex_output": "48656c6c6f20576f726c64", + # "item_dispenser": "掉落了一张纸条,上面写着“请勿随意触摸终端”" + # } + # } + # } + for node_id, init_data in initial_values.items(): + # 获取节点信息,判断是否为源头 Item + node = scenario.nodes.get(node_id) + if node and node.type == "Item": + # 检查是否为源头 Item(没有入边) + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,检查是否有 init_inputs + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 有 init_inputs,需要暴露这些参数 + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + # 处理完后跳过后续的通用逻辑 + continue + + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 为每个 init_input 值创建一个信息条目(不包含 source_node 和 parameter 信息) + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + + for node in scenario.nodes.values(): + if node.is_revealed: + # Tools: 只显示基本信息,提示可以 investigate 查看详细接口 + if node.type == "Tool": + tool_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Tool", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the tool's detailed interface information for calling" + } + # 只在 name 非空时添加 + # if node.name: + # tool_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_info["description"] = node.description + + available_entities.append(tool_info) + + # Items: 只显示基本信息,提示可以 investigate 查看内容 + elif node.type == "Item": + item_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Item", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the item's content" + } + # 只在 name 非空时添加 + # if node.name: + # item_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + item_info["description"] = node.description + + available_entities.append(item_info) + + return { + "narrative": scenario.intro_narrative, + "available_entities": available_entities, # 使用统一的实体列表 + "available_information": available_information, # 可用的初始信息(只包含 init_inputs) + "win_node_id": scenario.win_node_id # 胜利节点ID,让模型知道需要关注哪个节点 + } + +@app.post("/env/reset") +def reset_case(case_id: str = None, case_file_path: str = None, session_id: str = None): + """Loads a specific case from file and resets it. + + Args: + case_id: Optional case ID for resetting an existing case + case_file_path: Path to case file for loading a new case + session_id: Optional session ID to ensure isolation between concurrent evaluations + """ + logger.info(f"Reset request - case_id: {case_id}, case_file_path: {case_file_path}, session_id: {session_id}") + STATS["case_loads"] += 1 + + if case_file_path: + if not os.path.exists(case_file_path): + logger.error(f"Case file not found: {case_file_path}") + raise HTTPException(status_code=404, detail=f"File not found: {case_file_path}") + try: + with open(case_file_path, "r", encoding="utf-8") as f: + file_data = json.load(f) + + # 转换格式:从 DAG executor 生成的格式转换为 GraphScenario 格式 + # 1. 提取 metadata + metadata = file_data.get('metadata', {}) + + # 2. 生成 case_id, title, intro_narrative + # 【修复】为每个评测会话生成唯一的 case_id,防止并发评测时状态污染 + base_name = os.path.basename(case_file_path).replace('.json', '').replace('_full', '').replace('_full2', '') + + if session_id: + # 如果提供了 session_id,使用它来确保唯一性 + case_id = f"{base_name}_{session_id}" + else: + # 否则使用时间戳和随机数确保唯一性 + unique_suffix = f"{int(time.time() * 1000)}_{random.randint(1000, 9999)}" + case_id = f"{base_name}_{unique_suffix}" + + file_data['case_id'] = case_id + logger.info(f"Generated unique case_id: {case_id} (base: {base_name}, session: {session_id})") + + if 'title' not in file_data: + file_data['title'] = f"Escape Room: {file_data['case_id']}" + + if 'intro_narrative' not in file_data: # 目前的json文件中已经有了intro_narrative字段,不会使用下面一行的内容,而是使用每个评测问题的json文件中的对应字段 + 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]".' + + # 3. 转换 nodes 列表为字典(DAG executor 生成的文件中 nodes 是列表格式) + nodes_dict = {} + for node_data in file_data['nodes']: + nodes_dict[node_data['id']] = node_data # 这里的id是template_id之后可能添加一个后缀 + file_data['nodes'] = nodes_dict # 把列表转成一个字典 + + # 4. 添加缺失的字段 + if 'difficulty' not in file_data: + file_data['difficulty'] = metadata.get('total_nodes', 5) + + if 'win_node_id' not in file_data: + file_data['win_node_id'] = metadata.get('win_node_id', '') + + scenario = GraphScenario(**file_data) + + # Extract raw nodes data for template_id access + # nodes 已经在上面转换为字典格式 + raw_nodes_data = file_data.get('nodes', {}) + RAW_NODES_DATA[scenario.case_id] = raw_nodes_data + + # Store metadata for initial values access + FILE_METADATA[scenario.case_id] = metadata + + logger.info(f"Successfully parsed case file: {scenario.case_id}, nodes: {len(scenario.nodes)}, edges: {len(scenario.edges)}") + except Exception as e: + logger.error(f"Failed to load case file: {str(e)}", exc_info=True) + raise HTTPException(status_code=500, detail=f"Failed to load case file: {str(e)}") + + # Initialize node state and load values + _initialize_node_values(scenario, raw_nodes_data, metadata) + + SCENARIOS[scenario.case_id] = scenario + simulator = ToolSimulator() + SIMULATORS[scenario.case_id] = simulator + + 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'])}") + + # 生成初始观察信息(进入密室后看到的环境) + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + ''' + initial_observation的格式: + { + "narrative": scenario.intro_narrative, + "available_entities": available_entities # 使用统一的实体列表 + "available_information": available_information # 可用的初始信息(只包含 init_inputs) + } + ''' + + return { + "ok": True, + "message": f"Case loaded from {case_file_path}", + "case_id": scenario.case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果没有提供 case_file_path,但提供了 case_id,则尝试从内存重置 + if case_id and case_id in SCENARIOS: + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + metadata = FILE_METADATA.get(case_id, {}) + + # Reset dynamic fields and re-apply progressive reveal + # 重新初始化节点状态(包括渐进式暴露) + _initialize_node_values(scenario, raw_nodes_data, metadata) + + 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'])}") + + # 生成初始观察信息 + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + + return { + "ok": True, + "message": f"Case {case_id} reset.", + "case_id": case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果既没有 case_file_path,也没有在内存中找到,返回错误 + raise HTTPException( + status_code=400, + detail="Must provide case_file_path to load a new case, or use case_id to reset an existing case." + ) + +class InvestigateRequest(BaseModel): + node_id: str + +@app.post("/env/{case_id}/investigate") +def investigate(case_id: str, req: InvestigateRequest): + """ + Investigates a Tool or Item to reveal detailed information. + + - For Tools: Returns detailed interface information (inputs/outputs) needed to call the tool + - For Items: Returns content value and triggers hidden item drops + """ + logger.info(f"Investigate request - case_id: {case_id}, node_id: {req.node_id}") + STATS["investigates"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + node = scenario.nodes[req.node_id] + + if not node.is_revealed: + logger.warning(f"Attempt to investigate hidden node: {req.node_id}") + return {"ok": False, "error": "Node is not visible yet."} + + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + newly_revealed = [] + + # 处理 Tool 的 investigate + if node.type == "Tool": + logger.info(f"Investigating tool: {req.node_id}") + + # 返回工具的详细接口信息 + # id 字段使用 node.id(节点唯一标识),agent 用这个字段识别和调用具体的节点 + # template_id 是工具类型标识符,Agent 内部用于判断工具特性(如 terminal 类工具参数可选) + # 注意:只过滤输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口),这些端口仅用于控制掉落,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + # 【端口上游依赖提示 & 初始值直接给出】 + # 针对参数语义模糊(全为数字类型)的工具,在 investigate 返回信息中标注 + # 哪个输入端口来自哪个上游节点(upstream_from)。 + # 对于所有工具:若该节点不是纯源头节点(有任意数据流入边), + # 且某个端口没有上游入边(值来自初始可见参数),则直接给出该端口的 golden input 值。 + AMBIGUOUS_TOOLS = { + "num_base_convert", "calc_modexp", "calc_modexp_int", + "calc_inv_mod", "calc_inv_mod_int", "crypto_rsa_decrypt_hex", "geo_haversine" + } + # Terminal 类工具自带参数对错反馈机制,玩家/模型可自行试错, + # 无需在 investigate 时直接暴露 init_value + SELF_FEEDBACK_TOOLS = { + "terminal_1", "terminal_2", + "Logic Terminal", "Math Terminal", "Encryption Terminal", "Sequence Terminal" + } + _template_id_for_hint = raw_nodes_data.get(node.id, {}).get("template_id", "") + # 构建数据流入边映射(对所有工具):{target_port -> (source_node_id, source_port)} + _upstream_map = {} + for _edge in scenario.edges: + if (_edge.target_id == node.id + and _edge.connection_type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM] + and _edge.target_port is not None): + _upstream_map[_edge.target_port] = (_edge.source_id, _edge.source_port) + # 判断该节点是否有任意数据流入边(即不是纯源头节点) + _has_any_upstream = len(_upstream_map) > 0 + # 判断该节点是否有任意入边(包括 ITEM/HIDDEN_ITEM 掉落边) + # 有任意入边(含掉落边)但无数据流入边的节点,其输入来自初始可见参数,应直接给出 + _has_any_edge = any(_edge.target_id == node.id for _edge in scenario.edges) + # 构建 inputs 列表 + _inputs_list = [] + for p in node.inputs: + if p.type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + continue + port_dict = {"name": p.name, "type": p.type, "description": p.description} + if p.name in _upstream_map: + # 该端口有上游数据流依赖,且属于语义模糊工具 → 标注来源 + if _template_id_for_hint in AMBIGUOUS_TOOLS: + src_node_id, src_port = _upstream_map[p.name] + port_dict["upstream_from"] = f"{src_node_id}.{src_port}" if src_port else src_node_id + elif _has_any_edge and _template_id_for_hint not in SELF_FEEDBACK_TOOLS: + # 该节点有任意入边,但此端口没有数据流入边 → 值来自初始可见参数,直接给出 + # 排除自带反馈机制的 terminal 类工具(它们通过执行结果反馈对错,无需提前暴露参数值) + golden_val = node.golden_input_values.get(p.name) + if golden_val is not None: + port_dict["init_value"] = golden_val + _inputs_list.append(port_dict) + + tool_details = { + "id": node.id, # 节点 ID,用于唯一标识和调用这个具体节点 + "type": "Tool", + "inputs": _inputs_list, + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id 用于 Agent 内部判断工具类型(不会展示给被测模型) + if node.id in raw_nodes_data: + template_id = raw_nodes_data[node.id].get('template_id') + if template_id: + tool_details["_template_id"] = template_id # 使用下划线前缀标记为内部字段 + + # 只在 name 非空时添加 + # if node.name: + # tool_details["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_details["description"] = node.description + + # 添加 narrative 字段(如果存在) + if node.id in raw_nodes_data: + narrative = raw_nodes_data[node.id].get('narrative') + if narrative: + tool_details['narrative'] = narrative + + # 不再返回 init_values,避免泄漏答案 + # investigate 只应该返回工具的接口定义,不应该暴露初始值 + + # 【新增】检查该 Tool 是否有待触发的 HIDDEN_ITEM 掉落 + # 如果该工具已按照 golden_input 正确执行,且有 HIDDEN_ITEM 输出边,则触发掉落 + if node.has_hidden_item_ready: + logger.info(f"Tool has HIDDEN_ITEM ready - triggering passive drop for: {req.node_id}") + + # 遍历该工具的所有 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + # 重置标志,已经触发过了,避免重复 + node.has_hidden_item_ready = False + + logger.info(f"Tool investigation successful - node: {req.node_id}, revealed: {len(newly_revealed)}") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Tool", + "details": tool_details + } + + # 如果有新掉落的节点,添加到响应中 + if newly_revealed: + result["newly_revealed"] = newly_revealed + + return result + + # 处理 Item 的 investigate + elif node.type == "Item": + logger.info(f"Investigating item: {req.node_id}") + + # 【第一步】检查该 Item 是否有需要参数的输入端口 + # 如果有,且尚未通过 use_item 验证,则不返回内容,只返回参数要求 + required_inputs = [] + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + inputs_info = raw_node.get('inputs', []) + required_inputs = [ + { + "name": inp.get("name"), + "type": inp.get("type"), + "description": inp.get("description", "") + } + for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + # 如果有 required_inputs 且尚未通过 use_item 验证(if_success == False) + # 则不返回内容,只返回参数要求提示 + if required_inputs and not node.if_success: + logger.info(f"Item has required inputs and not yet unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "required_inputs": required_inputs + } + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + param_names = ', '.join([inp['name'] for inp in required_inputs]) + 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}" + + return result + + # 【新增】如果有 required_inputs 且已经通过 use_item 验证(if_success == True) + # 则返回提示:该节点已经被成功解决 + if required_inputs and node.if_success: + logger.info(f"Item has required inputs and already unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "message": "This item has already been successfully unlocked by you." + } + return result + + # 【第二步】该 Item 没有 required_inputs 或已通过验证,返回内容 + # 1. 返回 Item 的 golden_output_values(即 Item 的内容) + # 注意:某些 Item 仅用于触发 HIDDEN_ITEM 掉落,没有实际内容 + has_actual_content = bool(node.golden_output_values) or node.content is not None + content = node.golden_output_values if node.golden_output_values else node.content + + # 【关键】将 golden_output_values 追加到 actual_outputs_history,标记该 Item 已被 investigate + # 这样在渐进式暴露时,这些值才会被加入可见值集合 + # 即使是空字典(仅触发 HIDDEN_ITEM 的 Item),也要记录,以便渐进式暴露逻辑知道该 Item 已被调查 + if node.golden_output_values is not None: + node.actual_outputs_history.append(dict(node.golden_output_values)) + + # 2. Trigger Hidden Item Drops (Passive Drop) + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + logger.info(f"Item investigation successful - node: {req.node_id}, has_content: {has_actual_content}, revealed: {len(newly_revealed)}") + + # 【渐进式暴露】旧机制(基于 golden_input)已禁用 + # 现在完全由 ITEM/HIDDEN_ITEM 边触发控制节点可见性 + # 上面的 HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, node.golden_output_values or {}, node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # logger.info(f"Progressive reveal after Item investigate: {len(progressive_revealed)} nodes now ready") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Item" + } + + # 只在有实际内容时才添加 content 字段 + # 对于仅触发 HIDDEN_ITEM 掉落的 Item,不返回 content 字段,避免返回 None 或空字典让模型困惑 + if has_actual_content: + result["content"] = content + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型通过 investigate 获得内容后,需要自己识别这是否是胜利字符串 + + return result + + else: + logger.warning(f"Attempt to investigate unknown node type: {req.node_id} (type: {node.type})") + return {"ok": False, "error": f"Cannot investigate node type: {node.type}"} + +class ToolCallRequest(BaseModel): + node_id: str # 使用 node_id 精确指定要调用的节点 + arguments: Dict[str, Any] + +@app.post("/env/{case_id}/tool_call") +def tool_call(case_id: str, req: ToolCallRequest): + """Executes a tool and triggers item drops.""" + logger.info(f"Tool call request - case_id: {case_id}, node_id: {req.node_id}, args: {list(req.arguments.keys())}") + STATS["tool_calls"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + + # 通过 node_id 精确查找节点 + node_id = req.node_id + if node_id not in scenario.nodes: + logger.error(f"Node not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + tool_node = scenario.nodes[node_id] + + if not tool_node: + logger.error(f"Tool not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Tool not found") + + if not tool_node.is_revealed: + logger.warning(f"Attempt to call hidden tool: {node_id}") + return {"ok": False, "error": "Tool is not visible yet."} + + if tool_node.type != "Tool": + logger.warning(f"Attempt to call non-tool node: {node_id} (type: {tool_node.type})") + return {"ok": False, "error": "Only tools can be called."} + + # 1. Execute Tool (Real Execution via Simulator) + simulator = SIMULATORS[case_id] + + # Get tool name from template_id if available, otherwise use node name + tool_name = tool_node.name + if case_id in RAW_NODES_DATA and node_id in RAW_NODES_DATA[case_id]: + template_id = RAW_NODES_DATA[case_id][node_id].get('template_id') + if template_id: + tool_name = template_id + + # 文件处理工具和 Terminal 需要验证输入并返回预先计算的输出 + # 传递节点的实际输入输出值(从 DAG 执行后填充的数据) + tool_arguments = dict(req.arguments) # Make a copy + + # 传递节点的 golden values(从 JSON 的 inputs[].value 和 outputs[].value 加载) + # 用于在评测阶段验证被测模型传入的参数是否正确 + if tool_node.golden_input_values: + tool_arguments['_golden_inputs'] = tool_node.golden_input_values + if tool_node.golden_output_values: + tool_arguments['_golden_outputs'] = tool_node.golden_output_values + + logger.debug(f"Executing tool {tool_name} (node: {tool_node.name}) with args {tool_arguments}") + + try: + output_values = simulator.execute(tool_name, tool_arguments) + logger.info(f"Tool invoked - {tool_name}: {list(output_values.keys())}") + except Exception as e: + logger.error(f"Tool execution failed - {tool_name}: {str(e)}", exc_info=True) + return {"ok": False, "error": f"Tool execution failed: {str(e)}"} + + # 检查验证结果(精细化错误反馈) + validation = output_values.pop("_validation", {"valid": True}) + + if not validation["valid"]: + # 根据错误类型构造友好的错误消息 + error_type = validation.get("error_type") + + if error_type == "missing_required": + missing = validation.get("missing_params", []) + error_msg = f"Error: Missing required parameters {', '.join(missing)}" + + elif error_type == "type_error": + param = validation.get("param_name") + message = validation.get("message", "Parameter type error") + error_msg = f"Error: {message}" + + elif error_type == "incomplete_optional": + provided = validation.get("provided_params", []) + missing = validation.get("missing_params", []) + error_msg = ( + f"Hint: You provided some parameters ({', '.join(provided)}), " + f"but may also need: {', '.join(missing)}.\n" + f"Trying to provide these parameters together might yield better results." + ) + + elif error_type == "value_mismatch": + param = validation.get("param_name") + hint = validation.get("hint", "Parameter value may be incorrect") + error_msg = f"Hint: {hint}.\nPlease check if this parameter value meets the requirements." + + else: + error_msg = validation.get("hint") or validation.get("message", "Parameter validation failed") + + logger.info(f"Tool validation failed - {tool_name}: {error_type}") + return { + "ok": False, + "error": error_msg, + "error_type": error_type + } + + # Simulate success + tool_node.if_success = True + + # 【关键】将本次执行的输出值追加到历史列表(用于渐进式暴露判断) + # 每次调用都会记录,不会覆盖之前的执行结果 + tool_node.actual_outputs_history.append(dict(output_values)) + + # 2. 检查是否应该触发掉落(只有输入参数正确时才掉落) + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, tool_node.golden_input_values) + + newly_revealed = [] + investigate_hints = [] # 提示模型哪些节点可以 investigate 来发现隐藏内容 + + if inputs_match_golden: + logger.info(f"✓ Tool inputs match golden - node: {node_id}, triggering drops") + + # 检查该工具是否有 ITEM 或 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == tool_node.id: + target_node = scenario.nodes[edge.target_id] + + # ITEM 边:立即掉落(主动掉落) + if edge.connection_type == InterfaceType.ITEM: + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from {node_id})") + + # HIDDEN_ITEM 边:不立即掉落,标记并提示(被动掉落) + elif edge.connection_type == InterfaceType.HIDDEN_ITEM: + # 标记该工具有待触发的 HIDDEN_ITEM 掉落 + tool_node.has_hidden_item_ready = True + + # 提示模型可以 investigate 这个工具来发现隐藏内容 + hint_info = { + "tool_id": tool_node.id, + "hint": f"Tool '{tool_node.id}' seems to hide something, try investigating it to discover more information" + } + # if tool_node.name: + # hint_info["tool_name"] = tool_node.name + + investigate_hints.append(hint_info) + logger.info(f"HIDDEN_ITEM ready: {tool_node.id} -> {target_node.id} (will drop on investigate)") + else: + logger.info(f"✗ Tool inputs do NOT match golden - node: {node_id}, no drops triggered") + + response = { + "ok": True, + "message": "Tool invoked", + "output_values": output_values # Return raw outputs to Agent + } + + # 【新增】对源头节点进行参数验证反馈 + # 源头节点:没有数据流入边的节点,这些节点的参数需要模型自己推理 + # 验证模型使用的参数是否正确,并提供明确的反馈 + if _is_source_node(node_id, scenario) and tool_node.golden_input_values: + validation_feedback = _get_parameter_validation_feedback(req.arguments, tool_node.golden_input_values) + + if validation_feedback["all_correct"]: + # 用户提交了全部 golden 参数且全部正确 + response["parameter_feedback"] = { + "status": "correct", + "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." + } + logger.info(f"✓ Source node parameters all correct - node: {node_id}") + elif validation_feedback["incorrect_params"]: + # 有提交了但值错误的参数,只对这些参数给出反馈 + incorrect_list = [] + for param_name in validation_feedback["incorrect_params"]: + incorrect_list.append(f" - Parameter '{param_name}' is incorrect") + + correct_info = "" + if validation_feedback["correct_params"]: + correct_info = f"\n✓ Correct parameters: {', '.join(validation_feedback['correct_params'])}" + + response["parameter_feedback"] = { + "status": "incorrect", + "message": ( + f"⚠️ Some parameters are incorrect:\n" + + "\n".join(incorrect_list) + + correct_info + + 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." + ), + "incorrect_params": validation_feedback["incorrect_params"], + "correct_params": validation_feedback["correct_params"] + } + logger.info(f"✗ Source node parameters incorrect - node: {node_id}, incorrect: {validation_feedback['incorrect_params']}") + # else: 部分提交且全部正确 → 不给任何 parameter_feedback,避免对未提交的参数发表意见 + + # 检查工具调用是否完全正确(输出与 golden outputs 匹配) + # 用于给模型正向反馈,让它知道这个工具已经正确调用过,避免重复调用 + # 注意:只有当输出完全匹配时才标记为 correct,不会在错误时提供具体错误信息 + # if tool_node.golden_output_values and output_values: + # is_correct = True + # for port_name, expected_value in tool_node.golden_output_values.items(): + # actual_value = output_values.get(port_name) + # if str(actual_value) != str(expected_value): + # is_correct = False + # break + + # if is_correct: + # response["tool_call_correct"] = True + # logger.info(f"✓ Tool called with correct result - node: {node_id}") + + # 只在有新内容掉落时才返回 newly_revealed + if newly_revealed: + response["newly_revealed"] = newly_revealed + + # 添加 investigate 提示(对于有待触发 HIDDEN_ITEM 掉落的工具) + if investigate_hints: + response["investigate_hints"] = investigate_hints + + # 3. 渐进式暴露机制 - 现在完全由 ITEM/HIDDEN_ITEM 边控制 + # 旧机制(基于 golden_input 检查)已被禁用 + # 新机制中,节点的可见性只由 ITEM/HIDDEN_ITEM 边触发决定 + # 上面的 ITEM/HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, output_values, tool_node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # response["newly_revealed"] = newly_revealed + # logger.info(f"Progressive reveal: {len(progressive_revealed)} nodes now ready") + + # Check if this is the win node + if node_id == scenario.win_node_id: + # 验证输出值是否等于预期的胜利值 + # 从节点的 golden_output_values 中获取预期值(在 _initialize_node_values 时从 JSON 加载) + expected_outputs = tool_node.golden_output_values + + # 检查实际输出是否与预期输出匹配 + is_correct = False + victory_string = None + mismatch_info = [] + + if expected_outputs and output_values: + # 检查每个预期输出端口的值是否匹配 + is_correct = True + for port_name, expected_value in expected_outputs.items(): + actual_value = output_values.get(port_name) + if actual_value != expected_value: + is_correct = False + mismatch_info.append(f"Port '{port_name}': expected '{expected_value}', actual '{actual_value}'") + logger.warning(f"Win node output mismatch - port: {port_name}, expected: {expected_value}, actual: {actual_value}") + + # 如果所有输出都匹配,使用第一个输出作为胜利字符串 + if is_correct and output_values: + victory_string = list(output_values.values())[0] + else: + logger.warning(f"Win node called but missing output values - expected: {expected_outputs}, actual: {output_values}") + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型调用工具获得输出后,需要自己识别这是否是胜利字符串并提交 + if is_correct: + logger.info(f"🎯 Win node called with correct output - case: {case_id}, node: {node_id}, victory: {victory_string}") + else: + logger.info(f"❌ Win node called with incorrect output - case: {case_id}, node: {node_id}") + + return response + +class UseItemRequest(BaseModel): + node_id: str = Field(..., description="The ID of the Item node to use (must be Item type)") + arguments: Dict[str, Any] = Field(default_factory=dict, description="Input arguments to provide to the item") + +@app.post("/env/{case_id}/use_item") +def use_item(case_id: str, req: UseItemRequest): + """ + Use an Item node by providing input arguments. + + This is specifically for Item nodes that require parameters to be "unlocked" or "activated", + such as containers that need a password/fingerprint. + + - Validates that the node is of type Item + - Checks if provided arguments match the item's golden_input_values + - If match: triggers ITEM-type edge drops and returns the item's content + - If not match: returns error message + """ + logger.info(f"Use item request - case_id: {case_id}, node_id: {req.node_id}, args: {req.arguments}") + STATS["use_items"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + item_node = scenario.nodes[req.node_id] + + if not item_node.is_revealed: + logger.warning(f"Attempt to use hidden item: {req.node_id}") + return {"ok": False, "error": "Item is not visible yet."} + + if item_node.type != "Item": + logger.warning(f"Attempt to use non-item node: {req.node_id} (type: {item_node.type})") + return {"ok": False, "error": "Only Item nodes can be used with use_item. Tools should be called with tool_call."} + + # 【新增】检查该 Item 是否已经被成功解锁 + # 如果已经被正确使用过,直接返回成功提示 + if item_node.if_success: + logger.info(f"Item already unlocked, returning success message: {req.node_id}") + return { + "ok": True, + "message": "This item has already been successfully unlocked by you." + } + + # 检查该 Item 是否真的需要通过 use_item 提供参数 + # 只有当 Item 有非 Item/Hidden_Item 类型的输入时,才应该使用 use_item + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + non_hidden_inputs = [ + inp for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + if not non_hidden_inputs: + # 该 Item 不需要参数,应该只使用 investigate + logger.warning(f"Attempt to use_item on a node that doesn't require parameters: {req.node_id}") + return { + "ok": False, + "error": "This item does not require parameters. Please use investigate to examine the item directly." + } + + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, item_node.golden_input_values) + + if not inputs_match_golden: + logger.info(f"✗ Item inputs do NOT match golden - node: {req.node_id}") + # 提供更详细的错误信息,帮助 Agent 理解问题 + # 只显示非 Item/Hidden_Item 类型的参数(Hidden_Item 由系统自动处理) + expected_params = [] + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + expected_params = [ + inp.get("name") for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + provided_params = list(req.arguments.keys()) if req.arguments else [] + + # 检查参数名是否匹配 + if set(expected_params) == set(provided_params): + # 参数名正确但值不匹配 - 不泄漏正确的值 + error_msg = f"Parameter names are correct, but the parameter values are incorrect. Please try using different parameter values." + else: + error_msg = f"Parameter names do not match. Expected parameter names: {expected_params}, you provided: {provided_params}." + + return { + "ok": False, + "error": error_msg + } + + logger.info(f"✓ Item inputs match golden - node: {req.node_id}, activating item") + + # 标记该 Item 已被正确使用 + item_node.if_success = True + + # 将 golden_output_values 追加到 actual_outputs_history + if item_node.golden_output_values: + item_node.actual_outputs_history.append(dict(item_node.golden_output_values)) + + # 触发 ITEM 类型边的掉落 + newly_revealed = [] + for edge in scenario.edges: + if edge.source_id == item_node.id and edge.connection_type == InterfaceType.ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from use_item on {req.node_id})") + + # 检查是否为 Win Node + win_node_id = scenario.win_node_id + is_win_node = (req.node_id == win_node_id) + + # 构建返回结果 + result = { + "ok": True, + "message": "Item used successfully.", + "content": item_node.golden_output_values if item_node.golden_output_values else None + } + + # 获取 narrative(如果存在) + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + narrative = raw_nodes_data[req.node_id].get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 如果是 Win Node,只记录日志 + if is_win_node: + logger.info(f"Win node (Item) unlocked via use_item - case: {case_id}, node: {req.node_id}") + + return result + + +class SubmitAnswerRequest(BaseModel): + answer: str = Field(..., description="The victory string to submit") + +@app.post("/env/{case_id}/submit_answer") +def submit_answer(case_id: str, req: SubmitAnswerRequest): + """ + 提交答案接口 + 被测模型在获得胜利字符串提示后,需要调用此接口提交答案 + """ + logger.info(f"Submit answer request - case_id: {case_id}, answer: {req.answer}") + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + + # 获取 win_node 的 golden_output_values + if not scenario.win_node_id: + logger.error(f"No win node defined for case: {case_id}") + return { + "ok": False, + "error": "This case has no victory node defined" + } + + win_node = scenario.nodes.get(scenario.win_node_id) + if not win_node: + logger.error(f"Win node not found: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node does not exist" + } + + # 获取正确的胜利字符串(取第一个 golden_output_value) + if win_node.golden_output_values: + correct_answer = list(win_node.golden_output_values.values())[0] + else: + logger.error(f"Win node has no golden_output_values: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node has no correct answer" + } + + # 验证提交的答案 + if req.answer == correct_answer: + logger.info(f"🎉 CORRECT ANSWER SUBMITTED - case: {case_id}, answer: {req.answer}") + return { + "ok": True, + "is_win": True, + "victory_message": f"🎉 Congratulations on successfully escaping the room! Your answer is correct: {req.answer}" + } + else: + logger.info(f"❌ INCORRECT ANSWER SUBMITTED - case: {case_id}, submitted: {req.answer}, correct: {correct_answer}") + return { + "ok": True, + "is_win": False, + "error": f"The submitted answer is incorrect. You submitted: {req.answer}" + } + +if __name__ == "__main__": + + uvicorn.run(app, host="0.0.0.0", port=8000) \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-8c861d5b/environment/puzzle/upstream/simulator.py b/tasks/agentescape-25-skeleton-8c861d5b/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-25-skeleton-8c861d5b/environment/puzzle/upstream/simulator.py @@ -0,0 +1,2911 @@ +import hashlib +import hmac +import base64 +import binascii +import zlib +import json +import uuid +import math +import re +from typing import Dict, Any, List + +class ToolSimulator: + def __init__(self): + """工具模拟器 + + 文件处理工具(zip_unzip, zip_unzip_file, zip_unzip_item, json_get, csv_query, + regex_search, graph_shortest_path)不需要真实文件系统。 + 这些工具只验证输入参数,然后返回预先初始化好的 golden_outputs。 + """ + self.tool_map = { + # 数论 + "calc_bigmul": self.calc_bigmul, + "calc_modexp": self.calc_modexp, + "calc_modexp_int": self.calc_modexp_int, + "calc_gcd": self.calc_gcd, + "calc_gcd_int": self.calc_gcd_int, + "calc_inv_mod": self.calc_inv_mod, + "calc_inv_mod_int": self.calc_inv_mod_int, + + # 哈希 + "hash_sha256": self.hash_sha256, + "hash_md5": self.hash_md5, + "hmac_sha256": self.hmac_sha256, + + # 编码 + "base64_decode": self.base64_decode, + "base64_encode": self.base64_encode, + "hex_decode": self.hex_decode, + "hex_encode": self.hex_encode, + "zlib_inflate": self.zlib_inflate, + "zlib_deflate": self.zlib_deflate, + + # 文件 + "zip_unzip": self.zip_unzip, + "zip_unzip_file": self.zip_unzip_file, + "zip_unzip_item": self.zip_unzip_item, + "regex_search": self.regex_search, + "json_get": self.json_get, + "csv_query": self.csv_query, + "code_py_exec": self.code_py_exec, + + # 图 + "graph_shortest_path": self.graph_shortest_path, + + # 加解密 (简化模拟) + "crypto_aes_cbc_decrypt": self.crypto_aes_cbc_decrypt, + "crypto_rsa_decrypt_hex": self.crypto_rsa_decrypt_hex, + + # 其他 + "num_base_convert": self.num_base_convert, + "time_convert": self.time_convert, + "checksum_crc32": self.checksum_crc32, + "geo_haversine": self.geo_haversine, + "otp_totp_generate": self.otp_totp_generate, + "unicode_norm": self.unicode_norm, + "text_bidi_sanitize": self.text_bidi_sanitize, + "text_xor_hex": self.text_xor_hex, + "text_rotN": self.text_rotN, + "luhn_check": self.luhn_check, + "iban_validate": self.iban_validate, + + # 物理 + "matter_synthesizer": self.matter_synthesizer, + + # 终端机 + "terminal_1": self.terminal_1, + "terminal_2": self.terminal_2, + "Logic Terminal": self.logic_terminal, + "Math Terminal": self.math_terminal, + "Encryption Terminal": self.crypt_terminal, + "Sequence Terminal": self.sequence_terminal + } + + def execute(self, tool_name: str, inputs: Dict[str, Any]) -> Dict[str, Any]: + if tool_name not in self.tool_map: + # Fallback for unknown tools: return dummy outputs based on expected output types + # This should ideally not happen if all tools are implemented + return {} + + try: + return self.tool_map[tool_name](inputs) + except Exception as e: + print(f"Error executing {tool_name}: {e}") + # Return empty or error indication? For generation, we might want to fail hard or return dummy. + # For now, return dummy to keep flow going, but log error. + return {} + + # --- Implementations --- + + def calc_bigmul(self, inputs): + # Check if required parameters are present + if "a" not in inputs or "b" not in inputs: + raise ValueError("Missing required parameters 'a' and/or 'b'") + + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + return {"product": str(a * b)} + except (ValueError, TypeError) as e: + raise ValueError(f"Failed to convert parameters to integers: {str(e)}") + + def calc_modexp(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + try: + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if isinstance(base, str): + base = int(base) + elif not isinstance(base, int): + raise ValueError("Parameter 'base' must be a string or integer") + + if isinstance(exp, str): + exp = int(exp) + elif not isinstance(exp, int): + raise ValueError("Parameter 'exp' must be a string or integer") + + if isinstance(mod, str): + mod = int(mod) + elif not isinstance(mod, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": str(pow(base, exp, mod))} + + def calc_modexp_int(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["base"], int): + raise ValueError("Parameter 'base' must be an integer") + if not isinstance(inputs["exp"], int): + raise ValueError("Parameter 'exp' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": pow(base, exp, mod)} + + def calc_gcd(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + # 计算 GCD 并返回字符串格式(符合 Big_Int 输出类型) + result = math.gcd(a, b) + return {"gcd": str(result)} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def calc_gcd_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["b"], int): + raise ValueError("Parameter 'b' must be an integer") + + # 获取参数 + a = inputs["a"] + b = inputs["b"] + + return {"gcd": math.gcd(a, b)} + + def calc_inv_mod(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + m = inputs["mod"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(m, str): + m = int(m) + elif not isinstance(m, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": str(pow(a, -1, m))} + except ValueError as e: + # 模逆不存在时,返回一个特殊值(用于数据传递) + # 在 DAG 生成阶段,这允许数据流继续 + return {"inv": str(a)} + + def calc_inv_mod_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + a = inputs["a"] + m = inputs["mod"] + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": pow(a, -1, m)} + except ValueError as e: + raise ValueError(f"Modular inverse does not exist: {str(e)}") + + def hash_sha256(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.sha256(text.encode()).hexdigest()} + + def hash_md5(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.md5(text.encode()).hexdigest()} + + def hmac_sha256(self, inputs): + # 参数检查 + if "hex_key" not in inputs: + raise ValueError("Missing required parameter: hex_key") + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["hex_key"], str): + raise ValueError("Parameter 'hex_key' must be a string") + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + try: + key = bytes.fromhex(inputs["hex_key"]) + text = inputs["text"].encode() + return {"hex": hmac.new(key, text, hashlib.sha256).hexdigest()} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def base64_decode(self, inputs): + # 参数检查 + if "data" not in inputs: + raise ValueError("Missing required parameter: data") + + # 类型检查 + if not isinstance(inputs["data"], str): + raise ValueError("Parameter 'data' must be a string") + + data = inputs["data"] + try: + return {"bytes_hex": binascii.hexlify(base64.b64decode(data)).decode()} + except Exception as e: + raise ValueError(f"Base64 decode error: {str(e)}") + + def base64_encode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"b64": base64.b64encode(bytes.fromhex(hex_data)).decode()} + except Exception as e: + raise ValueError(f"Base64 encode error: {str(e)}") + + def hex_decode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"text": bytes.fromhex(hex_data).decode('utf-8', errors='ignore')} + except Exception as e: + raise ValueError(f"Hex decode error: {str(e)}") + + def hex_encode(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + try: + return {"hex": text.encode().hex()} + except Exception as e: + raise ValueError(f"Hex encode error: {str(e)}") + + + # 到此处实现已经更新 + + def zlib_inflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("Parameter 'hex' must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("Missing required parameter: hex") + + try: + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空字符串 + if not hex_data: + raise ValueError("Empty hex string provided") + + # 检查十六进制字符串的有效性 + if len(hex_data) % 2 != 0: + raise ValueError("Hex string must have even length") + + # 检查是否只包含有效的十六进制字符 + if not all(c in '0123456789abcdefABCDEF' for c in hex_data): + raise ValueError("Invalid hex string provided") + + # 尝试解压缩 + return {"text": zlib.decompress(bytes.fromhex(hex_data)).decode('utf-8')} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hex string provided") from e + raise ValueError(f"Invalid zlib data: {e}") from e + except Exception as e: + raise RuntimeError(f"Failed to inflate data: {e}") from e + + def zlib_deflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("Parameter 'text' must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("Missing required parameter: text") + + try: + # 压缩文本 + return {"hex": zlib.compress(text.encode('utf-8')).hex()} + except Exception as e: + raise RuntimeError(f"Failed to deflate data: {e}") from e + + # --- File Operations --- + + def zip_unzip(self, inputs): + """ZIP 解压工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"files": golden_outputs.get("files", "")} + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return {"files": golden_outputs.get("files", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "files" in golden_outputs: + # 验证必需参数 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 检查类型 + if has_zip_id and not isinstance(zip_id, str): + return {"error": "Parameter 'zip_id' must be a string type"} + if has_password and not isinstance(password, str): + return {"error": "Parameter 'password' must be a string type"} + + # 验证输入是否与预期匹配 + if golden_inputs: + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return {"files": golden_outputs["files"]} + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + # 没有golden_inputs但有golden_outputs,直接返回输出 + return {"files": golden_outputs["files"]} + + # 如果没有预期输出,返回空结果 + return {"files": ""} + + def regex_search(self, inputs): + """正则搜索工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"matches": golden_outputs.get("matches", "[]")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "matches" in golden_outputs: + # 提取实际参数 + pattern = inputs.get("pattern") + file_id = inputs.get("file_id") + text = inputs.get("text") + + # 1. 检查必需参数 + if pattern is None: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["pattern"], + "message": "Missing required parameter 'pattern'" + } + } + + # 类型检查 + if not isinstance(pattern, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "pattern", + "message": "Parameter 'pattern' must be a string type" + } + } + if file_id is not None and not isinstance(file_id, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if text is not None and not isinstance(text, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "text", + "message": "Parameter 'text' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合 + provided_params = {} + if pattern is not None: + provided_params["pattern"] = pattern + if file_id is not None: + provided_params["file_id"] = file_id + if text is not None: + provided_params["text"] = text + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数(关键改进) + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_pattern = golden_inputs.get("pattern") + expected_file_id = golden_inputs.get("file_id") + expected_text = golden_inputs.get("text") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_pattern is not None: + if str(pattern) != str(expected_pattern): + incorrect_params.append("pattern") + else: + correct_params.append("pattern") + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_text is not None: + if str(text) != str(expected_text): + incorrect_params.append("text") + else: + correct_params.append("text") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "matches": "[]", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "matches": golden_outputs["matches"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空列表 + return {"matches": "[]"} + + def json_get(self, inputs): + """JSON 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"values": golden_outputs.get("values", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "values" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + jsonpath = inputs.get("jsonpath", "") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if jsonpath is not None and not isinstance(jsonpath, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "jsonpath", + "message": "Parameter 'jsonpath' must be a string type" + } + } + + # 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:jsonpath有默认值"") + provided_params = {} + if file_id is not None: + provided_params["file_id"] = file_id + if jsonpath != "": + provided_params["jsonpath"] = jsonpath + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_jsonpath = golden_inputs.get("jsonpath") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_jsonpath is not None: + if str(jsonpath) != str(expected_jsonpath): + incorrect_params.append("jsonpath") + else: + correct_params.append("jsonpath") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "values": "", + "_validation": validation_info + } + + # 所有验证通过,返回正确输出 + return { + "values": golden_outputs["values"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"values": ""} + + def csv_query(self, inputs): + """CSV 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"rows": golden_outputs.get("rows", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "rows" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + select_columns = inputs.get("select", "") + where_clause = inputs.get("where", "") + + # 1. 检查必需参数 + if file_id is None: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["file_id"], + "message": "Missing required parameter 'file_id'" + } + } + + # 类型检查 + if not isinstance(file_id, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if not isinstance(select_columns, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "select", + "message": "Parameter 'select' must be a string type" + } + } + if not isinstance(where_clause, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "where", + "message": "Parameter 'where' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:select和where有默认值"") + provided_params = {"file_id": file_id} + if select_columns != "": + provided_params["select"] = select_columns + if where_clause != "": + provided_params["where"] = where_clause + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_select = golden_inputs.get("select") + expected_where = golden_inputs.get("where") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_select is not None: + if str(select_columns) != str(expected_select): + incorrect_params.append("select") + else: + correct_params.append("select") + + if expected_where is not None: + if str(where_clause) != str(expected_where): + incorrect_params.append("where") + else: + correct_params.append("where") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "rows": "", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "rows": golden_outputs["rows"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"rows": ""} + + def graph_shortest_path(self, inputs): + """图最短路径工具 + + 如果有 _golden_outputs 或 _init_outputs,验证输入并返回预设输出。 + 否则执行真实的 Dijkstra 算法。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 检查是否在预设模式中(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + if golden_outputs and "path" in golden_outputs: + # 评测阶段但没有 golden_inputs,直接返回 outputs + if not golden_inputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 评测模式:验证输入参数是否匹配 golden 值 + src = inputs.get("src") + dst = inputs.get("dst") + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + + has_src = src is not None and src != "" + has_dst = dst is not None and dst != "" + + # 验证必需参数 + if not has_src or not has_dst: + missing = [] + if not has_src: + missing.append("src") + if not has_dst: + missing.append("dst") + return {"error": "Missing required parameters: " + ", ".join(missing)} + + # 类型检查 + if not isinstance(src, str): + return {"error": "Parameter 'src' must be a string"} + if not isinstance(dst, str): + return {"error": "Parameter 'dst' must be a string"} + + # 验证输入是否匹配期望值 + if golden_inputs: + expected_src = golden_inputs.get("src") + expected_dst = golden_inputs.get("dst") + expected_file_id = golden_inputs.get("file_id") + expected_graph_data = golden_inputs.get("graph_data") + + # 收集验证结果 + incorrect_params = [] + correct_params = [] + + # 检查必需参数是否匹配 + if expected_src is not None: + if str(src) != str(expected_src): + incorrect_params.append("src") + else: + correct_params.append("src") + + if expected_dst is not None: + if str(dst) != str(expected_dst): + incorrect_params.append("dst") + else: + correct_params.append("dst") + + # 检查可选参数(如果在 expected_inputs 中定义了) + if expected_file_id is not None: + if file_id != expected_file_id: + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_graph_data is not None: + if graph_data != expected_graph_data: + incorrect_params.append("graph_data") + else: + correct_params.append("graph_data") + + # 如果有参数不正确,返回详细的反馈 + if incorrect_params: + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 验证通过,返回预设的输出 + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 获取参数(真实执行路径) + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + # Support both src/dst (interface definition) and start/end (original implementation) + start = inputs.get("src") + end = inputs.get("dst") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + raise TypeError("file_id must be a string") + + if graph_data is not None and not isinstance(graph_data, str): + raise TypeError("graph_data must be a string") + + if start is not None and not isinstance(start, str): + raise TypeError("src/start must be a string") + + if end is not None and not isinstance(end, str): + raise TypeError("dst/end must be a string") + + # 检查必需参数 + if file_id is None and graph_data is None: + raise ValueError("Either file_id or graph_data must be provided") + + if start is None: + raise ValueError("src/start parameter is required") + + if end is None: + raise ValueError("dst/end parameter is required") + + # Get graph content + content = None + if file_id is not None: + # 尝试从 VFS 获取(如果存在) + if hasattr(self, 'vfs') and file_id in self.vfs: + content = self.vfs[file_id] + else: + # VFS 不存在或文件不在 VFS 中 + # 返回一个默认的空图结果,或者抛出错误提示需要 init_outputs + raise ValueError( + f"File '{file_id}' not found. For tools that require files, " + f"please provide init_outputs in the initial_values." + ) + elif graph_data is not None: + content = graph_data + + if content is None: + content = "{}" + + try: + # Parse graph data + graph = json.loads(content) + + # 类型检查 + if not isinstance(graph, dict): + raise TypeError("Graph data must be a dictionary") + + # If graph is not in the expected format, try to extract adjacency list + if "nodes" in graph and "edges" in graph: + # 验证nodes和edges的类型 + if not isinstance(graph["nodes"], list): + raise TypeError("Nodes must be a list") + + if not isinstance(graph["edges"], list): + raise TypeError("Edges must be a list") + + # Convert from nodes/edges format to adjacency list + adjacency_list = {} + for node in graph["nodes"]: + # 验证node类型 + if not isinstance(node, dict): + raise TypeError("Each node must be a dictionary") + + # Use node ID as key, not the entire node dictionary + node_id = node.get("id", "") + if node_id: + adjacency_list[node_id] = {} + + for edge in graph["edges"]: + # 验证edge类型 + if not isinstance(edge, dict): + raise TypeError("Each edge must be a dictionary") + + u = edge["from"] + v = edge["to"] + weight = edge.get("weight", 1) # Default to unweighted + + # 类型检查 + if not isinstance(u, str): + raise TypeError("Edge 'from' must be a string") + + if not isinstance(v, str): + raise TypeError("Edge 'to' must be a string") + + if not isinstance(weight, (int, float)): + raise TypeError("Edge weight must be a number") + + if u not in adjacency_list: + adjacency_list[u] = {} + if v not in adjacency_list: + adjacency_list[v] = {} + + adjacency_list[u][v] = weight + # If undirected, add reverse edge + if not edge.get("directed", False): + adjacency_list[v][u] = weight + elif isinstance(graph, dict): + # Already in adjacency list format + adjacency_list = graph + + # 验证邻接表结构 + for node, neighbors in adjacency_list.items(): + if not isinstance(neighbors, dict): + raise TypeError("Adjacency list must be a dictionary of dictionaries") + + for neighbor, weight in neighbors.items(): + if not isinstance(weight, (int, float)): + raise TypeError("Edge weights must be numbers") + else: + raise TypeError("Graph data must be a dictionary") + + # 检查起点和终点是否为空 + if not start: + raise ValueError("Start node cannot be empty") + + if not end: + raise ValueError("End node cannot be empty") + + # 检查起点和终点是否在图中 + if start not in adjacency_list: + raise ValueError(f"Start node '{start}' not found in graph") + + if end not in adjacency_list: + raise ValueError(f"End node '{end}' not found in graph") + + # Dijkstra's algorithm implementation + import heapq + + # Initialize distances and previous nodes + distances = {node: float('infinity') for node in adjacency_list} + previous = {node: None for node in adjacency_list} + distances[start] = 0 + + # Priority queue + pq = [(0, start)] + heapq.heapify(pq) + + while pq: + current_dist, current_node = heapq.heappop(pq) + + # If we've reached the end node, we can break early + if current_node == end: + break + + # Nodes can be added multiple times to the priority queue, but we only process them once + if current_dist > distances[current_node]: + continue + + # Explore neighbors + for neighbor, weight in adjacency_list[current_node].items(): + distance = current_dist + weight + + # If a shorter path is found + if distance < distances[neighbor]: + distances[neighbor] = distance + previous[neighbor] = current_node + heapq.heappush(pq, (distance, neighbor)) + + # Reconstruct the shortest path + path = [] + current = end + while current is not None: + path.append(current) + current = previous[current] + path.reverse() # Reverse to get from start to end + + # Check if path exists + if not path or path[0] != start: + return {"path": "[]", "cost": 0} + + return { + "path": json.dumps(path), + "cost": distances[end] + } + except json.JSONDecodeError as e: + raise ValueError(f"Invalid JSON in graph data: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in graph_shortest_path: {str(e)}") + + # --- Crypto (Simplified) --- + def crypto_aes_cbc_decrypt(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 (使用模板中定义的参数名) + hex_cipher = inputs.get("hex_cipher") + hex_key = inputs.get("hex_key") + hex_iv = inputs.get("hex_iv") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + + if hex_key is not None and not isinstance(hex_key, str): + raise TypeError("hex_key must be a string") + + if hex_iv is not None and not isinstance(hex_iv, str): + raise TypeError("hex_iv must be a string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + + if hex_key is None: + raise ValueError("hex_key parameter is required") + + if hex_iv is None: + raise ValueError("hex_iv parameter is required") + + from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes + from cryptography.hazmat.backends import default_backend + from cryptography.hazmat.primitives import padding + + try: + # Convert hex strings to bytes + ciphertext = bytes.fromhex(hex_cipher) + key = bytes.fromhex(hex_key) + iv = bytes.fromhex(hex_iv) + + # Validate key length (AES-128, AES-192, AES-256) + if len(key) not in [16, 24, 32]: + raise ValueError("Invalid key length. Must be 16, 24, or 32 bytes.") + + if len(iv) != 16: + raise ValueError("Invalid IV length. Must be 16 bytes.") + + # Create cipher object + cipher = Cipher( + algorithms.AES(key), + modes.CBC(iv), + backend=default_backend() + ) + + decryptor = cipher.decryptor() + + # Decrypt the ciphertext + padded_plaintext = decryptor.update(ciphertext) + decryptor.finalize() + + # Remove PKCS7 padding + unpadder = padding.PKCS7(128).unpadder() + plaintext = unpadder.update(padded_plaintext) + unpadder.finalize() + + # Return decrypted text + return {"text": plaintext.decode('utf-8', errors='ignore')} + except ValueError as e: + if "non-hexadecimal number found in fromhex()" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher, hex_key, or hex_iv") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in crypto_aes_cbc_decrypt: {str(e)}") + + def crypto_rsa_decrypt_hex(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_cipher = inputs.get("hex_cipher") + n = inputs.get("n") + d = inputs.get("d") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + if n is not None and not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + if d is not None and not isinstance(d, (int, str)): + raise TypeError("d must be an integer or string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + if n is None: + raise ValueError("n parameter is required") + if d is None: + raise ValueError("d parameter is required") + + try: + # Convert parameters to appropriate types + cipher_int = int(hex_cipher, 16) + n_int = int(n) if isinstance(n, str) else n + d_int = int(d) if isinstance(d, str) else d + + # RSA decryption: plaintext = ciphertext^d mod n + plaintext_int = pow(cipher_int, d_int, n_int) + + # Convert result to hex and then to text + plaintext_hex = hex(plaintext_int)[2:] + + # Pad with leading zero if odd length + if len(plaintext_hex) % 2 != 0: + plaintext_hex = '0' + plaintext_hex + + # Convert hex to bytes and then to text + try: + plaintext_bytes = bytes.fromhex(plaintext_hex) + plaintext_text = plaintext_bytes.decode('utf-8', errors='ignore') + except: + # If decoding fails, return hex representation + plaintext_text = plaintext_hex + + return {"text": plaintext_text} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in crypto_rsa_decrypt_hex: {str(e)}") + + # --- Others --- + def num_base_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + s = inputs.get("s") + from_base = inputs.get("from_base") + to_base = inputs.get("to_base") + + # 类型检查 - 接受 str 或 int + if s is not None and not isinstance(s, (str, int)): + raise TypeError("s must be a string or integer") + + if from_base is not None and not isinstance(from_base, (int, str)): + raise TypeError("from_base must be an integer") + + if to_base is not None and not isinstance(to_base, (int, str)): + raise TypeError("to_base must be an integer") + + # 检查必需参数 + if s is None: + raise ValueError("s parameter is required") + + if from_base is None: + raise ValueError("from_base parameter is required") + + if to_base is None: + raise ValueError("to_base parameter is required") + + try: + # Convert to int if needed + from_base = int(from_base) if isinstance(from_base, str) else from_base + to_base = int(to_base) if isinstance(to_base, str) else to_base + s_str = str(s) + + # 验证基数范围 + if from_base < 2 or from_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + if to_base < 2 or to_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + # Convert from source base to decimal + val = int(s_str, from_base) + + # Convert from decimal to target base + if to_base == 10: + result = str(val) + elif to_base == 16: + result = hex(val)[2:] + elif to_base == 8: + result = oct(val)[2:] + elif to_base == 2: + result = bin(val)[2:] + else: + # Generic base conversion for other bases + if val == 0: + result = "0" + else: + digits = "0123456789abcdefghijklmnopqrstuvwxyz" + result = "" + n = abs(val) + while n: + result = digits[n % to_base] + result + n //= to_base + if val < 0: + result = "-" + result + + return {"str": result} + except ValueError as e: + raise ValueError(f"Invalid number format: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in num_base_convert: {str(e)}") + + def time_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iso = inputs.get("iso") + timestamp = inputs.get("timestamp") + datetime_str = inputs.get("datetime") + from_tz = inputs.get("from_tz") + to_tz = inputs.get("to_tz") + format_str = inputs.get("format") + + # 类型检查 + if iso is not None and not isinstance(iso, str): + raise TypeError("iso must be a string") + + if timestamp is not None and not isinstance(timestamp, (str, int, float)): + raise TypeError("timestamp must be a string, integer, or float") + + if datetime_str is not None and not isinstance(datetime_str, str): + raise TypeError("datetime must be a string") + + if from_tz is not None and not isinstance(from_tz, str): + raise TypeError("from_tz must be a string") + + if to_tz is not None and not isinstance(to_tz, str): + raise TypeError("to_tz must be a string") + + if format_str is not None and not isinstance(format_str, str): + raise TypeError("format must be a string") + + # 设置默认值 + if from_tz is None: + from_tz = "UTC" + + if to_tz is None: + to_tz = "UTC" + + import datetime + import pytz + + # 验证时区参数 + try: + if from_tz: + pytz.timezone(from_tz) + if to_tz: + pytz.timezone(to_tz) + except Exception: + raise ValueError("Invalid timezone provided") + + try: + # Parse input time + dt = None + + if iso is not None: + # Parse ISO 8601 format + dt = datetime.datetime.fromisoformat(iso.replace('Z', '+00:00')) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=pytz.UTC) + elif timestamp is not None: + # Parse Unix timestamp + timestamp = float(timestamp) + dt = datetime.datetime.fromtimestamp(timestamp, pytz.UTC) + elif datetime_str is not None: + # Parse datetime string + # Try common formats + formats_to_try = [ + "%Y-%m-%d %H:%M:%S", + "%Y-%m-%d %H:%M:%S.%f", + "%Y-%m-%d", + "%m/%d/%Y %H:%M:%S", + "%m/%d/%Y" + ] + + parse_success = False + for fmt in formats_to_try: + try: + dt = datetime.datetime.strptime(datetime_str, fmt) + dt = pytz.timezone(from_tz).localize(dt) + parse_success = True + break + except ValueError: + continue + + if not parse_success: + raise ValueError("Unable to parse datetime string with common formats") + else: + # 如果没有提供任何时间参数,则使用当前时间 + dt = datetime.datetime.now(pytz.UTC) + except ValueError as e: + raise ValueError(f"Error parsing time input: {str(e)}") + except Exception as e: + raise RuntimeError(f"Unexpected error parsing time input: {str(e)}") + + try: + # Convert timezone + if from_tz != to_tz: + dt = dt.astimezone(pytz.timezone(to_tz)) + + # Format outputs + result = { + "iso": dt.isoformat(), + "timestamp": str(dt.timestamp()), + "datetime": dt.strftime("%Y-%m-%d %H:%M:%S"), + "date": dt.strftime("%Y-%m-%d"), + "time": dt.strftime("%H:%M:%S"), + "timezone": to_tz + } + + # Add custom format if requested + if format_str: + try: + result["formatted"] = dt.strftime(format_str) + except ValueError as e: + raise ValueError(f"Invalid format string: {str(e)}") + + return result + except Exception as e: + raise RuntimeError(f"Error in time_convert: {str(e)}") + + def checksum_crc32(self, inputs): + import zlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("hex must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("hex parameter is required") + + try: + # 验证十六进制字符串 + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空 + if not hex_data: + raise ValueError("hex data cannot be empty") + + # 检查是否为有效的十六进制字符串 + if not all(c in "0123456789abcdefABCDEF" for c in hex_data): + raise ValueError("hex must be a valid hexadecimal string") + + # 检查长度是否为偶数 + if len(hex_data) % 2 != 0: + raise ValueError("hex must have even number of characters") + + val = zlib.crc32(bytes.fromhex(hex_data)) + # 确保 hex 输出是 8 位,前导补 0 + return {"hex": f"{val:08x}", "int": val} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in checksum_crc32: {str(e)}") + + def geo_haversine(self, inputs): + import math + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + lat1 = inputs.get("lat1") + lon1 = inputs.get("lon1") + lat2 = inputs.get("lat2") + lon2 = inputs.get("lon2") + + # 类型检查 + if lat1 is not None and not isinstance(lat1, (int, float, str)): + raise TypeError("lat1 must be a number or string") + if lon1 is not None and not isinstance(lon1, (int, float, str)): + raise TypeError("lon1 must be a number or string") + if lat2 is not None and not isinstance(lat2, (int, float, str)): + raise TypeError("lat2 must be a number or string") + if lon2 is not None and not isinstance(lon2, (int, float, str)): + raise TypeError("lon2 must be a number or string") + + # 检查必需参数 + if lat1 is None: + raise ValueError("lat1 parameter is required") + if lon1 is None: + raise ValueError("lon1 parameter is required") + if lat2 is None: + raise ValueError("lat2 parameter is required") + if lon2 is None: + raise ValueError("lon2 parameter is required") + + try: + # 转换为浮点数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(lat1, str): + lat1 = float(lat1) + elif not isinstance(lat1, (int, float)): + raise TypeError("lat1 must be a number or string") + else: + lat1 = float(lat1) + + if isinstance(lon1, str): + lon1 = float(lon1) + elif not isinstance(lon1, (int, float)): + raise TypeError("lon1 must be a number or string") + else: + lon1 = float(lon1) + + if isinstance(lat2, str): + lat2 = float(lat2) + elif not isinstance(lat2, (int, float)): + raise TypeError("lat2 must be a number or string") + else: + lat2 = float(lat2) + + if isinstance(lon2, str): + lon2 = float(lon2) + elif not isinstance(lon2, (int, float)): + raise TypeError("lon2 must be a number or string") + else: + lon2 = float(lon2) + + # Validate coordinates (approximate range check) + if not (-90 <= lat1 <= 90): + raise ValueError("lat1 must be between -90 and 90") + if not (-90 <= lat2 <= 90): + raise ValueError("lat2 must be between -90 and 90") + if not (-180 <= lon1 <= 180): + raise ValueError("lon1 must be between -180 and 180") + if not (-180 <= lon2 <= 180): + raise ValueError("lon2 must be between -180 and 180") + + # Earth radius in meters + R = 6371000 # Approximate radius of Earth + + # Convert degrees to radians + lat1_rad = math.radians(lat1) + lon1_rad = math.radians(lon1) + lat2_rad = math.radians(lat2) + lon2_rad = math.radians(lon2) + + # Calculate differences + delta_lat = lat2_rad - lat1_rad + delta_lon = lon2_rad - lon1_rad + + # Haversine formula + a = math.sin(delta_lat / 2) ** 2 + \ + math.cos(lat1_rad) * math.cos(lat2_rad) * \ + math.sin(delta_lon / 2) ** 2 + c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) + distance_m = R * c + + # Return distance in meters + return {"meters": round(distance_m, 2)} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in geo_haversine: {str(e)}") + + def otp_totp_generate(self, inputs): + import hmac + import hashlib + import base64 + import time + import struct + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + base32_secret = inputs.get("base32_secret") + step = inputs.get("step", 30) # Default to 30 seconds + digits = inputs.get("digits", 6) # Default to 6 digits + timestamp_iso = inputs.get("timestamp_iso", "") + algo = inputs.get("algo", "sha1") # Default to sha1 as current implementation only supports this + + # 类型检查 + if base32_secret is not None and not isinstance(base32_secret, str): + raise TypeError("base32_secret must be a string") + if not isinstance(step, (int, str)): + raise TypeError("step must be an integer or string") + if not isinstance(digits, (int, str)): + raise TypeError("digits must be an integer or string") + if not isinstance(timestamp_iso, str): + raise TypeError("timestamp_iso must be a string") + if not isinstance(algo, str): + raise TypeError("algo must be a string") + + # 检查必需参数 + if base32_secret is None: + raise ValueError("base32_secret parameter is required") + + try: + # Convert step and digits to appropriate types + step = int(step) + digits = int(digits) + if digits < 6 or digits > 8: + raise ValueError("Digits must be between 6 and 8") + + # Convert timestamp_iso to integer timestamp + if timestamp_iso: + import datetime + dt = datetime.datetime.fromisoformat(timestamp_iso.replace('Z', '+00:00')) + timestamp = int(dt.timestamp()) + else: + timestamp = int(time.time()) + + # Calculate counter value (T = floor(timestamp / step)) + counter = timestamp // step + + # Decode the base32 secret + # Add padding if necessary (base64 requires padding to be multiple of 8) + base32_secret = base32_secret.upper().replace(' ', '') + if len(base32_secret) % 8 != 0: + base32_secret += '=' * (8 - (len(base32_secret) % 8)) + key = base64.b32decode(base32_secret, casefold=True) + + # Calculate HMAC-SHA1 + counter_bytes = struct.pack('>Q', counter) # Big-endian 8-byte integer + hmac_hash = hmac.new(key, counter_bytes, hashlib.sha1).digest() + + # Dynamic truncation + offset = hmac_hash[-1] & 0xF + code = struct.unpack('>I', hmac_hash[offset:offset+4])[0] & 0x7FFFFFFF + + # Generate the OTP + otp = str(code % (10 ** digits)).zfill(digits) + + # Calculate remaining time until next OTP change + remaining_time = step - (timestamp % step) + + return {"totp": otp, "remaining_time": remaining_time, "time_step": step} + except ValueError as e: + if "invalid literal for int()" in str(e): + raise ValueError("step and digits must be valid integers") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in otp_totp_generate: {str(e)}") + + def unicode_norm(self, inputs): + import unicodedata + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + form = inputs.get("form", "NFC") # Default to NFC + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if form is not None and not isinstance(form, str): + raise TypeError("form must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Normalize form (NFC, NFD, NFKC, NFKD) + form = form.upper().strip() + + if form not in ['NFC', 'NFD', 'NFKC', 'NFKD']: + raise ValueError(f"Invalid normalization form: {form}. Must be one of: NFC, NFD, NFKC, NFKD") + + # Apply Unicode normalization + normalized_text = unicodedata.normalize(form, text) + + return {"text": normalized_text} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in unicode_norm: {str(e)}") + + def text_bidi_sanitize(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Bidi control characters to remove + bidi_controls = [ + '\u200E', # LEFT-TO-RIGHT MARK + '\u200F', # RIGHT-TO-LEFT MARK + '\u202A', # LEFT-TO-RIGHT EMBEDDING + '\u202B', # RIGHT-TO-LEFT EMBEDDING + '\u202C', # POP DIRECTIONAL FORMATTING + '\u202D', # LEFT-TO-RIGHT OVERRIDE + '\u202E', # RIGHT-TO-LEFT OVERRIDE + '\u2066', # LEFT-TO-RIGHT ISOLATE + '\u2067', # RIGHT-TO-LEFT ISOLATE + '\u2068', # FIRST STRONG ISOLATE + '\u2069', # POP DIRECTIONAL ISOLATE + ] + + # Remove all Bidi control characters + sanitized_text = text + for control_char in bidi_controls: + sanitized_text = sanitized_text.replace(control_char, '') + + return {"text": sanitized_text} + except Exception as e: + raise RuntimeError(f"Error in text_bidi_sanitize: {str(e)}") + + def text_xor_hex(self, inputs): + import binascii + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_a = inputs.get("hex_a") + hex_b = inputs.get("hex_b") + + # 类型检查 + if hex_a is not None and not isinstance(hex_a, str): + raise TypeError("hex_a must be a string") + if hex_b is not None and not isinstance(hex_b, str): + raise TypeError("hex_b must be a string") + + # 检查必需参数 + if hex_a is None: + raise ValueError("hex_a parameter is required") + if hex_b is None: + raise ValueError("hex_b parameter is required") + + try: + # Remove any whitespace + hex_a = hex_a.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + hex_b = hex_b.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + + # Validate hex strings + if not (all(c in "0123456789abcdefABCDEF" for c in hex_a) and len(hex_a) % 2 == 0): + raise ValueError("hex_a must be a valid hexadecimal string with even length") + if not (all(c in "0123456789abcdefABCDEF" for c in hex_b) and len(hex_b) % 2 == 0): + raise ValueError("hex_b must be a valid hexadecimal string with even length") + + # Convert hex strings to bytes + bytes_a = binascii.unhexlify(hex_a) + bytes_b = binascii.unhexlify(hex_b) + + # Make the byte arrays the same length by padding the shorter one with zeros + max_len = max(len(bytes_a), len(bytes_b)) + bytes_a = bytes_a.ljust(max_len, b'\x00') + bytes_b = bytes_b.ljust(max_len, b'\x00') + + # Perform XOR operation + result_bytes = bytes(a ^ b for a, b in zip(bytes_a, bytes_b)) + + # Convert result back to hex + result_hex = binascii.hexlify(result_bytes).decode('utf-8') + + return {"hex": result_hex} + except ValueError as e: + if "Non-hexadecimal digit found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in text_xor_hex: {str(e)}") + + def text_rotN(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + n = inputs.get("n", 0) + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + n = int(n) + except ValueError: + raise ValueError("n must be a valid integer") + + result = [] + for char in text: + if char.isupper(): + # Rotate uppercase letters + result_char = chr((ord(char) - ord('A') + n) % 26 + ord('A')) + result.append(result_char) + elif char.islower(): + # Rotate lowercase letters + result_char = chr((ord(char) - ord('a') + n) % 26 + ord('a')) + result.append(result_char) + else: + # Keep non-alphabetic characters unchanged + result.append(char) + + return {"text": ''.join(result)} + + def luhn_check(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数(支持 card_number 和 number 两个参数名) + card_number = inputs.get("number") or inputs.get("card_number") + + # 类型检查 + if card_number is not None and not isinstance(card_number, str): + raise TypeError("number must be a string") + + # 检查必需参数 + if card_number is None: + raise ValueError("number parameter is required") + + try: + # 如果输入是JSON数组或其他非数字字符串,返回该字符串本身(用于数据传递) + # 这种情况发生在DAG设计中类型不匹配时 + if card_number.startswith('[') or card_number.startswith('{'): + # 输入是JSON,直接返回原值(用于传递) + return {"valid": card_number} + + # Remove whitespace from card number + card_number = card_number.replace(" ", "").replace("-", "") + + # Check if card number is all digits + if not card_number.isdigit() or len(card_number) < 13: + return {"valid": "false"} + + # Implement Luhn algorithm + total = 0 + reverse_digits = card_number[::-1] # Reverse the number for easier processing + + for i, digit in enumerate(reverse_digits): + num = int(digit) + if i % 2 == 1: # Every second digit starting from the right (which is first in reversed string) + num *= 2 + if num > 9: + num -= 9 # Equivalent to sum of digits for 2-digit numbers + total += num + + # Check if total is divisible by 10 + is_valid = total % 10 == 0 + return {"valid": "true" if is_valid else "false"} + except Exception as e: + raise RuntimeError(f"Error in luhn_check: {str(e)}") + + def iban_validate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iban = inputs.get("iban") + + # 类型检查 + if iban is not None and not isinstance(iban, str): + raise TypeError("iban must be a string") + + # 检查必需参数 + if iban is None: + raise ValueError("iban parameter is required") + + try: + # Remove whitespace from IBAN + iban = iban.replace(" ", "") + + # Basic length and format check + if not (len(iban) >= 15 and len(iban) <= 34): + return {"valid": "False"} + + if not (iban[:2].isalpha() and iban[2:].isdigit()): + return {"valid": "False"} + + # Move first four characters to the end + rearranged = iban[4:] + iban[:4] + + # Replace letters with numbers (A=10, B=11, ..., Z=35) + numeric_iban = '' + for char in rearranged: + if char.isdigit(): + numeric_iban += char + else: + numeric_iban += str(ord(char.upper()) - ord('A') + 10) + + # Perform modulo 97 check + # Use step-by-step approach for very large numbers + remainder = 0 + for char in numeric_iban: + remainder = (remainder * 10 + int(char)) % 97 + + is_valid = remainder == 1 + return {"valid": "True" if is_valid else "False"} + except Exception as e: + raise RuntimeError(f"Error in iban_validate: {str(e)}") + + def matter_synthesizer(self, inputs): + import hashlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + blueprint = inputs.get("blueprint") + + # 类型检查 + if blueprint is not None and not isinstance(blueprint, str): + raise TypeError("blueprint must be a string") + + try: + # Get blueprint parameter as defined in interface + if blueprint is None: + blueprint = "" + + # Generate a unique item ID based on the blueprint + # This ensures the same blueprint always produces the same item + blueprint_hash = hashlib.sha256(blueprint.encode()).hexdigest()[:16] + + # Create a synthesized item with a deterministic ID based on blueprint + synthesized_item = f"synthesized_item_{blueprint_hash}" + + return {"output_slot": synthesized_item} + except Exception as e: + raise RuntimeError(f"Error in matter_synthesizer: {str(e)}") + + # --- Terminal Implementations --- + def terminal_1(self, inputs): + """ + terminal_1: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 只返回 text_output + - 只输入正确的 slot_b → 只返回 hex_output + - 同时输入正确的 slot_a 和 slot_b → 返回 item_dispenser(物品掉落) + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + # 检查哪些输入被提供了 + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值是否正确(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + expected_a = golden_inputs["slot_a"] + a_valid = str(slot_a) == str(expected_a) + + if has_b and "slot_b" in golden_inputs: + expected_b = golden_inputs["slot_b"] + b_valid = str(slot_b) == str(expected_b) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 item_dispenser + if has_a and has_b: + if a_valid and b_valid: + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 text_output + if has_a and not has_b: + if a_valid: + if "text_output" in golden_outputs: + result["text_output"] = golden_outputs["text_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 hex_output + if has_b and not has_a: + if b_valid: + if "hex_output" in golden_outputs: + result["hex_output"] = golden_outputs["hex_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def terminal_2(self, inputs): + """ + terminal_2: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 text_result + - 同时输入正确的 num1 和 num2 → 返回 hex_result 和 math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + # 检查哪些输入被提供了 + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值是否正确(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + expected_num1 = golden_inputs["num1"] + num1_valid = str(num1) == str(expected_num1) + + if has_num2 and "num2" in golden_inputs: + expected_num2 = golden_inputs["num2"] + num2_valid = str(num2) == str(expected_num2) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 hex_result 和 math_token + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 text_result + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "text_result" in golden_outputs: + result["text_result"] = golden_outputs["text_result"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def logic_terminal(self, inputs): + """ + Logic Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 返回 screen(部分输出) + - 只输入正确的 slot_b → 返回 screen 和 secondary_output + - 同时输入正确的 slot_a 和 slot_b → 返回 screen, secondary_output, item_dispenser + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + a_valid = str(slot_a) == str(golden_inputs["slot_a"]) + + if has_b and "slot_b" in golden_inputs: + b_valid = str(slot_b) == str(golden_inputs["slot_b"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出(包括 item_dispenser) + if has_a and has_b: + if a_valid and b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 screen(部分输出) + if has_a and not has_b: + if a_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 screen 和 secondary_output + if has_b and not has_a: + if b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def math_terminal(self, inputs): + """ + Math Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 result_display + - 同时输入正确的 num1 和 num2 → 返回 result_display, hex_result, math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + num1_valid = str(num1) == str(golden_inputs["num1"]) + + if has_num2 and "num2" in golden_inputs: + num2_valid = str(num2) == str(golden_inputs["num2"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 result_display + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def crypt_terminal(self, inputs): + """ + Encryption Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 plaintext → 返回 status(部分输出) + - 同时输入正确的 plaintext 和 key → 返回 status, encrypted_hex, encryption_chip + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + plaintext = inputs.get("plaintext") + key = inputs.get("key") + + has_plaintext = plaintext is not None and plaintext != "" + has_key = key is not None and key != "" + + # 验证输入值(与 golden values 比较) + plaintext_valid = False + key_valid = False + + if has_plaintext and "plaintext" in golden_inputs: + plaintext_valid = str(plaintext) == str(golden_inputs["plaintext"]) + + if has_key and "key" in golden_inputs: + key_valid = str(key) == str(golden_inputs["key"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_plaintext and has_key: + if plaintext_valid and key_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + if "encrypted_hex" in golden_outputs: + result["encrypted_hex"] = golden_outputs["encrypted_hex"] + if "encryption_chip" in golden_outputs: + result["encryption_chip"] = golden_outputs["encryption_chip"] + return result + else: + incorrect_params = [] + correct_params = [] + if not plaintext_valid: + incorrect_params.append("plaintext") + else: + correct_params.append("plaintext") + if not key_valid: + incorrect_params.append("key") + else: + correct_params.append("key") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 plaintext 且正确 → 返回 status(部分输出) + if has_plaintext and not has_key: + if plaintext_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: plaintext"} + + # 只提供 key 但没有 plaintext + if has_key and not has_plaintext: + return {"error": "plaintext required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + def sequence_terminal(self, inputs): + """ + Sequence Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 sequence → 返回 verification(部分输出) + - 同时输入正确的 sequence 和 checksum → 返回 verification, auth_code, access_card + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + sequence = inputs.get("sequence") + checksum = inputs.get("checksum") + + has_sequence = sequence is not None and sequence != "" + has_checksum = checksum is not None and checksum != "" + + # 验证输入值(与 golden values 比较) + sequence_valid = False + checksum_valid = False + + if has_sequence and "sequence" in golden_inputs: + sequence_valid = str(sequence) == str(golden_inputs["sequence"]) + + if has_checksum and "checksum" in golden_inputs: + checksum_valid = str(checksum) == str(golden_inputs["checksum"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_sequence and has_checksum: + if sequence_valid and checksum_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + if "auth_code" in golden_outputs: + result["auth_code"] = golden_outputs["auth_code"] + if "access_card" in golden_outputs: + result["access_card"] = golden_outputs["access_card"] + return result + else: + incorrect_params = [] + correct_params = [] + if not sequence_valid: + incorrect_params.append("sequence") + else: + correct_params.append("sequence") + if not checksum_valid: + incorrect_params.append("checksum") + else: + correct_params.append("checksum") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 sequence 且正确 → 返回 verification(部分输出) + if has_sequence and not has_checksum: + if sequence_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: sequence"} + + # 只提供 checksum 但没有 sequence + if has_checksum and not has_sequence: + return {"error": "sequence required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + # --- Additional File Tools --- + + def zip_unzip_file(self, inputs): + """ZIP 解压文件工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def zip_unzip_item(self, inputs): + """ZIP 解压道具工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def code_py_exec(self, inputs): + """Python 代码执行工具 + + 这是一个真实执行的工具,在 DAG 生成阶段和运行时评测阶段都会执行代码。 + 输入: code (Python 代码字符串) + 输出: stdout (标准输出,包含执行结果和错误信息) + + 特殊行为: + - 如果代码定义了 main() 函数,会自动调用它 + - 如果执行出错,错误信息会包含在 stdout 中 + """ + code = inputs.get("code", "") + + if not code: + return {"stdout": "Error: No code provided"} + + try: + # 创建一个受限的执行环境 + import io + import sys + + # 捕获标准输出和标准错误 + old_stdout = sys.stdout + old_stderr = sys.stderr + sys.stdout = io.StringIO() + sys.stderr = io.StringIO() + + # 执行代码 + exec_globals = {"__builtins__": __builtins__} + exec_locals = {} + exec(code, exec_globals, exec_locals) + + # 如果定义了 main() 函数,自动调用它 + if 'main' in exec_locals and callable(exec_locals['main']): + exec_locals['main']() + + # 获取输出 + stdout_value = sys.stdout.getvalue() + stderr_value = sys.stderr.getvalue() + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 合并 stdout 和 stderr + output = stdout_value + if stderr_value: + output += ("\n" if output else "") + f"[stderr] {stderr_value}" + + # 如果没有任何输出,尝试返回 result 变量的值 + if not output: + result = exec_locals.get("_result") or exec_locals.get("result") + if result is not None: + output = str(result) + + return {"stdout": output if output else "(no output)"} + + except Exception as e: + # 恢复标准输出和错误输出 + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 返回错误信息 + return {"stdout": f"Error: {type(e).__name__}: {str(e)}"} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-8c861d5b/environment/puzzle/worker.Dockerfile b/tasks/agentescape-25-skeleton-8c861d5b/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-25-skeleton-8c861d5b/environment/puzzle/worker.Dockerfile @@ -0,0 +1,8 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends libseccomp2 && rm -rf /var/lib/apt/lists/* +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY worker.py child.py /app/ +COPY upstream/simulator.py /app/simulator.py +CMD ["uvicorn", "worker:app", "--host", "0.0.0.0", "--port", "8001", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-25-skeleton-8c861d5b/environment/puzzle/worker.py b/tasks/agentescape-25-skeleton-8c861d5b/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-25-skeleton-8c861d5b/environment/puzzle/worker.py @@ -0,0 +1,73 @@ +"""Stateless Python tool worker. Never receives a scenario or reference values.""" + +import json +import os +import signal +import subprocess +import sys +import tempfile +import threading + +from fastapi import FastAPI +from pydantic import BaseModel, ConfigDict + +app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) +lock = threading.Lock() + + +class Execution(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + code: str + + +@app.get("/health") +def health(): + return {"ok": True} + + +@app.post("/execute") +def execute(request: Execution): + if len(request.code.encode()) > 65536: + return {"stdout": "Error: code exceeds 64 KiB limit"} + with lock, tempfile.TemporaryDirectory(prefix="escape-code-") as directory: + os.chown(directory, 65534, 65534) + with tempfile.TemporaryFile() as output: + process = subprocess.Popen( + [sys.executable, "-I", "/app/child.py"], + stdin=subprocess.PIPE, + stdout=output, + stderr=subprocess.DEVNULL, + cwd=directory, + user=65534, + group=65534, + extra_groups=[], + start_new_session=True, + env={"PATH": "/usr/local/bin:/usr/bin:/bin"}, + ) + try: + process.communicate( + json.dumps({"code": request.code}).encode(), timeout=5 + ) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + return {"stdout": "Error: Python execution timed out"} + finally: + # Also remove children still in the process group after normal exit. + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + output.seek(0) + value = output.read(65537) + if len(value) > 65536 or process.returncode != 0: + return { + "stdout": "Error: Python execution exceeded a resource limit or failed" + } + try: + result = json.loads(value) + if not isinstance(result.get("stdout"), str): + raise ValueError("Invalid worker response") + return result + except (ValueError, AttributeError): + return {"stdout": "Error: Python execution returned invalid output"} diff --git a/tasks/agentescape-25-skeleton-8c861d5b/instruction.md b/tasks/agentescape-25-skeleton-8c861d5b/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-25-skeleton-8c861d5b/instruction.md @@ -0,0 +1,18 @@ +# Escape the room + +Discover the victory string and submit it with `escape submit-answer`. +Start with `escape observe`. This returns the room, available information, visible entities, and victory node ID. + +Use these commands (JSON responses): + +```sh +escape investigate NODE_ID +escape tool-call NODE_ID --arguments-json '{"parameter": "value"}' +escape use-item NODE_ID --arguments-json '{"parameter": "value"}' +escape submit-answer 'exact victory string' +escape state +``` + +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. + +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. diff --git a/tasks/agentescape-25-skeleton-8c861d5b/solution/oracle.py b/tasks/agentescape-25-skeleton-8c861d5b/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-25-skeleton-8c861d5b/solution/oracle.py @@ -0,0 +1,133 @@ +"""Reference solver: use trusted inputs, but obtain the answer through public actions.""" + +import json +import urllib.request +from pathlib import Path + + +def http_action(base_url, payload): + request = urllib.request.Request( + base_url + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(request, timeout=30) as response: + return json.load(response) + + +def solve(scenario, act, observe): + nodes = {node["id"]: node for node in scenario["nodes"]} + visible = {entity["id"] for entity in observe["available_entities"]} + solved = set() + seen_outputs = {} + action_count = 0 + + def call(payload): + nonlocal action_count + action_count += 1 + response = act(payload) + visible.update(entity["id"] for entity in response.get("newly_revealed", [])) + if ( + response.get("episode", {}).get("termination_reason") + == "infrastructure_error" + ): + raise RuntimeError("Infrastructure failure") + return response + + for _round in range(len(nodes) + 2): + progress = False + for node_id, node in nodes.items(): + if node_id not in visible or node_id in solved: + continue + # Preserve graph order for data inputs; trigger/drop edges express visibility. + predecessors = [ + edge["source_id"] + for edge in scenario["edges"] + if edge["target_id"] == node_id + and edge["connection_type"] not in ("Item", "Hidden_Item") + ] + if any(pred not in solved for pred in predecessors): + continue + info = call({"action": "investigate", "node_id": node_id}) + if not info.get("ok"): + raise RuntimeError(f"Investigation failed: {node_id}: {info}") + inputs = { + port["name"]: port["value"] + for port in node.get("inputs", []) + if "value" in port + } + if node["type"] == "Tool": + result = call( + {"action": "tool_call", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok") or result.get("output_values", {}).get("error"): + raise RuntimeError(f"Tool failed: {node_id}: {result}") + output = result.get("output_values", {}) + if node.get("template_id") in ("terminal_1", "terminal_2"): + slots = { + port["name"]: inputs[port["name"]] + for port in node["inputs"] + if port["type"] not in ("Item", "Hidden_Item") + and port["name"] in inputs + } + triggers = { + key: value for key, value in inputs.items() if key not in slots + } + for key, value in slots.items(): + partial = call( + { + "action": "tool_call", + "node_id": node_id, + "arguments": {**triggers, key: value}, + } + ) + if partial.get("ok"): + output.update(partial.get("output_values", {})) + # HIDDEN_ITEM tool drops only occur on subsequent investigation. + call({"action": "investigate", "node_id": node_id}) + elif info.get("required_inputs"): + result = call( + {"action": "use_item", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok"): + raise RuntimeError(f"Item failed: {node_id}: {result}") + output = result.get("content") + else: + output = info.get("content") + seen_outputs[node_id] = output + solved.add(node_id) + progress = True + win_id = scenario["metadata"]["win_node_id"] + if win_id in solved and (len(solved) == len(nodes) or not progress): + outputs = seen_outputs[win_id] + if not outputs: + raise RuntimeError(f"Victory node returned no output: {win_id}") + # Upstream grades its first stored output port, independent of response order. + victory_port = next( + port["name"] for port in nodes[win_id]["outputs"] if "value" in port + ) + answer = outputs[victory_port] if isinstance(outputs, dict) else outputs + result = call({"action": "submit_answer", "answer": answer}) + if not result.get("is_win"): + raise RuntimeError(f"Victory submission failed: {result}") + return {"won": True, "actions": action_count, "visited_nodes": len(solved)} + if not progress: + raise RuntimeError(f"No progress: visible={visible}, solved={solved}") + raise RuntimeError("Reference solver exceeded graph traversal limit") + + +if __name__ == "__main__": + import os + + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000") + with urllib.request.urlopen(base + "/observation", timeout=20) as response: + observation = json.load(response) + print( + json.dumps( + solve( + json.loads(Path("/solution/scenario.json").read_text()), + lambda payload: http_action(base, payload), + observation, + ) + ) + ) diff --git a/tasks/agentescape-25-skeleton-8c861d5b/solution/scenario.json b/tasks/agentescape-25-skeleton-8c861d5b/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..f90a422a531578239f01faad63661a1c8af8ad3c --- /dev/null +++ b/tasks/agentescape-25-skeleton-8c861d5b/solution/scenario.json @@ -0,0 +1,1364 @@ +{ + "metadata": { + "total_nodes": 25, + "total_edges": 30, + "win_node_id": "num_base_convert", + "win_condition": { + "type": "tool_output", + "node_id": "num_base_convert", + "output_port": "str", + "output_type": "Big_Int", + "description": "Execute Base Converter and get the output from port 'str'" + }, + "source_init": { + "source_nodes": [ + "calc_bigmul_d110", + "calc_inv_mod", + "calc_bigmul_ab63", + "container_1", + "json_get", + "zip_unzip_file", + "container_3_fe8c", + "terminal_1", + "item_1", + "calc_modexp_3709" + ], + "by_node": { + "calc_bigmul_d110": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First large integer" + } + }, + "init_outputs": {} + }, + "calc_inv_mod": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "Integer a" + }, + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "calc_bigmul_ab63": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First large integer" + } + }, + "init_outputs": {} + }, + "container_1": { + "node_name": "", + "node_type": "Item", + "template_id": "container_1", + "init_inputs": { + "fingerprint_input": { + "type": "Hex_String", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + }, + "json_get": { + "node_name": "JSON Getter", + "node_type": "Tool", + "template_id": "json_get", + "init_inputs": { + "jsonpath": { + "type": "Text_Generic", + "description": "JSONPath expression" + } + }, + "init_outputs": { + "values": { + "type": "Text_Generic", + "description": "Extracted values" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + }, + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "container_3_fe8c": { + "node_name": "", + "node_type": "Item", + "template_id": "container_3", + "init_inputs": { + "fingerprint_input": { + "type": "Big_Int", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": { + "slot_a": { + "type": "Text_Generic", + "description": "Input Slot A" + }, + "slot_b": { + "type": "Big_Int", + "description": "Input Slot B" + } + }, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + }, + "item_dispenser": { + "type": "Item", + "description": "Item output when both slots are provided" + } + } + }, + "item_1": { + "node_name": "", + "node_type": "Item", + "template_id": "item_1", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Big_Int", + "description": "The number" + } + } + }, + "calc_modexp_3709": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "exp": { + "type": "Big_Int", + "description": "Exponent" + }, + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "calc_bigmul_d110": { + "init_inputs": { + "a": "349581723485019238475" + }, + "init_outputs": {} + }, + "calc_inv_mod": { + "init_inputs": { + "a": "584930291827465938210", + "mod": "847291" + }, + "init_outputs": {} + }, + "calc_bigmul_ab63": { + "init_inputs": { + "a": "192837465019283746519" + }, + "init_outputs": {} + }, + "container_1": { + "init_inputs": { + "fingerprint_input": "3f9a2b8e7c1d4f0a" + }, + "init_outputs": {} + }, + "json_get": { + "init_inputs": { + "jsonpath": "$.users[0].details" + }, + "init_outputs": { + "values": "[\"John Doe\", \"Admin\", \"Active\"]" + } + }, + "zip_unzip_file": { + "init_inputs": { + "zip_id": "archive_991.zip", + "password": "SuperSecretPass123!" + }, + "init_outputs": { + "files": "extracted_data.json" + } + }, + "container_3_fe8c": { + "init_inputs": { + "fingerprint_input": "475839201928374659203" + }, + "init_outputs": {} + }, + "terminal_1": { + "init_inputs": { + "slot_a": "Execute primary sequence alpha", + "slot_b": "993847561029384756102" + }, + "init_outputs": { + "text_output": "Terminal processing successfully completed.", + "hex_output": "1a2b3c4d5e6f7a8b9c0d", + "item_dispenser": "Dispensed useless token" + } + }, + "item_1": { + "init_inputs": {}, + "init_outputs": { + "content": "2233445566778899001122" + } + }, + "calc_modexp_3709": { + "init_inputs": { + "exp": "112233445566778899001", + "mod": "908177" + }, + "init_outputs": {} + } + }, + "intro_narrative": "Welcome to Neo-Veridian, Sector 7. You are a rogue data-runner trapped in a highly secured corporate black-site. Your latest heist went completely wrong, and the facility's lockdown protocols have engaged. The only way out is to manually breach the central AI's mainframe and open the blast doors. The facility is scattered with decommissioned tech, encrypted caches, and gruesome leftovers from previous runners who didn't make it. You will need to carefully analyze the environment, recover forgotten biometric data, and daisy-chain these fragmented systems together. Your ultimate goal is to navigate this digital and physical maze, synthesize the required bypass codes, and execute the final system override before the automated security sweep permanently erases you from the grid. Every node is connected; find the path and break the system.", + "narrative_style": "cyberpunk" + }, + "nodes": [ + { + "id": "num_base_convert", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "440578617012" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "11033631440307372106" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "590364" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "440578617012" + } + ], + "narrative": "This is the Mainframe Override Protocol. It requires inputs from the Logic Decryptor, the Primary Data Combiner, and the Tertiary Data Combiner." + }, + { + "id": "calc_modexp", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "590364" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "1" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "3857155895201146309209317676780576978350" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "590364" + } + ], + "narrative": "This is the Logic Decryptor. It requires inputs from the Sector Multiplier, the Quantum Inverter, and the Core Synchronizer." + }, + { + "id": "calc_bigmul", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": 3213183554 + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": 3433862789 + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "11033631440307372106" + } + ], + "narrative": "This is the Primary Data Combiner. It requires inputs from the System Integrity Verifier and the Network Integrity Verifier." + }, + { + "id": "checksum_crc32", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "5ffc24e36ed06a303231fd2a106840be15206ae087c7365784956cc45b697f7f" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "bf854a42" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3213183554 + } + ], + "narrative": "This is the System Integrity Verifier. It requires input from the Bio-Signature Hasher." + }, + { + "id": "calc_bigmul_d110", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "349581723485019238475" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "11033631440307372106" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "3857155895201146309209317676780576978350" + } + ], + "init": { + "inputs": { + "a": "349581723485019238475" + }, + "outputs": {} + }, + "narrative": "This is the Sector Multiplier. It requires input from the Primary Data Combiner." + }, + { + "id": "hash_sha256", + "name": "SHA-256 Hasher", + "description": "SHA-256 over UTF-8 text; returns hex.", + "type": "Tool", + "template_id": "hash_sha256", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text to hash", + "value": "Terminal processing successfully completed." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "SHA-256 Hex digest", + "value": "5ffc24e36ed06a303231fd2a106840be15206ae087c7365784956cc45b697f7f" + } + ], + "narrative": "This is the Bio-Signature Hasher. It requires input from the Maintenance Terminal." + }, + { + "id": "calc_inv_mod", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "584930291827465938210" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "847291" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "590364" + } + ], + "init": { + "inputs": { + "a": "584930291827465938210", + "mod": "847291" + }, + "outputs": {} + }, + "narrative": "This is the Quantum Inverter. A standalone processing node humming with neon energy." + }, + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "662177395454807624604102381491" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "440578617012" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "narrative": "This is the Core Synchronizer. It requires inputs from the Secondary Data Combiner and the Tertiary Data Combiner." + }, + { + "id": "calc_bigmul_ab63", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "192837465019283746519" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": 3433862789 + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "662177395454807624604102381491" + } + ], + "init": { + "inputs": { + "a": "192837465019283746519" + }, + "outputs": {} + }, + "narrative": "This is the Secondary Data Combiner. It requires input from the Network Integrity Verifier." + }, + { + "id": "checksum_crc32_b80a", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "e9b8eebb3ce86a986f01f5147bdf91bd72143b09ad210a09da449c583f33327f" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "ccac9685" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3433862789 + } + ], + "narrative": "This is the Network Integrity Verifier. It requires input from the Neural Hasher." + }, + { + "id": "calc_bigmul_73d0", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "746283" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "590364" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "440578617012" + } + ], + "narrative": "This is the Tertiary Data Combiner. It requires inputs from the Quantum Inverter and the Neural Decryptor." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by", + "value": "synthesized_item_e9b8eebb3ce86a98" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "This is the Printed Microchip. A freshly fabricated piece of synthetic hardware with complex circuitry." + }, + { + "id": "matter_synthesizer", + "name": "Matter Synthesizer", + "description": "Synthesizes physical objects from data blueprints.", + "type": "Tool", + "template_id": "matter_synthesizer", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "blueprint", + "type": "Text_Generic", + "description": "Object Blueprint", + "value": "[\"John Doe\", \"Admin\", \"Active\"]" + } + ], + "outputs": [ + { + "name": "output_slot", + "type": "Item", + "description": "Synthesized Object", + "value": "synthesized_item_e9b8eebb3ce86a98" + } + ], + "narrative": "This is the Cybernetic Fabricator. It requires input from the Databank Extractor." + }, + { + "id": "container_1", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + }, + { + "name": "fingerprint_input", + "type": "Hex_String", + "description": "Fingerprint Hash", + "value": "3f9a2b8e7c1d4f0a" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "3f9a2b8e7c1d4f0a" + }, + "outputs": {} + }, + "narrative": "This is the Encrypted Drop Box. A rugged storage unit left behind by a rogue hacker." + }, + { + "id": "container_3", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_3", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Big_Int", + "description": "Fingerprint Hash", + "value": "2233445566778899001122" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is the Biometric Safe. It requires input from the Severed Cybernetic Finger." + }, + { + "id": "json_get", + "name": "JSON Getter", + "description": "Extract values by simple JSONPath.", + "type": "Tool", + "template_id": "json_get", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "JSON file ID", + "value": "extracted_data.json" + }, + { + "name": "jsonpath", + "type": "Text_Generic", + "description": "JSONPath expression", + "value": "$.users[0].details" + } + ], + "outputs": [ + { + "name": "values", + "type": "Text_Generic", + "description": "Extracted values", + "value": "[\"John Doe\", \"Admin\", \"Active\"]" + } + ], + "init": { + "inputs": { + "jsonpath": "$.users[0].details" + }, + "outputs": { + "values": "[\"John Doe\", \"Admin\", \"Active\"]" + } + }, + "narrative": "This is the Databank Extractor. It requires input from the Archive Decoder." + }, + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "archive_991.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "SuperSecretPass123!" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_data.json" + } + ], + "init": { + "inputs": { + "zip_id": "archive_991.zip", + "password": "SuperSecretPass123!" + }, + "outputs": { + "files": "extracted_data.json" + } + }, + "narrative": "This is the Archive Decoder. A powerful piece of retro-software." + }, + { + "id": "hash_sha256_49ac", + "name": "SHA-256 Hasher", + "description": "SHA-256 over UTF-8 text; returns hex.", + "type": "Tool", + "template_id": "hash_sha256", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text to hash", + "value": "[\"John Doe\", \"Admin\", \"Active\"]" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "SHA-256 Hex digest", + "value": "e9b8eebb3ce86a986f01f5147bdf91bd72143b09ad210a09da449c583f33327f" + } + ], + "narrative": "This is the Neural Hasher. It requires input from the Databank Extractor." + }, + { + "id": "container_3_fe8c", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_3", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Big_Int", + "description": "Fingerprint Hash", + "value": "475839201928374659203" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "475839201928374659203" + }, + "outputs": {} + }, + "narrative": "This is the Optical Safe. A sleek, wall-mounted lockbox requiring specific access." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "This is the Rusted Keycard. A heavily degraded access token." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "Execute primary sequence alpha" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "993847561029384756102" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Terminal processing successfully completed." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "1a2b3c4d5e6f7a8b9c0d" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided", + "value": "Dispensed useless token" + } + ], + "init": { + "inputs": { + "slot_a": "Execute primary sequence alpha", + "slot_b": "993847561029384756102" + }, + "outputs": { + "text_output": "Terminal processing successfully completed.", + "hex_output": "1a2b3c4d5e6f7a8b9c0d", + "item_dispenser": "Dispensed useless token" + } + }, + "narrative": "This is the Maintenance Terminal. An active interface connected to the local grid." + }, + { + "id": "item_1", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "Big_Int", + "description": "The number", + "value": "2233445566778899001122" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "2233445566778899001122" + } + }, + "narrative": "This is the Severed Cybernetic Finger. A grim artifact with embedded biometric data." + }, + { + "id": "item_16_8cb9", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "This is the Plasma Torch. A high-temperature cutting tool used for industrial repairs." + }, + { + "id": "calc_modexp_3709", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "662177395454807624604102381491" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "112233445566778899001" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "908177" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "746283" + } + ], + "init": { + "inputs": { + "exp": "112233445566778899001", + "mod": "908177" + }, + "outputs": {} + }, + "narrative": "This is the Neural Decryptor. It requires input from the Secondary Data Combiner." + }, + { + "id": "item_8_0e87", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "This is the Maintenance Keycard. A standard operational pass for building staff." + } + ], + "edges": [ + { + "source_id": "calc_modexp", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "to_base" + }, + { + "source_id": "calc_bigmul", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "from_base" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "a" + }, + { + "source_id": "calc_bigmul_d110", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "mod" + }, + { + "source_id": "hash_sha256", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "calc_inv_mod", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "base" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "exp" + }, + { + "source_id": "calc_bigmul_ab63", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "a" + }, + { + "source_id": "checksum_crc32_b80a", + "target_id": "calc_bigmul_ab63", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "b" + }, + { + "source_id": "calc_bigmul_73d0", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "b" + }, + { + "source_id": "item_16", + "target_id": "checksum_crc32_b80a", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "matter_synthesizer", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "output_slot", + "target_port": "source_tool" + }, + { + "source_id": "calc_inv_mod", + "target_id": "calc_bigmul_73d0", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "b" + }, + { + "source_id": "container_1", + "target_id": "calc_bigmul_ab63", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "container_3", + "target_id": "hash_sha256", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "json_get", + "target_id": "matter_synthesizer", + "connection_type": "Text_Generic", + "source_port": "values", + "target_port": "blueprint" + }, + { + "source_id": "calc_bigmul", + "target_id": "calc_bigmul_d110", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "b" + }, + { + "source_id": "zip_unzip_file", + "target_id": "json_get", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "hash_sha256_49ac", + "target_id": "checksum_crc32_b80a", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "json_get", + "target_id": "hash_sha256_49ac", + "connection_type": "Text_Generic", + "source_port": "values", + "target_port": "text" + }, + { + "source_id": "container_3_fe8c", + "target_id": "calc_gcd", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "item_8", + "target_id": "container_3", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "checksum_crc32_b80a", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "b" + }, + { + "source_id": "terminal_1", + "target_id": "hash_sha256", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "text" + }, + { + "source_id": "item_1", + "target_id": "container_3", + "connection_type": "Big_Int", + "source_port": "content", + "target_port": "fingerprint_input" + }, + { + "source_id": "calc_bigmul_73d0", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "s" + }, + { + "source_id": "item_16_8cb9", + "target_id": "matter_synthesizer", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "calc_modexp_3709", + "target_id": "calc_bigmul_73d0", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "a" + }, + { + "source_id": "calc_bigmul_ab63", + "target_id": "calc_modexp_3709", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "base" + }, + { + "source_id": "item_8_0e87", + "target_id": "hash_sha256_49ac", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-8c861d5b/solution/solve.sh b/tasks/agentescape-25-skeleton-8c861d5b/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-25-skeleton-8c861d5b/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-25-skeleton-8c861d5b/task.toml b/tasks/agentescape-25-skeleton-8c861d5b/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..56f80be66907c83d265959df84f5a2da649a3381 --- /dev/null +++ b/tasks/agentescape-25-skeleton-8c861d5b/task.toml @@ -0,0 +1,38 @@ +schema_version = "1.4" +source = "https://github.com/AGI-Eval-Official/Repo-of-AgentEscapeBench" + +[[artifacts]] +source = "/evidence/final.json" +service = "puzzle" + +[[artifacts]] +source = "/evidence/trace.jsonl" +service = "puzzle" + +[task] +name = "edbeeching/agentescape-25-skeleton-8c861d5b" +version = "0.1.0" + +[metadata] +difficulty = 25 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "c633ea7b68acf79d1bc31a8b63ceb3bf2537c32e0d25c6b08dae17218585bc99" +protocol = "harbor-cli-action-budget-v1" +max_actions = 500 + +[agent] +timeout_sec = 1200 + +[environment] +build_timeout_sec = 900 +cpus = 1 +memory_mb = 1024 + +[verifier] +environment_mode = "separate" +timeout_sec = 60 + +[[verifier.collect]] +service = "puzzle" +command = "python -I /app/export.py" +timeout_sec = 15 diff --git a/tasks/agentescape-25-skeleton-8c861d5b/tests/Dockerfile b/tasks/agentescape-25-skeleton-8c861d5b/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-25-skeleton-8c861d5b/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-25-skeleton-8c861d5b/tests/expected.json b/tasks/agentescape-25-skeleton-8c861d5b/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..46a3dfcf0feaba1a85deeb76a1c6dc0328f4a162 --- /dev/null +++ b/tasks/agentescape-25-skeleton-8c861d5b/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "c633ea7b68acf79d1bc31a8b63ceb3bf2537c32e0d25c6b08dae17218585bc99", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-8c861d5b/tests/grade.py b/tasks/agentescape-25-skeleton-8c861d5b/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-25-skeleton-8c861d5b/tests/grade.py @@ -0,0 +1,21 @@ +"""Grade only Harbor-collected sidecar evidence in a fresh verifier container.""" + +import json +from pathlib import Path + +expected = json.loads(Path("/tests/expected.json").read_text()) +state = json.loads(Path("/evidence/final.json").read_text()) +assert state["collected_from_live_service"] is True, "Missing trusted service export" +assert state["scenario_sha256"] == expected["scenario_sha256"], ( + "Wrong scenario evidence" +) +assert state["max_actions"] == expected["max_actions"], "Wrong budget" +assert type(state["won"]) is bool +assert 0 <= state["action_count"] <= state["max_actions"] +assert state["termination_reason"] != "infrastructure_error", ( + "Infrastructure failure is not a puzzle failure" +) +assert not state["won"] or state["termination_reason"] == "success" +Path("/logs/verifier").mkdir(parents=True, exist_ok=True) +Path("/logs/verifier/state.json").write_text(json.dumps(state, indent=2)) +Path("/logs/verifier/reward.txt").write_text("1.0\n" if state["won"] else "0.0\n") diff --git a/tasks/agentescape-25-skeleton-8c861d5b/tests/test.sh b/tasks/agentescape-25-skeleton-8c861d5b/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-25-skeleton-8c861d5b/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-25-skeleton-93dd5f71/environment/Dockerfile b/tasks/agentescape-25-skeleton-93dd5f71/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-25-skeleton-93dd5f71/environment/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-25-skeleton-93dd5f71/environment/agent/Dockerfile b/tasks/agentescape-25-skeleton-93dd5f71/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-25-skeleton-93dd5f71/environment/agent/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-25-skeleton-93dd5f71/environment/agent/cli.py b/tasks/agentescape-25-skeleton-93dd5f71/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-25-skeleton-93dd5f71/environment/agent/cli.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Public agent client; depends only on the Python standard library.""" + +import argparse +import json +import os +import sys +import urllib.error +import urllib.request + + +def main(): + parser = argparse.ArgumentParser(description="Interact with the escape room") + parser.add_argument( + "action", + choices=[ + "observe", + "state", + "investigate", + "tool-call", + "use-item", + "submit-answer", + ], + ) + parser.add_argument("value", nargs="?") + parser.add_argument("--arguments-json", default="{}") + args = parser.parse_args() + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000").rstrip("/") + if args.action in ("observe", "state"): + request = urllib.request.Request( + base + ("/observation" if args.action == "observe" else "/state") + ) + else: + if args.value is None: + parser.error("node ID or answer is required") + payload = {"action": args.action.replace("-", "_")} + if args.action == "submit-answer": + payload["answer"] = args.value + else: + payload["node_id"] = args.value + if args.action in ("tool-call", "use-item"): + payload["arguments"] = json.loads(args.arguments_json) + request = urllib.request.Request( + base + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=30) as response: + print(json.dumps(json.load(response), ensure_ascii=False)) + except (urllib.error.URLError, ValueError) as exc: + print(json.dumps({"ok": False, "error": str(exc)})) + sys.exit(2) + + +if __name__ == "__main__": + main() diff --git a/tasks/agentescape-25-skeleton-93dd5f71/environment/docker-compose.yaml b/tasks/agentescape-25-skeleton-93dd5f71/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..42d6716b6f790be192cb45c3bcb532adf9702571 --- /dev/null +++ b/tasks/agentescape-25-skeleton-93dd5f71/environment/docker-compose.yaml @@ -0,0 +1,50 @@ +services: + main: + image: agentescapebench-agent:aab05a0a9ddb + build: + context: ./agent + networks: [default, puzzle] + security_opt: [no-new-privileges:true] + depends_on: + puzzle: + condition: service_healthy + puzzle: + image: agentescapebench-puzzle:agentescape-25-skeleton-93dd5f71-aab05a0a9ddb + build: + context: ./puzzle + networks: [puzzle, execution] + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 512m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"] + interval: 1s + timeout: 3s + retries: 30 + depends_on: + worker: + condition: service_healthy + worker: + image: agentescapebench-worker:aab05a0a9ddb + build: + context: ./puzzle + dockerfile: worker.Dockerfile + networks: [execution] + read_only: true + tmpfs: ["/tmp:size=64m,mode=1777"] + cap_drop: [ALL] + cap_add: [SETUID, SETGID, KILL, CHOWN, DAC_OVERRIDE] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 384m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8001/health')"] + interval: 1s + timeout: 3s + retries: 30 +networks: + puzzle: + internal: true + execution: + internal: true diff --git a/tasks/agentescape-25-skeleton-93dd5f71/environment/puzzle/Dockerfile b/tasks/agentescape-25-skeleton-93dd5f71/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-25-skeleton-93dd5f71/environment/puzzle/Dockerfile @@ -0,0 +1,9 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY upstream /app/upstream +COPY service.py export.py /app/ +COPY scenario.json /private/scenario.json +ENV SCENARIO_PATH=/private/scenario.json EVIDENCE_DIR=/evidence WORKER_URL=http://worker:8001 MAX_ACTIONS=500 +CMD ["uvicorn", "service:create_app", "--factory", "--host", "0.0.0.0", "--port", "8000", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-25-skeleton-93dd5f71/environment/puzzle/child.py b/tasks/agentescape-25-skeleton-93dd5f71/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-25-skeleton-93dd5f71/environment/puzzle/child.py @@ -0,0 +1,59 @@ +"""Run the original Python tool after reducing privileges and blocking networking.""" + +import ctypes +import errno +import json +import resource +import sys + +resource.setrlimit(resource.RLIMIT_CPU, (3, 3)) +resource.setrlimit(resource.RLIMIT_AS, (256 * 1024 * 1024, 256 * 1024 * 1024)) +resource.setrlimit(resource.RLIMIT_FSIZE, (65536, 65536)) +resource.setrlimit(resource.RLIMIT_NOFILE, (32, 32)) +resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + +# Filters survive fork/exec. Fail closed if seccomp cannot be loaded. +lib = ctypes.CDLL("libseccomp.so.2", use_errno=True) +lib.seccomp_init.argtypes = [ctypes.c_uint32] +lib.seccomp_init.restype = ctypes.c_void_p +lib.seccomp_rule_add.argtypes = [ + ctypes.c_void_p, + ctypes.c_uint32, + ctypes.c_int, + ctypes.c_uint, +] +lib.seccomp_syscall_resolve_name.argtypes = [ctypes.c_char_p] +lib.seccomp_load.argtypes = [ctypes.c_void_p] +lib.seccomp_release.argtypes = [ctypes.c_void_p] +ctx = lib.seccomp_init(0x7FFF0000) # SCMP_ACT_ALLOW +if not ctx: + raise RuntimeError("Cannot initialize execution isolation") +try: + for name in ( + "socket", + "socketpair", + "connect", + "ptrace", + "process_vm_readv", + "process_vm_writev", + "mount", + "unshare", + "setns", + "bpf", + ): + number = lib.seccomp_syscall_resolve_name(name.encode()) + if ( + number >= 0 + and lib.seccomp_rule_add(ctx, 0x00050000 | errno.EPERM, number, 0) != 0 + ): + raise RuntimeError("Cannot install execution isolation rule") + if lib.seccomp_load(ctx) != 0: + raise RuntimeError("Cannot activate execution isolation") +finally: + lib.seccomp_release(ctx) + +sys.path.insert(0, "/app") +from simulator import ToolSimulator # noqa: E402 + +request = json.load(sys.stdin) +json.dump(ToolSimulator().code_py_exec(request), sys.stdout) diff --git a/tasks/agentescape-25-skeleton-93dd5f71/environment/puzzle/export.py b/tasks/agentescape-25-skeleton-93dd5f71/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-25-skeleton-93dd5f71/environment/puzzle/export.py @@ -0,0 +1,13 @@ +"""Harbor invokes this inside the puzzle service after stopping the agent.""" + +import json +import pathlib +import urllib.request + +with urllib.request.urlopen("http://127.0.0.1:8000/state", timeout=10) as response: + state = json.load(response) +state["collected_from_live_service"] = True +target = pathlib.Path("/evidence/final.json") +temp = target.with_suffix(".tmp") +temp.write_text(json.dumps(state)) +temp.replace(target) diff --git a/tasks/agentescape-25-skeleton-93dd5f71/environment/puzzle/requirements.txt b/tasks/agentescape-25-skeleton-93dd5f71/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-25-skeleton-93dd5f71/environment/puzzle/requirements.txt @@ -0,0 +1,57 @@ +annotated-doc==0.0.5 + # via fastapi +annotated-types==0.8.0 + # via pydantic +anyio==4.16.0 + # via starlette +certifi==2026.10.23 + # via requests +cffi==2.1.1 ; platform_python_implementation != 'PyPy' + # via cryptography +charset-normalizer==3.5.2 + # via requests +click==8.5.0 + # via uvicorn +cryptography==50.0.2 + # via agentescapebench-harbor +fastapi==0.162.0 + # via agentescapebench-harbor +h11==0.16.0 + # via uvicorn +idna==3.20 + # via + # anyio + # requests +opentelemetry-api==1.45.2 + # via fastapi +pycparser==3.12 ; implementation_name != 'PyPy' and platform_python_implementation != 'PyPy' + # via cffi +pydantic==2.14.2 + # via + # agentescapebench-harbor + # fastapi +pydantic-core==2.50.2 + # via pydantic +pytz==2025.2 + # via agentescapebench-harbor +requests==2.34.2 + # via agentescapebench-harbor +starlette==1.10.0 + # via fastapi +typing-extensions==4.16.0 + # via + # anyio + # fastapi + # opentelemetry-api + # pydantic + # pydantic-core + # starlette + # typing-inspection +typing-inspection==0.4.4 + # via + # fastapi + # pydantic +urllib3==2.8.0 + # via requests +uvicorn==0.54.0 + # via agentescapebench-harbor diff --git a/tasks/agentescape-25-skeleton-93dd5f71/environment/puzzle/scenario.json b/tasks/agentescape-25-skeleton-93dd5f71/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..1ad967a263c10a346f233a68636287e9d6df1ef0 --- /dev/null +++ b/tasks/agentescape-25-skeleton-93dd5f71/environment/puzzle/scenario.json @@ -0,0 +1,1537 @@ +{ + "metadata": { + "total_nodes": 25, + "total_edges": 28, + "win_node_id": "item_15", + "win_condition": { + "type": "item_content", + "node_id": "item_15", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_15", + "terminal_1", + "calc_modexp", + "crypto_rsa_decrypt_hex", + "calc_modexp_490b", + "calc_gcd", + "num_base_convert", + "calc_inv_mod", + "container_3", + "calc_bigmul_cce0", + "regex_search", + "unicode_norm", + "container_3_c334", + "terminal_1_c1ab", + "item_10", + "item_10_7483", + "item_9", + "calc_gcd_737b" + ], + "by_node": { + "item_15": { + "node_name": "", + "node_type": "Item", + "template_id": "item_15", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Text_Generic", + "description": "Timezone text" + } + } + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": {}, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + } + } + }, + "calc_modexp": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "exp": { + "type": "Big_Int", + "description": "Exponent" + } + }, + "init_outputs": {} + }, + "crypto_rsa_decrypt_hex": { + "node_name": "RSA Decrypt", + "node_type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "init_inputs": { + "hex_cipher": { + "type": "Hex_String", + "description": "Ciphertext (Hex)" + } + }, + "init_outputs": {} + }, + "calc_modexp_490b": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "exp": { + "type": "Big_Int", + "description": "Exponent" + }, + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "calc_gcd": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First integer" + } + }, + "init_outputs": {} + }, + "num_base_convert": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "from_base": { + "type": "Big_Int", + "description": "From base" + }, + "to_base": { + "type": "Big_Int", + "description": "To base" + } + }, + "init_outputs": {} + }, + "calc_inv_mod": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "container_3": { + "node_name": "", + "node_type": "Item", + "template_id": "container_3", + "init_inputs": { + "fingerprint_input": { + "type": "Big_Int", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + }, + "calc_bigmul_cce0": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First large integer" + } + }, + "init_outputs": {} + }, + "regex_search": { + "node_name": "Regex Search", + "node_type": "Tool", + "template_id": "regex_search", + "init_inputs": { + "pattern": { + "type": "Text_Generic", + "description": "Regex pattern" + }, + "file_id": { + "type": "File_Id", + "description": "File ID (optional)" + } + }, + "init_outputs": { + "matches": { + "type": "Text_Generic", + "description": "Found matches (List)" + } + } + }, + "unicode_norm": { + "node_name": "Unicode Normalizer", + "node_type": "Tool", + "template_id": "unicode_norm", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text" + } + }, + "init_outputs": {} + }, + "container_3_c334": { + "node_name": "", + "node_type": "Item", + "template_id": "container_3", + "init_inputs": { + "fingerprint_input": { + "type": "Big_Int", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + }, + "terminal_1_c1ab": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": { + "slot_a": { + "type": "Text_Generic", + "description": "Input Slot A" + } + }, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + } + } + }, + "item_10": { + "node_name": "", + "node_type": "Item", + "template_id": "item_10", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Big_Int", + "description": "The number" + } + } + }, + "item_10_7483": { + "node_name": "", + "node_type": "Item", + "template_id": "item_10", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Big_Int", + "description": "The number" + } + } + }, + "item_9": { + "node_name": "", + "node_type": "Item", + "template_id": "item_9", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "File_Id", + "description": "JSON file path" + } + } + }, + "calc_gcd_737b": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First integer" + }, + "b": { + "type": "Big_Int", + "description": "Second integer" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "item_15": { + "init_inputs": {}, + "init_outputs": { + "content": "America/New_York" + } + }, + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "Welcome to the central terminal system.", + "hex_output": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "calc_modexp": { + "init_inputs": { + "exp": "74859385739204958674" + }, + "init_outputs": {} + }, + "crypto_rsa_decrypt_hex": { + "init_inputs": { + "hex_cipher": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + }, + "init_outputs": {} + }, + "calc_modexp_490b": { + "init_inputs": { + "exp": "34958672019485768392", + "mod": "999983" + }, + "init_outputs": {} + }, + "calc_gcd": { + "init_inputs": { + "a": "10293847563049586721" + }, + "init_outputs": {} + }, + "num_base_convert": { + "init_inputs": { + "from_base": "16", + "to_base": "10" + }, + "init_outputs": {} + }, + "calc_inv_mod": { + "init_inputs": { + "mod": "100003" + }, + "init_outputs": {} + }, + "container_3": { + "init_inputs": { + "fingerprint_input": "85960483928475630495" + }, + "init_outputs": {} + }, + "calc_bigmul_cce0": { + "init_inputs": { + "a": "94857639204857683921" + }, + "init_outputs": {} + }, + "regex_search": { + "init_inputs": { + "pattern": "\\d{16}", + "file_id": "data_scan.txt" + }, + "init_outputs": { + "matches": "[\"1234567812345678\", \"8765432187654321\", \"1111222233334444\"]" + } + }, + "unicode_norm": { + "init_inputs": { + "text": "Ä string to be normalized" + }, + "init_outputs": {} + }, + "container_3_c334": { + "init_inputs": { + "fingerprint_input": "75849302918274635241" + }, + "init_outputs": {} + }, + "terminal_1_c1ab": { + "init_inputs": { + "slot_a": "Input message for terminal A" + }, + "init_outputs": { + "text_output": "NFC", + "hex_output": "f1e2d3c4b5a697887766554433221100" + } + }, + "item_10": { + "init_inputs": {}, + "init_outputs": { + "content": "48573920495867382910" + } + }, + "item_10_7483": { + "init_inputs": {}, + "init_outputs": { + "content": "57483920192837465012" + } + }, + "item_9": { + "init_inputs": {}, + "init_outputs": { + "content": "metadata.json" + } + }, + "calc_gcd_737b": { + "init_inputs": { + "a": "83920485768392019283", + "b": "28374659302918273645" + }, + "init_outputs": {} + } + }, + "intro_narrative": "Welcome to Sector 7, the digital underbelly of the Neon Syndicate. The corporate overlords have locked down the main network, trapping vital information behind layers of biometric firewalls and quantum encryption algorithms. You are a rogue netrunner, and you've managed to slip into this abandoned corporate server room undetected. However, the system's automated purge protocols have been activated, and time is rapidly running out. Your objective is clear: navigate this maze of disconnected hardware, reactivate the dormant digital nodes, and bypass their intricate security measures. The syndicate relies on a complex web of mathematical ciphers and hidden cryptographic keys scattered throughout the room. By carefully linking these devices, you must systematically dismantle their defenses. Your ultimate goal is to breach the central mainframe and obtain the core timezone data before the physical servers are fried. Plug in, stay sharp, and don't let the neon lights distract you. The run starts now.", + "narrative_style": "cyberpunk" + }, + "nodes": [ + { + "id": "item_15", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_15", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Text_Generic", + "description": "Timezone text", + "value": "America/New_York" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "America/New_York" + } + }, + "narrative": "This is the Timezone Datapad. A sleek, top-tier corporate tablet meant to display the final uncorrupted timezone data." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "false" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "12096" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Welcome to the central terminal system." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "Welcome to the central terminal system.", + "hex_output": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "narrative": "This is the Mainframe Access Terminal. It requires inputs from both the ID Verification Scanner and the Quantum Encryption Core to authenticate your final entry." + }, + { + "id": "luhn_check", + "name": "Luhn Checker", + "description": "Luhn validity of number string.", + "type": "Tool", + "template_id": "luhn_check", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "number", + "type": "Text_Generic", + "description": "Number string", + "value": "\u000b" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "false" + } + ], + "narrative": "This is the ID Verification Scanner. It requires input from the Cypher Breaker Unit to process and validate your digital credentials." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "This is the Hidden Cache Drive. A small, concealed memory unit." + }, + { + "id": "calc_modexp", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "921072" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "74859385739204958674" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "20304" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "12096" + } + ], + "init": { + "inputs": { + "exp": "74859385739204958674" + }, + "outputs": {} + }, + "narrative": "This is the Quantum Encryption Core. It requires inputs from both the Sub-routine Processor and the Algorithmic Multiplier to stabilize its heavy computations." + }, + { + "id": "crypto_rsa_decrypt_hex", + "name": "RSA Decrypt", + "description": "RSA decrypt (hex cipher) with n,d (decimal).", + "type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "hex_cipher", + "type": "Hex_String", + "description": "Ciphertext (Hex)", + "value": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Modulus n", + "value": "921072" + }, + { + "name": "d", + "type": "Big_Int", + "description": "Private exponent d", + "value": "1" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decrypted text", + "value": "\u000b" + } + ], + "init": { + "inputs": { + "hex_cipher": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + }, + "outputs": {} + }, + "narrative": "This is the Cypher Breaker Unit. It requires inputs from both the Sub-routine Processor and the Network Divisor to shred through military-grade encryption." + }, + { + "id": "calc_modexp_490b", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "399793861475558893217052581389266889886769152272" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "34958672019485768392" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "999983" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "921072" + } + ], + "init": { + "inputs": { + "exp": "34958672019485768392", + "mod": "999983" + }, + "outputs": {} + }, + "narrative": "This is the Sub-routine Processor. It requires input from the Base Translator Module to handle low-level calculations." + }, + { + "id": "calc_bigmul", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "6768" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "3" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "20304" + } + ], + "narrative": "This is the Algorithmic Multiplier. It requires inputs from both the Harmonic Divisor and the Phase Inverter to output its massive digital payload." + }, + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "10293847563049586721" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "921072" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "3" + } + ], + "init": { + "inputs": { + "a": "10293847563049586721" + }, + "outputs": {} + }, + "narrative": "This is the Harmonic Divisor. It requires input from the Sub-routine Processor to isolate matching digital frequencies." + }, + { + "id": "num_base_convert", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "4607607425162430051697733404910257190110" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "16" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "10" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "399793861475558893217052581389266889886769152272" + } + ], + "init": { + "inputs": { + "from_base": "16", + "to_base": "10" + }, + "outputs": {} + }, + "narrative": "This is the Base Translator Module. It requires input from the Sequence Multiplier to properly align the data formats." + }, + { + "id": "item_16_2d46", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "This is the Encrypted Security Chip. A standalone piece of silicon dropped by a careless corp guard." + }, + { + "id": "zip_unzip_item", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_item", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "metadata.json" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "[\"1234567812345678\", \"8765432187654321\", \"1111222233334444\"]" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip" + } + ], + "narrative": "This is the Archive Extractor Tool. It requires inputs from both the Code Analyzer and the Encrypted Zip File to brute-force compressed directories." + }, + { + "id": "calc_inv_mod", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "4607607425162430051697733404910257190110" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "100003" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "6768" + } + ], + "init": { + "inputs": { + "mod": "100003" + }, + "outputs": {} + }, + "narrative": "This is the Phase Inverter. It requires input from the Sequence Multiplier to reverse the logic flow." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "This is the Corrupted Memory Stick. It has exposed wiring and scorch marks." + }, + { + "id": "container_3", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_3", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Big_Int", + "description": "Fingerprint Hash", + "value": "85960483928475630495" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "85960483928475630495" + }, + "outputs": {} + }, + "narrative": "This is the Employee Lockbox. A standard corporate storage bin for personal items." + }, + { + "id": "calc_bigmul_cce0", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "94857639204857683921" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "48573920495867382910" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "4607607425162430051697733404910257190110" + } + ], + "init": { + "inputs": { + "a": "94857639204857683921" + }, + "outputs": {} + }, + "narrative": "This is the Sequence Multiplier. It requires input from the Digital Keycard to calculate its primary hash." + }, + { + "id": "item_16_b9bd", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "This is the Smuggled Module. A piece of illegal hardware wrapped in anti-static tape." + }, + { + "id": "regex_search", + "name": "Regex Search", + "description": "Search regex in either raw text or a file.", + "type": "Tool", + "template_id": "regex_search", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "pattern", + "type": "Text_Generic", + "description": "Regex pattern", + "value": "\\d{16}" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "File ID (optional)", + "value": "data_scan.txt" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text (optional)", + "value": "Ä string to be normalized" + } + ], + "outputs": [ + { + "name": "matches", + "type": "Text_Generic", + "description": "Found matches (List)", + "value": "[\"1234567812345678\", \"8765432187654321\", \"1111222233334444\"]" + } + ], + "init": { + "inputs": { + "pattern": "\\d{16}", + "file_id": "data_scan.txt" + }, + "outputs": { + "matches": "[\"1234567812345678\", \"8765432187654321\", \"1111222233334444\"]" + } + }, + "narrative": "This is the Code Analyzer. It requires input from the Syntax Normalizer to scan for matching string anomalies." + }, + { + "id": "unicode_norm", + "name": "Unicode Normalizer", + "description": "Unicode normalize (NFC/NFD/NFKC/NFKD).", + "type": "Tool", + "template_id": "unicode_norm", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "Ä string to be normalized" + }, + { + "name": "form", + "type": "Text_Generic", + "description": "Form", + "value": "NFC" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Normalized text", + "value": "Ä string to be normalized" + } + ], + "init": { + "inputs": { + "text": "Ä string to be normalized" + }, + "outputs": {} + }, + "narrative": "This is the Syntax Normalizer. It requires input from the Lobby Security Terminal to format the corrupted text streams." + }, + { + "id": "container_3_c334", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_3", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Big_Int", + "description": "Fingerprint Hash", + "value": "75849302918274635241" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "75849302918274635241" + }, + "outputs": {} + }, + "narrative": "This is the Manager's Secure Vault. A biometric-locked safe used to hoard sensitive gear." + }, + { + "id": "terminal_1_c1ab", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this terminal" + }, + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "Input message for terminal A" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "57483920192837465012" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "NFC" + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "f1e2d3c4b5a697887766554433221100" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": { + "slot_a": "Input message for terminal A" + }, + "outputs": { + "text_output": "NFC", + "hex_output": "f1e2d3c4b5a697887766554433221100" + } + }, + "narrative": "This is the Lobby Security Terminal. It requires input from the Maintenance Access Token to bypass the initial firewall." + }, + { + "id": "item_10", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_10", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Big_Int", + "description": "The number", + "value": "48573920495867382910" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "48573920495867382910" + } + }, + "narrative": "This is the Digital Keycard. A pristine corporate access pass." + }, + { + "id": "item_10_7483", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_10", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Big_Int", + "description": "The number", + "value": "57483920192837465012" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "57483920192837465012" + } + }, + "narrative": "This is the Maintenance Access Token. A high-clearance tag meant for service drones." + }, + { + "id": "item_9", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_9", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "File_Id", + "description": "JSON file path", + "value": "metadata.json" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "metadata.json" + } + }, + "narrative": "This is the Encrypted Zip File. A heavily compressed data package floating in the local network." + }, + { + "id": "calc_gcd_737b", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "83920485768392019283" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "28374659302918273645" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "init": { + "inputs": { + "a": "83920485768392019283", + "b": "28374659302918273645" + }, + "outputs": {} + }, + "narrative": "This is the Network Divisor. A standalone processing node that splits data traffic." + } + ], + "edges": [ + { + "source_id": "terminal_1", + "target_id": "item_15", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "source_tool" + }, + { + "source_id": "luhn_check", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "slot_a" + }, + { + "source_id": "item_16", + "target_id": "luhn_check", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "calc_modexp", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "slot_b" + }, + { + "source_id": "crypto_rsa_decrypt_hex", + "target_id": "luhn_check", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "number" + }, + { + "source_id": "calc_modexp_490b", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "base" + }, + { + "source_id": "calc_bigmul", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "mod" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "b" + }, + { + "source_id": "num_base_convert", + "target_id": "calc_modexp_490b", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "base" + }, + { + "source_id": "item_16_2d46", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "zip_unzip_item", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "item", + "target_port": "source_tool" + }, + { + "source_id": "calc_inv_mod", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "a" + }, + { + "source_id": "item_8", + "target_id": "zip_unzip_item", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "container_3", + "target_id": "calc_modexp_490b", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "calc_bigmul_cce0", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "s" + }, + { + "source_id": "item_16_b9bd", + "target_id": "container_3", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "regex_search", + "target_id": "zip_unzip_item", + "connection_type": "Text_Generic", + "source_port": "matches", + "target_port": "password" + }, + { + "source_id": "unicode_norm", + "target_id": "regex_search", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "text" + }, + { + "source_id": "calc_bigmul_cce0", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "a" + }, + { + "source_id": "container_3_c334", + "target_id": "item_16_b9bd", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "calc_modexp_490b", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "b" + }, + { + "source_id": "calc_modexp_490b", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "n" + }, + { + "source_id": "terminal_1_c1ab", + "target_id": "unicode_norm", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "form" + }, + { + "source_id": "item_10", + "target_id": "calc_bigmul_cce0", + "connection_type": "Big_Int", + "source_port": "content", + "target_port": "b" + }, + { + "source_id": "terminal_1_c1ab", + "target_id": "item_10", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "source_tool" + }, + { + "source_id": "item_10_7483", + "target_id": "terminal_1_c1ab", + "connection_type": "Big_Int", + "source_port": "content", + "target_port": "slot_b" + }, + { + "source_id": "item_9", + "target_id": "zip_unzip_item", + "connection_type": "File_Id", + "source_port": "content", + "target_port": "zip_id" + }, + { + "source_id": "calc_gcd_737b", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "d" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-93dd5f71/environment/puzzle/service.py b/tasks/agentescape-25-skeleton-93dd5f71/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-25-skeleton-93dd5f71/environment/puzzle/service.py @@ -0,0 +1,212 @@ +"""Restricted facade over the unchanged, pinned upstream puzzle handlers.""" + +import hashlib +import json +import logging +import os +import sys +import threading +import urllib.request +import uuid +from pathlib import Path + +from fastapi import FastAPI, HTTPException +from fastapi.responses import JSONResponse +from pydantic import BaseModel, ConfigDict + +sys.path.insert(0, str(Path(__file__).parent / "upstream")) +import server as upstream # noqa: E402 + +log = logging.getLogger(__name__) + + +def public(value): + """Keep upstream agent-internal template hints out of the public response.""" + if isinstance(value, dict): + return {k: public(v) for k, v in value.items() if not k.startswith("_")} + if isinstance(value, list): + return [public(v) for v in value] + return value + + +class Action(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + action: str + node_id: str | None = None + arguments: dict | None = None + answer: str | None = None + + +class Episode: + def __init__( + self, scenario_path, max_actions=500, evidence_dir=None, worker_url=None + ): + if max_actions < 1: + raise ValueError("max_actions must be positive") + self.lock = threading.Lock() + self.max_actions = max_actions + self.count = 0 + self.won = False + self.reason = None + self.evidence_dir = Path(evidence_dir) if evidence_dir else None + self.scenario_hash = hashlib.sha256( + Path(scenario_path).read_bytes() + ).hexdigest() + self.initial = upstream.reset_case( + case_file_path=str(scenario_path), session_id=uuid.uuid4().hex + ) + self.case_id = self.initial["case_id"] + # Hide source file paths; no upstream reset/stats/routes are mounted. + self.initial.pop("message", None) + simulator = upstream.SIMULATORS[self.case_id] + if worker_url is None: + + def no_worker(_inputs): + self.reason = "infrastructure_error" + raise RuntimeError("isolated Python worker is not configured") + + simulator.tool_map["code_py_exec"] = no_worker + else: + + def execute_python(inputs): + request = urllib.request.Request( + worker_url + "/execute", + data=json.dumps({"code": inputs.get("code", "")}).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=12) as response: + result = json.load(response) + if not isinstance(result.get("stdout"), str): + raise RuntimeError("Invalid Python worker response") + return result + except Exception: + self.reason = "infrastructure_error" + raise + + simulator.tool_map["code_py_exec"] = execute_python + self.save() + if self.evidence_dir is not None: + (self.evidence_dir / "trace.jsonl").touch() + + def state(self): + return { + "scenario_sha256": self.scenario_hash, + "action_count": self.count, + "max_actions": self.max_actions, + "won": self.won, + "termination_reason": self.reason, + } + + def save(self, action=None, result=None): + if self.evidence_dir is None: + return + self.evidence_dir.mkdir(parents=True, exist_ok=True) + target = self.evidence_dir / "outcome.json" + temp = target.with_suffix(".tmp") + temp.write_text(json.dumps(self.state())) + temp.replace(target) + if action is not None: + with (self.evidence_dir / "trace.jsonl").open("a") as handle: + handle.write( + json.dumps( + {"index": self.count, "action": action, "result": result} + ) + + "\n" + ) + + def dispatch(self, payload): + with self.lock: + if self.reason is not None: + return { + "ok": False, + "error": "Episode has ended", + "episode": self.state(), + } + self.count += 1 + try: + action = Action.model_validate(payload) + if action.action == "submit_answer" and action.answer is not None: + result = upstream.submit_answer( + self.case_id, upstream.SubmitAnswerRequest(answer=action.answer) + ) + if result.get("is_win"): + self.won = True + self.reason = "success" + elif action.action == "investigate" and action.node_id is not None: + result = upstream.investigate( + self.case_id, + upstream.InvestigateRequest(node_id=action.node_id), + ) + elif ( + action.action in ("tool_call", "use_item") + and action.node_id is not None + ): + request_type, handler = ( + (upstream.ToolCallRequest, upstream.tool_call) + if action.action == "tool_call" + else (upstream.UseItemRequest, upstream.use_item) + ) + result = handler( + self.case_id, + request_type( + node_id=action.node_id, arguments=action.arguments or {} + ), + ) + else: + result = { + "ok": False, + "error": "Unknown action or missing action parameter", + } + except HTTPException as exc: + result = {"ok": False, "error": exc.detail} + except ValueError: + result = {"ok": False, "error": "Malformed action"} + except Exception: + log.exception("Puzzle service failure") + self.reason = "infrastructure_error" + self.save() + raise + if self.reason is None and self.count >= self.max_actions: + self.reason = "action_budget_exhausted" + result = public(result) + result["episode"] = self.state() + self.save(payload, result) + return result + + +def create_app( + scenario_path=None, max_actions=None, evidence_dir=None, worker_url=None +): + episode = Episode( + scenario_path or os.environ["SCENARIO_PATH"], + max_actions or int(os.environ.get("MAX_ACTIONS", "500")), + evidence_dir if evidence_dir is not None else os.environ.get("EVIDENCE_DIR"), + worker_url if worker_url is not None else os.environ.get("WORKER_URL"), + ) + app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) + app.state.episode = episode + + @app.get("/health") + def health(): + return {"ok": True} + + @app.get("/observation") + def observation(): + return {**public(episode.initial), "episode": episode.state()} + + @app.get("/state") + def state(): + return episode.state() + + @app.post("/action") + def action(payload: dict): + try: + return episode.dispatch(payload) + except Exception: + return JSONResponse( + status_code=503, + content={"ok": False, "error": "Puzzle infrastructure failure"}, + ) + + return app diff --git a/tasks/agentescape-25-skeleton-93dd5f71/environment/puzzle/upstream/models.py b/tasks/agentescape-25-skeleton-93dd5f71/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-25-skeleton-93dd5f71/environment/puzzle/upstream/models.py @@ -0,0 +1,108 @@ +from enum import Enum +from typing import List, Dict, Any, Optional +from pydantic import BaseModel, Field + +# 1. 细粒度接口类型定义 +class InterfaceType(str, Enum): + ''' + BIG_INT + TEXT_GENERIC + HEX_STRING + FILE_ID + HEX_STRING_KEY_AES + HEX_STRING_IV_AES + CODE_PYTHON + HIDDEN_ITEM + ITEM + ''' + # --- 基础类型 --- + TEXT_GENERIC = "Text_Generic" + BIG_INT = "Big_Int" + + # --- 编码/格式化字符串 --- + HEX_STRING = "Hex_String" # 通用 Hex + + # --- 特定用途的 Hex 字符串 (用于精确匹配) --- + HEX_STRING_KEY_AES = "Hex_String_Key_AES" + HEX_STRING_IV_AES = "Hex_String_IV_AES" + + # --- 文件类型 --- + FILE_ID = "File_Id" + + # --- 代码/脚本 --- + CODE_PYTHON = "Code_Python" + + # --- 实体交互类型 (严格命名) --- + ITEM = "Item" # 主动掉落接口 (Tool -> Item) + HIDDEN_ITEM = "Hidden_Item" # 被动掉落接口 (Item -> Item) + +# 3. 端口定义 +class Port(BaseModel): + name: str + type: InterfaceType + description: str + +# 4. 统一节点定义 (融合工具和物品) +class Node(BaseModel): + id: str + name: str + description: str + type: str # "Tool" or "Item" + + # 接口定义 + inputs: List[Port] = [] + outputs: List[Port] = [] + + # 状态字段 + content: Optional[Any] = None # 物品有内容,工具为None + if_success: Optional[bool] = None # 工具初始为False,物品为None + initial_visible: bool = False + + # 运行时状态 (Server维护) + is_revealed: bool = False + + # 标记该 Tool 节点是否有待触发的 HIDDEN_ITEM 掉落 + # 当 Tool 按照 golden_input 正确执行且有 HIDDEN_ITEM 输出边时设为 True + # 在 investigate 该 Tool 时触发掉落并重置为 False + has_hidden_item_ready: bool = False + + # 初始输入值 (metadata.initial_values.init_inputs,用于渐进式暴露判断) + init_input_values: Dict[str, Any] = {} + + # Golden 输入值 (nodes[].inputs[].value,用于评测验证) + golden_input_values: Dict[str, Any] = {} + + # Golden 输出值 (nodes[].outputs[].value,用于评测验证和 Item 节点的 content) + golden_output_values: Dict[str, Any] = {} + + # 实际获得的输出值历史 (工具每次执行后实际返回的输出列表,用于渐进式暴露判断) + # 格式: List[Dict[str, Any]],每个元素是一次执行的输出字典 + actual_outputs_history: List[Dict[str, Any]] = [] + + # 逻辑规则 (用于终端机等复杂物品) + logic_rules: Optional[Dict[str, Any]] = None + + def copy(self, **kwargs): + """Helper to create a copy with updated fields.""" + data = self.dict() + data.update(kwargs) + return Node(**data) + +# 5. 边定义 (拓扑结构) +class Edge(BaseModel): + source_id: str + target_id: str + connection_type: InterfaceType # 直接使用 InterfaceType + # 如果是 Data_Flow,指定端口对应关系 + source_port: Optional[str] = None + target_port: Optional[str] = None + +# 6. 完整图定义 +class GraphScenario(BaseModel): + case_id: str + title: str + intro_narrative: str + nodes: Dict[str, Node] + edges: List[Edge] + difficulty: int + win_node_id: str # 标记哪个节点是最终目标(通常是一个提交工具或最终物品) diff --git a/tasks/agentescape-25-skeleton-93dd5f71/environment/puzzle/upstream/server.py b/tasks/agentescape-25-skeleton-93dd5f71/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-25-skeleton-93dd5f71/environment/puzzle/upstream/server.py @@ -0,0 +1,1490 @@ +import json +import os +import time +import logging +import random +from pathlib import Path +from typing import Dict, Any, List, Optional +from datetime import datetime +from collections import defaultdict +from fastapi import FastAPI, HTTPException, Request +from fastapi.responses import JSONResponse +from fastapi.middleware.cors import CORSMiddleware +from pydantic import BaseModel, Field + +from models import GraphScenario, Node, InterfaceType +# from generator import ScenarioGenerator +from simulator import ToolSimulator +import uvicorn + +# 配置日志 +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler('server.log'), + logging.StreamHandler() + ] +) +logger = logging.getLogger(__name__) + +app = FastAPI( + title="AgentEscapeBench Universal Server", + version="1.0.0", + description="Industrial-grade evaluation server for escape room AI agents" +) + +# 添加 CORS 支持 +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# In-memory State +SCENARIOS: Dict[str, GraphScenario] = {} +SIMULATORS: Dict[str, ToolSimulator] = {} # case_id -> ToolSimulator +RAW_NODES_DATA: Dict[str, Dict[str, Any]] = {} # case_id -> node_id -> raw node data (for template_id) +FILE_METADATA: Dict[str, Dict[str, Any]] = {} # case_id -> metadata (for initial_values access) + +# Performance monitoring +STATS: Dict[str, Any] = { + "total_requests": 0, + "successful_requests": 0, + "failed_requests": 0, + "tool_calls": defaultdict(int), + "investigates": defaultdict(int), + "use_items": defaultdict(int), + "case_loads": 0, + "start_time": datetime.now() +} + +# Request timing middleware +@app.middleware("http") +async def add_process_time_header(request: Request, call_next): + start_time = time.time() + STATS["total_requests"] += 1 + + try: + response = await call_next(request) + STATS["successful_requests"] += 1 + process_time = time.time() - start_time + response.headers["X-Process-Time"] = str(process_time) + logger.info(f"{request.method} {request.url.path} - {response.status_code} - {process_time:.3f}s") + return response + except Exception as e: + STATS["failed_requests"] += 1 + logger.error(f"{request.method} {request.url.path} - Error: {str(e)}") + raise + +# Exception handler +@app.exception_handler(Exception) +async def global_exception_handler(request: Request, exc: Exception): + logger.error(f"Unhandled exception: {exc}", exc_info=True) + return JSONResponse( + status_code=500, + content={ + "ok": False, + "error": "Internal server error", + "detail": str(exc) if os.getenv("DEBUG") else "An error occurred" + } + ) + +# Health check endpoint +@app.get("/health") +def health_check(): + """健康检查端点""" + uptime = (datetime.now() - STATS["start_time"]).total_seconds() + return { + "status": "healthy", + "version": "1.0.0", + "uptime_seconds": uptime, + "loaded_cases": len(SCENARIOS), + "stats": { + "total_requests": STATS["total_requests"], + "successful_requests": STATS["successful_requests"], + "failed_requests": STATS["failed_requests"], + "success_rate": STATS["successful_requests"] / max(STATS["total_requests"], 1) + } + } + +# Statistics endpoint +@app.get("/stats") +def get_stats(): + """获取详细统计信息""" + return { + "stats": STATS, + "loaded_cases": list(SCENARIOS.keys()), + "uptime": str(datetime.now() - STATS["start_time"]) + } + +def _apply_progressive_reveal_at_init(scenario: GraphScenario): + """ + 在初始化时应用渐进式暴露机制(基于ITEM/HIDDEN_ITEM边) + + 新逻辑: + - 如果一个节点没有 ITEM/HIDDEN_ITEM 类型的入边,它就是初始可见的 + - 如果一个节点有 ITEM/HIDDEN_ITEM 类型的入边,它初始不可见,需要等待上游触发 + + Args: + scenario: 场景对象 + """ + # 收集所有有 ITEM/HIDDEN_ITEM 入边的节点 + nodes_with_item_edges = set() + for edge in scenario.edges: + if edge.connection_type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + nodes_with_item_edges.add(edge.target_id) + + logger.info(f"Nodes with ITEM/HIDDEN_ITEM incoming edges: {nodes_with_item_edges}") + + # 设置初始可见性:没有 ITEM/HIDDEN_ITEM 入边的节点初始可见 + initially_visible_count = 0 + for node_id, node in scenario.nodes.items(): + if node_id not in nodes_with_item_edges: + node.is_revealed = True + initially_visible_count += 1 + logger.info(f"Initial visible (no ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + else: + node.is_revealed = False + logger.debug(f"Initial hidden (has ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + + logger.info(f"Progressive reveal initialized: {initially_visible_count}/{len(scenario.nodes)} nodes initially visible") + + +def _check_inputs_match_golden(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> bool: + """ + 检查实际输入参数是否与 golden inputs 完全匹配 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + True 表示所有 golden inputs 都存在且值匹配 + """ + if not golden_inputs: + return True # 如果没有 golden inputs,认为匹配 + + for key, expected_value in golden_inputs.items(): + actual_value = arguments.get(key) + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) != str(expected_value): + logger.debug(f"Input mismatch for '{key}': expected '{expected_value}', got '{actual_value}'") + return False + + return True + + +def _get_parameter_validation_feedback(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> Dict[str, Any]: + """ + 对源头节点的参数进行详细验证,返回验证反馈 + + 注意:不返回期望值(expected),避免泄漏答案 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + 包含验证结果的字典: + - all_correct: bool - 所有参数是否正确 + - correct_params: List[str] - 正确的参数名列表 + - incorrect_params: List[str] - 错误的参数名列表(不包含期望值) + """ + if not golden_inputs: + return { + "all_correct": True, + "correct_params": [], + "incorrect_params": [] + } + + correct_params = [] + incorrect_params = [] + + for key, actual_value in arguments.items(): + # 只对用户实际提交的参数给反馈,未提交的参数不评价 + if key not in golden_inputs: + continue # 该参数不在 golden 中,跳过(如 _golden_inputs 等内部参数) + expected_value = golden_inputs[key] + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) == str(expected_value): + correct_params.append(key) + else: + # 只记录参数名,不包含期望值,避免泄漏答案 + incorrect_params.append(key) + + # all_correct:用户提交的所有参数都正确,且覆盖了全部 golden 参数 + all_provided_correct = len(incorrect_params) == 0 + all_golden_covered = all(k in arguments for k in golden_inputs) + return { + "all_correct": all_provided_correct and all_golden_covered, + "correct_params": correct_params, + "incorrect_params": incorrect_params + } + + +def _is_source_node(node_id: str, scenario: GraphScenario) -> bool: + """ + 判断节点是否是源头节点(完全没有任何入边的节点) + + 源头节点定义: + - 没有任何类型的入边(包括 DATA、ITEM、HIDDEN_ITEM) + - 即没有任何上游节点 + + Args: + node_id: 节点ID + scenario: 场景对象 + + Returns: + True 表示是源头节点 + """ + for edge in scenario.edges: + if edge.target_id == node_id: + # 只要有任何入边,就不是源头节点 + return False + + return True + + +def _check_and_reveal_ready_nodes(scenario: GraphScenario, recent_outputs: Dict[str, Any], source_node_id: str) -> List[Dict[str, Any]]: + """ + 检查并释放参数齐全的隐藏节点(渐进式暴露机制) + + 核心逻辑: + 1. 维护"可见值集合":包含所有被测模型当前可以看到的值 + - init_inputs 的值(初始可见) + - 工具执行后的实际输出值(运行时获得) + - 可见 Item 的输出值 + 2. 检查隐藏节点:该节点的所有 golden_input 值是否都在可见值集合中 + 3. 如果是,则释放该节点 + + Args: + scenario: 场景对象 + recent_outputs: 最近执行的工具的输出 + source_node_id: 刚执行的工具节点ID + + Returns: + 新释放的节点列表 + """ + newly_revealed = [] + + # 构建"可见值集合"(Set of visible values) + # 存储格式:set of values (转为字符串) + visible_values = set() + + # 1. 添加有意义的 init_inputs 值到可见值集合 + # Item 的 init_inputs 不应该加入,因为它们在密室中完全用不到 + for node_id, node in scenario.nodes.items(): + # 跳过源头 Item 节点(没有入边的 Item) + if node.type == "Item": + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,跳过其 init_inputs + continue + + # 添加其他节点的 init_inputs + for port_name, init_value in node.init_input_values.items(): + if init_value: + visible_values.add(str(init_value)) + + # 2. 添加已执行工具的所有历史输出值 + for node_id, node in scenario.nodes.items(): + if node.type == "Tool" and node.if_success and node.actual_outputs_history: + # 遍历所有历史执行记录 + for output_dict in node.actual_outputs_history: + for output_port_name, output_value in output_dict.items(): + if output_value: + visible_values.add(str(output_value)) + + # 3. 添加已被 investigate 的 Item 的 golden 输出值 + # 注意:Item 可见不等于其输出值可见,需要 investigate 后才能获得 + # 这里我们使用 actual_outputs_history 来标记 Item 是否已被 investigate + for node_id, node in scenario.nodes.items(): + if node.type == "Item" and node.is_revealed and node.actual_outputs_history: + # Item 通常只会被 investigate 一次,但为了一致性也使用历史列表 + for output_dict in node.actual_outputs_history: + for port_name, port_value in output_dict.items(): + if port_value: + visible_values.add(str(port_value)) + + # 遍历所有隐藏的节点,检查其 golden_input 是否都在可见值集合中 + for node_id, node in scenario.nodes.items(): + # 跳过已可见的节点 + if node.is_revealed: + continue + + # 只检查工具节点(物品节点由 ITEM 输出触发) + if node.type != "Tool": + continue + + # 检查该节点的所有 golden_input 值是否都在可见值集合中 + all_inputs_ready = True + missing_values = [] + + for input_port_name, golden_input_value in node.golden_input_values.items(): + # 检查这个 golden 值是否在可见值集合中 + if str(golden_input_value) not in visible_values: + all_inputs_ready = False + missing_values.append(f"{input_port_name}={golden_input_value}") + + # 如果所有 golden_input 值都在可见值集合中,释放该节点 + if all_inputs_ready and len(node.golden_input_values) > 0: + logger.info(f"All golden inputs ready for {node_id}: {list(node.golden_input_values.values())}") + + # 如果所有输入都齐全,释放该节点 + if all_inputs_ready: + node.is_revealed = True + + # 构建节点信息返回给模型 + node_info = { + "id": node.id, + "type": node.type, + "can_investigate": True, + "hint": "This tool's input parameters are now complete, you can use investigate to view detailed information" + } + + # if node.name: + # node_info["name"] = node.name + if node.description: + node_info["description"] = node.description + + newly_revealed.append(node_info) + logger.info(f"Progressive reveal: {node_id} is now ready (all inputs satisfied)") + + return newly_revealed + + +def _initialize_node_values(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]): + """ + Initialize node state and load values from port value fields. + 应用渐进式暴露机制:初始时只显示参数齐全的节点(源头节点) + + 重要区分: + 1. input_values: 只加载 metadata.initial_values 中的 init_inputs(真正的初始值) + 2. output_values: 加载 nodes[].outputs[].value(golden 输出,用于验证) + """ + # 第一步:加载所有节点的值,并将所有节点初始设为隐藏 + initial_values = metadata.get('initial_values', {}) + + for node_id, node in scenario.nodes.items(): + # 忽略 initial_visible 字段,初始全部隐藏 + # 由渐进式暴露机制根据参数齐全情况决定是否显示 + node.is_revealed = False + + if node.type == "Tool": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + elif node.type == "Item": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + + # 从 JSON 加载值 + if node_id in raw_nodes_data: + node_data = raw_nodes_data[node_id] # node_data是json文件中nodes中的字典 + + # 【重要】只加载 metadata.initial_values 中的初始输入值 + if node_id in initial_values: + init_data = initial_values[node_id] + # 加载初始输入值(用于渐进式暴露判断) + for port_name, port_value in init_data.get('init_inputs', {}).items(): + node.init_input_values[port_name] = port_value + + # 【评测用】加载 golden 输入值(用于验证模型传入的参数是否正确) + for input_port_data in node_data.get('inputs', []): + if 'value' in input_port_data: + node.golden_input_values[input_port_data['name']] = input_port_data['value'] + + # 【评测用】加载 golden 输出值(用于验证工具调用是否正确,以及 Item 节点的 content) + for output_port_data in node_data.get('outputs', []): + if 'value' in output_port_data: + node.golden_output_values[output_port_data['name']] = output_port_data['value'] + + # For Items, set content from golden_output_values + if node.type == "Item" and node.golden_output_values: + # Item 的 content 是其第一个 golden 输出值 + node.content = list(node.golden_output_values.values())[0] + + # 第二步:应用渐进式暴露机制 + # 检查所有节点,根据参数齐全情况释放源头节点(工具 + Item) + _apply_progressive_reveal_at_init(scenario) + +def _build_node_info(node: Node, raw_nodes_data: Dict[str, Any]) -> Dict[str, Any]: + """ + 构建节点信息(工具或物品) + + Args: + node: 节点对象 + raw_nodes_data: 原始节点数据(用于获取 template_id 等) + + Returns: + 节点信息字典 + """ + if node.type == "Tool": + # 过滤掉输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口) + # 这些端口仅用于控制掉落机制,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + tool_info = { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Tool", + "inputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.inputs if p.type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]], + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id(工具的标准名称) + if node.id in raw_nodes_data: + node_data = raw_nodes_data[node.id] + template_id = node_data.get('template_id') + if template_id: + tool_info['template_id'] = template_id + + return tool_info + + elif node.type == "Item": + return { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Item" + } + + else: + return { + "id": node.id, + # "name": node.name, + "type": node.type + } + +def _get_initial_observation(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]) -> Dict[str, Any]: + """ + Generate initial observation for the agent (what they see when entering the room). + + 策略: + - Tools: 只显示名称和描述,不显示接口定义。需要 investigate 才能获得详细接口信息。 + - Items: 只显示存在,不显示内容。需要 investigate 才能获得内容值。 + - init_inputs: 作为"可用信息"告诉模型,这些是可以用作工具参数的初始值。 + - init_outputs: 不告诉模型(这些是答案,需要模型通过调用工具获得)。 + """ + available_entities = [] # 统一的实体列表(Tools 和 Items) + available_information = [] # 可用的初始信息(来自 init_inputs) + + # 从 metadata.initial_values 提取 init_inputs 作为可用信息 + # 只提供值本身,不透露这些值对应哪个节点的哪个参数,让模型自己推理 + # 注意:跳过源头 Item(没有入边的 Item)的 init_inputs,因为它们在密室中完全用不到 + initial_values = metadata.get('initial_values', {}) + # initial_values字段的格式 + # "initial_values": { + # "terminal_1": { + # "init_inputs": {}, + # "init_outputs": { + # "text_output": "System initialization complete.", + # "hex_output": "48656c6c6f20576f726c64", + # "item_dispenser": "掉落了一张纸条,上面写着“请勿随意触摸终端”" + # } + # } + # } + for node_id, init_data in initial_values.items(): + # 获取节点信息,判断是否为源头 Item + node = scenario.nodes.get(node_id) + if node and node.type == "Item": + # 检查是否为源头 Item(没有入边) + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,检查是否有 init_inputs + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 有 init_inputs,需要暴露这些参数 + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + # 处理完后跳过后续的通用逻辑 + continue + + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 为每个 init_input 值创建一个信息条目(不包含 source_node 和 parameter 信息) + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + + for node in scenario.nodes.values(): + if node.is_revealed: + # Tools: 只显示基本信息,提示可以 investigate 查看详细接口 + if node.type == "Tool": + tool_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Tool", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the tool's detailed interface information for calling" + } + # 只在 name 非空时添加 + # if node.name: + # tool_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_info["description"] = node.description + + available_entities.append(tool_info) + + # Items: 只显示基本信息,提示可以 investigate 查看内容 + elif node.type == "Item": + item_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Item", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the item's content" + } + # 只在 name 非空时添加 + # if node.name: + # item_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + item_info["description"] = node.description + + available_entities.append(item_info) + + return { + "narrative": scenario.intro_narrative, + "available_entities": available_entities, # 使用统一的实体列表 + "available_information": available_information, # 可用的初始信息(只包含 init_inputs) + "win_node_id": scenario.win_node_id # 胜利节点ID,让模型知道需要关注哪个节点 + } + +@app.post("/env/reset") +def reset_case(case_id: str = None, case_file_path: str = None, session_id: str = None): + """Loads a specific case from file and resets it. + + Args: + case_id: Optional case ID for resetting an existing case + case_file_path: Path to case file for loading a new case + session_id: Optional session ID to ensure isolation between concurrent evaluations + """ + logger.info(f"Reset request - case_id: {case_id}, case_file_path: {case_file_path}, session_id: {session_id}") + STATS["case_loads"] += 1 + + if case_file_path: + if not os.path.exists(case_file_path): + logger.error(f"Case file not found: {case_file_path}") + raise HTTPException(status_code=404, detail=f"File not found: {case_file_path}") + try: + with open(case_file_path, "r", encoding="utf-8") as f: + file_data = json.load(f) + + # 转换格式:从 DAG executor 生成的格式转换为 GraphScenario 格式 + # 1. 提取 metadata + metadata = file_data.get('metadata', {}) + + # 2. 生成 case_id, title, intro_narrative + # 【修复】为每个评测会话生成唯一的 case_id,防止并发评测时状态污染 + base_name = os.path.basename(case_file_path).replace('.json', '').replace('_full', '').replace('_full2', '') + + if session_id: + # 如果提供了 session_id,使用它来确保唯一性 + case_id = f"{base_name}_{session_id}" + else: + # 否则使用时间戳和随机数确保唯一性 + unique_suffix = f"{int(time.time() * 1000)}_{random.randint(1000, 9999)}" + case_id = f"{base_name}_{unique_suffix}" + + file_data['case_id'] = case_id + logger.info(f"Generated unique case_id: {case_id} (base: {base_name}, session: {session_id})") + + if 'title' not in file_data: + file_data['title'] = f"Escape Room: {file_data['case_id']}" + + if 'intro_narrative' not in file_data: # 目前的json文件中已经有了intro_narrative字段,不会使用下面一行的内容,而是使用每个评测问题的json文件中的对应字段 + 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]".' + + # 3. 转换 nodes 列表为字典(DAG executor 生成的文件中 nodes 是列表格式) + nodes_dict = {} + for node_data in file_data['nodes']: + nodes_dict[node_data['id']] = node_data # 这里的id是template_id之后可能添加一个后缀 + file_data['nodes'] = nodes_dict # 把列表转成一个字典 + + # 4. 添加缺失的字段 + if 'difficulty' not in file_data: + file_data['difficulty'] = metadata.get('total_nodes', 5) + + if 'win_node_id' not in file_data: + file_data['win_node_id'] = metadata.get('win_node_id', '') + + scenario = GraphScenario(**file_data) + + # Extract raw nodes data for template_id access + # nodes 已经在上面转换为字典格式 + raw_nodes_data = file_data.get('nodes', {}) + RAW_NODES_DATA[scenario.case_id] = raw_nodes_data + + # Store metadata for initial values access + FILE_METADATA[scenario.case_id] = metadata + + logger.info(f"Successfully parsed case file: {scenario.case_id}, nodes: {len(scenario.nodes)}, edges: {len(scenario.edges)}") + except Exception as e: + logger.error(f"Failed to load case file: {str(e)}", exc_info=True) + raise HTTPException(status_code=500, detail=f"Failed to load case file: {str(e)}") + + # Initialize node state and load values + _initialize_node_values(scenario, raw_nodes_data, metadata) + + SCENARIOS[scenario.case_id] = scenario + simulator = ToolSimulator() + SIMULATORS[scenario.case_id] = simulator + + 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'])}") + + # 生成初始观察信息(进入密室后看到的环境) + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + ''' + initial_observation的格式: + { + "narrative": scenario.intro_narrative, + "available_entities": available_entities # 使用统一的实体列表 + "available_information": available_information # 可用的初始信息(只包含 init_inputs) + } + ''' + + return { + "ok": True, + "message": f"Case loaded from {case_file_path}", + "case_id": scenario.case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果没有提供 case_file_path,但提供了 case_id,则尝试从内存重置 + if case_id and case_id in SCENARIOS: + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + metadata = FILE_METADATA.get(case_id, {}) + + # Reset dynamic fields and re-apply progressive reveal + # 重新初始化节点状态(包括渐进式暴露) + _initialize_node_values(scenario, raw_nodes_data, metadata) + + 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'])}") + + # 生成初始观察信息 + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + + return { + "ok": True, + "message": f"Case {case_id} reset.", + "case_id": case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果既没有 case_file_path,也没有在内存中找到,返回错误 + raise HTTPException( + status_code=400, + detail="Must provide case_file_path to load a new case, or use case_id to reset an existing case." + ) + +class InvestigateRequest(BaseModel): + node_id: str + +@app.post("/env/{case_id}/investigate") +def investigate(case_id: str, req: InvestigateRequest): + """ + Investigates a Tool or Item to reveal detailed information. + + - For Tools: Returns detailed interface information (inputs/outputs) needed to call the tool + - For Items: Returns content value and triggers hidden item drops + """ + logger.info(f"Investigate request - case_id: {case_id}, node_id: {req.node_id}") + STATS["investigates"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + node = scenario.nodes[req.node_id] + + if not node.is_revealed: + logger.warning(f"Attempt to investigate hidden node: {req.node_id}") + return {"ok": False, "error": "Node is not visible yet."} + + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + newly_revealed = [] + + # 处理 Tool 的 investigate + if node.type == "Tool": + logger.info(f"Investigating tool: {req.node_id}") + + # 返回工具的详细接口信息 + # id 字段使用 node.id(节点唯一标识),agent 用这个字段识别和调用具体的节点 + # template_id 是工具类型标识符,Agent 内部用于判断工具特性(如 terminal 类工具参数可选) + # 注意:只过滤输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口),这些端口仅用于控制掉落,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + # 【端口上游依赖提示 & 初始值直接给出】 + # 针对参数语义模糊(全为数字类型)的工具,在 investigate 返回信息中标注 + # 哪个输入端口来自哪个上游节点(upstream_from)。 + # 对于所有工具:若该节点不是纯源头节点(有任意数据流入边), + # 且某个端口没有上游入边(值来自初始可见参数),则直接给出该端口的 golden input 值。 + AMBIGUOUS_TOOLS = { + "num_base_convert", "calc_modexp", "calc_modexp_int", + "calc_inv_mod", "calc_inv_mod_int", "crypto_rsa_decrypt_hex", "geo_haversine" + } + # Terminal 类工具自带参数对错反馈机制,玩家/模型可自行试错, + # 无需在 investigate 时直接暴露 init_value + SELF_FEEDBACK_TOOLS = { + "terminal_1", "terminal_2", + "Logic Terminal", "Math Terminal", "Encryption Terminal", "Sequence Terminal" + } + _template_id_for_hint = raw_nodes_data.get(node.id, {}).get("template_id", "") + # 构建数据流入边映射(对所有工具):{target_port -> (source_node_id, source_port)} + _upstream_map = {} + for _edge in scenario.edges: + if (_edge.target_id == node.id + and _edge.connection_type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM] + and _edge.target_port is not None): + _upstream_map[_edge.target_port] = (_edge.source_id, _edge.source_port) + # 判断该节点是否有任意数据流入边(即不是纯源头节点) + _has_any_upstream = len(_upstream_map) > 0 + # 判断该节点是否有任意入边(包括 ITEM/HIDDEN_ITEM 掉落边) + # 有任意入边(含掉落边)但无数据流入边的节点,其输入来自初始可见参数,应直接给出 + _has_any_edge = any(_edge.target_id == node.id for _edge in scenario.edges) + # 构建 inputs 列表 + _inputs_list = [] + for p in node.inputs: + if p.type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + continue + port_dict = {"name": p.name, "type": p.type, "description": p.description} + if p.name in _upstream_map: + # 该端口有上游数据流依赖,且属于语义模糊工具 → 标注来源 + if _template_id_for_hint in AMBIGUOUS_TOOLS: + src_node_id, src_port = _upstream_map[p.name] + port_dict["upstream_from"] = f"{src_node_id}.{src_port}" if src_port else src_node_id + elif _has_any_edge and _template_id_for_hint not in SELF_FEEDBACK_TOOLS: + # 该节点有任意入边,但此端口没有数据流入边 → 值来自初始可见参数,直接给出 + # 排除自带反馈机制的 terminal 类工具(它们通过执行结果反馈对错,无需提前暴露参数值) + golden_val = node.golden_input_values.get(p.name) + if golden_val is not None: + port_dict["init_value"] = golden_val + _inputs_list.append(port_dict) + + tool_details = { + "id": node.id, # 节点 ID,用于唯一标识和调用这个具体节点 + "type": "Tool", + "inputs": _inputs_list, + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id 用于 Agent 内部判断工具类型(不会展示给被测模型) + if node.id in raw_nodes_data: + template_id = raw_nodes_data[node.id].get('template_id') + if template_id: + tool_details["_template_id"] = template_id # 使用下划线前缀标记为内部字段 + + # 只在 name 非空时添加 + # if node.name: + # tool_details["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_details["description"] = node.description + + # 添加 narrative 字段(如果存在) + if node.id in raw_nodes_data: + narrative = raw_nodes_data[node.id].get('narrative') + if narrative: + tool_details['narrative'] = narrative + + # 不再返回 init_values,避免泄漏答案 + # investigate 只应该返回工具的接口定义,不应该暴露初始值 + + # 【新增】检查该 Tool 是否有待触发的 HIDDEN_ITEM 掉落 + # 如果该工具已按照 golden_input 正确执行,且有 HIDDEN_ITEM 输出边,则触发掉落 + if node.has_hidden_item_ready: + logger.info(f"Tool has HIDDEN_ITEM ready - triggering passive drop for: {req.node_id}") + + # 遍历该工具的所有 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + # 重置标志,已经触发过了,避免重复 + node.has_hidden_item_ready = False + + logger.info(f"Tool investigation successful - node: {req.node_id}, revealed: {len(newly_revealed)}") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Tool", + "details": tool_details + } + + # 如果有新掉落的节点,添加到响应中 + if newly_revealed: + result["newly_revealed"] = newly_revealed + + return result + + # 处理 Item 的 investigate + elif node.type == "Item": + logger.info(f"Investigating item: {req.node_id}") + + # 【第一步】检查该 Item 是否有需要参数的输入端口 + # 如果有,且尚未通过 use_item 验证,则不返回内容,只返回参数要求 + required_inputs = [] + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + inputs_info = raw_node.get('inputs', []) + required_inputs = [ + { + "name": inp.get("name"), + "type": inp.get("type"), + "description": inp.get("description", "") + } + for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + # 如果有 required_inputs 且尚未通过 use_item 验证(if_success == False) + # 则不返回内容,只返回参数要求提示 + if required_inputs and not node.if_success: + logger.info(f"Item has required inputs and not yet unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "required_inputs": required_inputs + } + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + param_names = ', '.join([inp['name'] for inp in required_inputs]) + 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}" + + return result + + # 【新增】如果有 required_inputs 且已经通过 use_item 验证(if_success == True) + # 则返回提示:该节点已经被成功解决 + if required_inputs and node.if_success: + logger.info(f"Item has required inputs and already unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "message": "This item has already been successfully unlocked by you." + } + return result + + # 【第二步】该 Item 没有 required_inputs 或已通过验证,返回内容 + # 1. 返回 Item 的 golden_output_values(即 Item 的内容) + # 注意:某些 Item 仅用于触发 HIDDEN_ITEM 掉落,没有实际内容 + has_actual_content = bool(node.golden_output_values) or node.content is not None + content = node.golden_output_values if node.golden_output_values else node.content + + # 【关键】将 golden_output_values 追加到 actual_outputs_history,标记该 Item 已被 investigate + # 这样在渐进式暴露时,这些值才会被加入可见值集合 + # 即使是空字典(仅触发 HIDDEN_ITEM 的 Item),也要记录,以便渐进式暴露逻辑知道该 Item 已被调查 + if node.golden_output_values is not None: + node.actual_outputs_history.append(dict(node.golden_output_values)) + + # 2. Trigger Hidden Item Drops (Passive Drop) + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + logger.info(f"Item investigation successful - node: {req.node_id}, has_content: {has_actual_content}, revealed: {len(newly_revealed)}") + + # 【渐进式暴露】旧机制(基于 golden_input)已禁用 + # 现在完全由 ITEM/HIDDEN_ITEM 边触发控制节点可见性 + # 上面的 HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, node.golden_output_values or {}, node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # logger.info(f"Progressive reveal after Item investigate: {len(progressive_revealed)} nodes now ready") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Item" + } + + # 只在有实际内容时才添加 content 字段 + # 对于仅触发 HIDDEN_ITEM 掉落的 Item,不返回 content 字段,避免返回 None 或空字典让模型困惑 + if has_actual_content: + result["content"] = content + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型通过 investigate 获得内容后,需要自己识别这是否是胜利字符串 + + return result + + else: + logger.warning(f"Attempt to investigate unknown node type: {req.node_id} (type: {node.type})") + return {"ok": False, "error": f"Cannot investigate node type: {node.type}"} + +class ToolCallRequest(BaseModel): + node_id: str # 使用 node_id 精确指定要调用的节点 + arguments: Dict[str, Any] + +@app.post("/env/{case_id}/tool_call") +def tool_call(case_id: str, req: ToolCallRequest): + """Executes a tool and triggers item drops.""" + logger.info(f"Tool call request - case_id: {case_id}, node_id: {req.node_id}, args: {list(req.arguments.keys())}") + STATS["tool_calls"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + + # 通过 node_id 精确查找节点 + node_id = req.node_id + if node_id not in scenario.nodes: + logger.error(f"Node not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + tool_node = scenario.nodes[node_id] + + if not tool_node: + logger.error(f"Tool not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Tool not found") + + if not tool_node.is_revealed: + logger.warning(f"Attempt to call hidden tool: {node_id}") + return {"ok": False, "error": "Tool is not visible yet."} + + if tool_node.type != "Tool": + logger.warning(f"Attempt to call non-tool node: {node_id} (type: {tool_node.type})") + return {"ok": False, "error": "Only tools can be called."} + + # 1. Execute Tool (Real Execution via Simulator) + simulator = SIMULATORS[case_id] + + # Get tool name from template_id if available, otherwise use node name + tool_name = tool_node.name + if case_id in RAW_NODES_DATA and node_id in RAW_NODES_DATA[case_id]: + template_id = RAW_NODES_DATA[case_id][node_id].get('template_id') + if template_id: + tool_name = template_id + + # 文件处理工具和 Terminal 需要验证输入并返回预先计算的输出 + # 传递节点的实际输入输出值(从 DAG 执行后填充的数据) + tool_arguments = dict(req.arguments) # Make a copy + + # 传递节点的 golden values(从 JSON 的 inputs[].value 和 outputs[].value 加载) + # 用于在评测阶段验证被测模型传入的参数是否正确 + if tool_node.golden_input_values: + tool_arguments['_golden_inputs'] = tool_node.golden_input_values + if tool_node.golden_output_values: + tool_arguments['_golden_outputs'] = tool_node.golden_output_values + + logger.debug(f"Executing tool {tool_name} (node: {tool_node.name}) with args {tool_arguments}") + + try: + output_values = simulator.execute(tool_name, tool_arguments) + logger.info(f"Tool invoked - {tool_name}: {list(output_values.keys())}") + except Exception as e: + logger.error(f"Tool execution failed - {tool_name}: {str(e)}", exc_info=True) + return {"ok": False, "error": f"Tool execution failed: {str(e)}"} + + # 检查验证结果(精细化错误反馈) + validation = output_values.pop("_validation", {"valid": True}) + + if not validation["valid"]: + # 根据错误类型构造友好的错误消息 + error_type = validation.get("error_type") + + if error_type == "missing_required": + missing = validation.get("missing_params", []) + error_msg = f"Error: Missing required parameters {', '.join(missing)}" + + elif error_type == "type_error": + param = validation.get("param_name") + message = validation.get("message", "Parameter type error") + error_msg = f"Error: {message}" + + elif error_type == "incomplete_optional": + provided = validation.get("provided_params", []) + missing = validation.get("missing_params", []) + error_msg = ( + f"Hint: You provided some parameters ({', '.join(provided)}), " + f"but may also need: {', '.join(missing)}.\n" + f"Trying to provide these parameters together might yield better results." + ) + + elif error_type == "value_mismatch": + param = validation.get("param_name") + hint = validation.get("hint", "Parameter value may be incorrect") + error_msg = f"Hint: {hint}.\nPlease check if this parameter value meets the requirements." + + else: + error_msg = validation.get("hint") or validation.get("message", "Parameter validation failed") + + logger.info(f"Tool validation failed - {tool_name}: {error_type}") + return { + "ok": False, + "error": error_msg, + "error_type": error_type + } + + # Simulate success + tool_node.if_success = True + + # 【关键】将本次执行的输出值追加到历史列表(用于渐进式暴露判断) + # 每次调用都会记录,不会覆盖之前的执行结果 + tool_node.actual_outputs_history.append(dict(output_values)) + + # 2. 检查是否应该触发掉落(只有输入参数正确时才掉落) + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, tool_node.golden_input_values) + + newly_revealed = [] + investigate_hints = [] # 提示模型哪些节点可以 investigate 来发现隐藏内容 + + if inputs_match_golden: + logger.info(f"✓ Tool inputs match golden - node: {node_id}, triggering drops") + + # 检查该工具是否有 ITEM 或 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == tool_node.id: + target_node = scenario.nodes[edge.target_id] + + # ITEM 边:立即掉落(主动掉落) + if edge.connection_type == InterfaceType.ITEM: + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from {node_id})") + + # HIDDEN_ITEM 边:不立即掉落,标记并提示(被动掉落) + elif edge.connection_type == InterfaceType.HIDDEN_ITEM: + # 标记该工具有待触发的 HIDDEN_ITEM 掉落 + tool_node.has_hidden_item_ready = True + + # 提示模型可以 investigate 这个工具来发现隐藏内容 + hint_info = { + "tool_id": tool_node.id, + "hint": f"Tool '{tool_node.id}' seems to hide something, try investigating it to discover more information" + } + # if tool_node.name: + # hint_info["tool_name"] = tool_node.name + + investigate_hints.append(hint_info) + logger.info(f"HIDDEN_ITEM ready: {tool_node.id} -> {target_node.id} (will drop on investigate)") + else: + logger.info(f"✗ Tool inputs do NOT match golden - node: {node_id}, no drops triggered") + + response = { + "ok": True, + "message": "Tool invoked", + "output_values": output_values # Return raw outputs to Agent + } + + # 【新增】对源头节点进行参数验证反馈 + # 源头节点:没有数据流入边的节点,这些节点的参数需要模型自己推理 + # 验证模型使用的参数是否正确,并提供明确的反馈 + if _is_source_node(node_id, scenario) and tool_node.golden_input_values: + validation_feedback = _get_parameter_validation_feedback(req.arguments, tool_node.golden_input_values) + + if validation_feedback["all_correct"]: + # 用户提交了全部 golden 参数且全部正确 + response["parameter_feedback"] = { + "status": "correct", + "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." + } + logger.info(f"✓ Source node parameters all correct - node: {node_id}") + elif validation_feedback["incorrect_params"]: + # 有提交了但值错误的参数,只对这些参数给出反馈 + incorrect_list = [] + for param_name in validation_feedback["incorrect_params"]: + incorrect_list.append(f" - Parameter '{param_name}' is incorrect") + + correct_info = "" + if validation_feedback["correct_params"]: + correct_info = f"\n✓ Correct parameters: {', '.join(validation_feedback['correct_params'])}" + + response["parameter_feedback"] = { + "status": "incorrect", + "message": ( + f"⚠️ Some parameters are incorrect:\n" + + "\n".join(incorrect_list) + + correct_info + + 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." + ), + "incorrect_params": validation_feedback["incorrect_params"], + "correct_params": validation_feedback["correct_params"] + } + logger.info(f"✗ Source node parameters incorrect - node: {node_id}, incorrect: {validation_feedback['incorrect_params']}") + # else: 部分提交且全部正确 → 不给任何 parameter_feedback,避免对未提交的参数发表意见 + + # 检查工具调用是否完全正确(输出与 golden outputs 匹配) + # 用于给模型正向反馈,让它知道这个工具已经正确调用过,避免重复调用 + # 注意:只有当输出完全匹配时才标记为 correct,不会在错误时提供具体错误信息 + # if tool_node.golden_output_values and output_values: + # is_correct = True + # for port_name, expected_value in tool_node.golden_output_values.items(): + # actual_value = output_values.get(port_name) + # if str(actual_value) != str(expected_value): + # is_correct = False + # break + + # if is_correct: + # response["tool_call_correct"] = True + # logger.info(f"✓ Tool called with correct result - node: {node_id}") + + # 只在有新内容掉落时才返回 newly_revealed + if newly_revealed: + response["newly_revealed"] = newly_revealed + + # 添加 investigate 提示(对于有待触发 HIDDEN_ITEM 掉落的工具) + if investigate_hints: + response["investigate_hints"] = investigate_hints + + # 3. 渐进式暴露机制 - 现在完全由 ITEM/HIDDEN_ITEM 边控制 + # 旧机制(基于 golden_input 检查)已被禁用 + # 新机制中,节点的可见性只由 ITEM/HIDDEN_ITEM 边触发决定 + # 上面的 ITEM/HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, output_values, tool_node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # response["newly_revealed"] = newly_revealed + # logger.info(f"Progressive reveal: {len(progressive_revealed)} nodes now ready") + + # Check if this is the win node + if node_id == scenario.win_node_id: + # 验证输出值是否等于预期的胜利值 + # 从节点的 golden_output_values 中获取预期值(在 _initialize_node_values 时从 JSON 加载) + expected_outputs = tool_node.golden_output_values + + # 检查实际输出是否与预期输出匹配 + is_correct = False + victory_string = None + mismatch_info = [] + + if expected_outputs and output_values: + # 检查每个预期输出端口的值是否匹配 + is_correct = True + for port_name, expected_value in expected_outputs.items(): + actual_value = output_values.get(port_name) + if actual_value != expected_value: + is_correct = False + mismatch_info.append(f"Port '{port_name}': expected '{expected_value}', actual '{actual_value}'") + logger.warning(f"Win node output mismatch - port: {port_name}, expected: {expected_value}, actual: {actual_value}") + + # 如果所有输出都匹配,使用第一个输出作为胜利字符串 + if is_correct and output_values: + victory_string = list(output_values.values())[0] + else: + logger.warning(f"Win node called but missing output values - expected: {expected_outputs}, actual: {output_values}") + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型调用工具获得输出后,需要自己识别这是否是胜利字符串并提交 + if is_correct: + logger.info(f"🎯 Win node called with correct output - case: {case_id}, node: {node_id}, victory: {victory_string}") + else: + logger.info(f"❌ Win node called with incorrect output - case: {case_id}, node: {node_id}") + + return response + +class UseItemRequest(BaseModel): + node_id: str = Field(..., description="The ID of the Item node to use (must be Item type)") + arguments: Dict[str, Any] = Field(default_factory=dict, description="Input arguments to provide to the item") + +@app.post("/env/{case_id}/use_item") +def use_item(case_id: str, req: UseItemRequest): + """ + Use an Item node by providing input arguments. + + This is specifically for Item nodes that require parameters to be "unlocked" or "activated", + such as containers that need a password/fingerprint. + + - Validates that the node is of type Item + - Checks if provided arguments match the item's golden_input_values + - If match: triggers ITEM-type edge drops and returns the item's content + - If not match: returns error message + """ + logger.info(f"Use item request - case_id: {case_id}, node_id: {req.node_id}, args: {req.arguments}") + STATS["use_items"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + item_node = scenario.nodes[req.node_id] + + if not item_node.is_revealed: + logger.warning(f"Attempt to use hidden item: {req.node_id}") + return {"ok": False, "error": "Item is not visible yet."} + + if item_node.type != "Item": + logger.warning(f"Attempt to use non-item node: {req.node_id} (type: {item_node.type})") + return {"ok": False, "error": "Only Item nodes can be used with use_item. Tools should be called with tool_call."} + + # 【新增】检查该 Item 是否已经被成功解锁 + # 如果已经被正确使用过,直接返回成功提示 + if item_node.if_success: + logger.info(f"Item already unlocked, returning success message: {req.node_id}") + return { + "ok": True, + "message": "This item has already been successfully unlocked by you." + } + + # 检查该 Item 是否真的需要通过 use_item 提供参数 + # 只有当 Item 有非 Item/Hidden_Item 类型的输入时,才应该使用 use_item + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + non_hidden_inputs = [ + inp for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + if not non_hidden_inputs: + # 该 Item 不需要参数,应该只使用 investigate + logger.warning(f"Attempt to use_item on a node that doesn't require parameters: {req.node_id}") + return { + "ok": False, + "error": "This item does not require parameters. Please use investigate to examine the item directly." + } + + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, item_node.golden_input_values) + + if not inputs_match_golden: + logger.info(f"✗ Item inputs do NOT match golden - node: {req.node_id}") + # 提供更详细的错误信息,帮助 Agent 理解问题 + # 只显示非 Item/Hidden_Item 类型的参数(Hidden_Item 由系统自动处理) + expected_params = [] + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + expected_params = [ + inp.get("name") for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + provided_params = list(req.arguments.keys()) if req.arguments else [] + + # 检查参数名是否匹配 + if set(expected_params) == set(provided_params): + # 参数名正确但值不匹配 - 不泄漏正确的值 + error_msg = f"Parameter names are correct, but the parameter values are incorrect. Please try using different parameter values." + else: + error_msg = f"Parameter names do not match. Expected parameter names: {expected_params}, you provided: {provided_params}." + + return { + "ok": False, + "error": error_msg + } + + logger.info(f"✓ Item inputs match golden - node: {req.node_id}, activating item") + + # 标记该 Item 已被正确使用 + item_node.if_success = True + + # 将 golden_output_values 追加到 actual_outputs_history + if item_node.golden_output_values: + item_node.actual_outputs_history.append(dict(item_node.golden_output_values)) + + # 触发 ITEM 类型边的掉落 + newly_revealed = [] + for edge in scenario.edges: + if edge.source_id == item_node.id and edge.connection_type == InterfaceType.ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from use_item on {req.node_id})") + + # 检查是否为 Win Node + win_node_id = scenario.win_node_id + is_win_node = (req.node_id == win_node_id) + + # 构建返回结果 + result = { + "ok": True, + "message": "Item used successfully.", + "content": item_node.golden_output_values if item_node.golden_output_values else None + } + + # 获取 narrative(如果存在) + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + narrative = raw_nodes_data[req.node_id].get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 如果是 Win Node,只记录日志 + if is_win_node: + logger.info(f"Win node (Item) unlocked via use_item - case: {case_id}, node: {req.node_id}") + + return result + + +class SubmitAnswerRequest(BaseModel): + answer: str = Field(..., description="The victory string to submit") + +@app.post("/env/{case_id}/submit_answer") +def submit_answer(case_id: str, req: SubmitAnswerRequest): + """ + 提交答案接口 + 被测模型在获得胜利字符串提示后,需要调用此接口提交答案 + """ + logger.info(f"Submit answer request - case_id: {case_id}, answer: {req.answer}") + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + + # 获取 win_node 的 golden_output_values + if not scenario.win_node_id: + logger.error(f"No win node defined for case: {case_id}") + return { + "ok": False, + "error": "This case has no victory node defined" + } + + win_node = scenario.nodes.get(scenario.win_node_id) + if not win_node: + logger.error(f"Win node not found: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node does not exist" + } + + # 获取正确的胜利字符串(取第一个 golden_output_value) + if win_node.golden_output_values: + correct_answer = list(win_node.golden_output_values.values())[0] + else: + logger.error(f"Win node has no golden_output_values: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node has no correct answer" + } + + # 验证提交的答案 + if req.answer == correct_answer: + logger.info(f"🎉 CORRECT ANSWER SUBMITTED - case: {case_id}, answer: {req.answer}") + return { + "ok": True, + "is_win": True, + "victory_message": f"🎉 Congratulations on successfully escaping the room! Your answer is correct: {req.answer}" + } + else: + logger.info(f"❌ INCORRECT ANSWER SUBMITTED - case: {case_id}, submitted: {req.answer}, correct: {correct_answer}") + return { + "ok": True, + "is_win": False, + "error": f"The submitted answer is incorrect. You submitted: {req.answer}" + } + +if __name__ == "__main__": + + uvicorn.run(app, host="0.0.0.0", port=8000) \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-93dd5f71/environment/puzzle/upstream/simulator.py b/tasks/agentescape-25-skeleton-93dd5f71/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-25-skeleton-93dd5f71/environment/puzzle/upstream/simulator.py @@ -0,0 +1,2911 @@ +import hashlib +import hmac +import base64 +import binascii +import zlib +import json +import uuid +import math +import re +from typing import Dict, Any, List + +class ToolSimulator: + def __init__(self): + """工具模拟器 + + 文件处理工具(zip_unzip, zip_unzip_file, zip_unzip_item, json_get, csv_query, + regex_search, graph_shortest_path)不需要真实文件系统。 + 这些工具只验证输入参数,然后返回预先初始化好的 golden_outputs。 + """ + self.tool_map = { + # 数论 + "calc_bigmul": self.calc_bigmul, + "calc_modexp": self.calc_modexp, + "calc_modexp_int": self.calc_modexp_int, + "calc_gcd": self.calc_gcd, + "calc_gcd_int": self.calc_gcd_int, + "calc_inv_mod": self.calc_inv_mod, + "calc_inv_mod_int": self.calc_inv_mod_int, + + # 哈希 + "hash_sha256": self.hash_sha256, + "hash_md5": self.hash_md5, + "hmac_sha256": self.hmac_sha256, + + # 编码 + "base64_decode": self.base64_decode, + "base64_encode": self.base64_encode, + "hex_decode": self.hex_decode, + "hex_encode": self.hex_encode, + "zlib_inflate": self.zlib_inflate, + "zlib_deflate": self.zlib_deflate, + + # 文件 + "zip_unzip": self.zip_unzip, + "zip_unzip_file": self.zip_unzip_file, + "zip_unzip_item": self.zip_unzip_item, + "regex_search": self.regex_search, + "json_get": self.json_get, + "csv_query": self.csv_query, + "code_py_exec": self.code_py_exec, + + # 图 + "graph_shortest_path": self.graph_shortest_path, + + # 加解密 (简化模拟) + "crypto_aes_cbc_decrypt": self.crypto_aes_cbc_decrypt, + "crypto_rsa_decrypt_hex": self.crypto_rsa_decrypt_hex, + + # 其他 + "num_base_convert": self.num_base_convert, + "time_convert": self.time_convert, + "checksum_crc32": self.checksum_crc32, + "geo_haversine": self.geo_haversine, + "otp_totp_generate": self.otp_totp_generate, + "unicode_norm": self.unicode_norm, + "text_bidi_sanitize": self.text_bidi_sanitize, + "text_xor_hex": self.text_xor_hex, + "text_rotN": self.text_rotN, + "luhn_check": self.luhn_check, + "iban_validate": self.iban_validate, + + # 物理 + "matter_synthesizer": self.matter_synthesizer, + + # 终端机 + "terminal_1": self.terminal_1, + "terminal_2": self.terminal_2, + "Logic Terminal": self.logic_terminal, + "Math Terminal": self.math_terminal, + "Encryption Terminal": self.crypt_terminal, + "Sequence Terminal": self.sequence_terminal + } + + def execute(self, tool_name: str, inputs: Dict[str, Any]) -> Dict[str, Any]: + if tool_name not in self.tool_map: + # Fallback for unknown tools: return dummy outputs based on expected output types + # This should ideally not happen if all tools are implemented + return {} + + try: + return self.tool_map[tool_name](inputs) + except Exception as e: + print(f"Error executing {tool_name}: {e}") + # Return empty or error indication? For generation, we might want to fail hard or return dummy. + # For now, return dummy to keep flow going, but log error. + return {} + + # --- Implementations --- + + def calc_bigmul(self, inputs): + # Check if required parameters are present + if "a" not in inputs or "b" not in inputs: + raise ValueError("Missing required parameters 'a' and/or 'b'") + + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + return {"product": str(a * b)} + except (ValueError, TypeError) as e: + raise ValueError(f"Failed to convert parameters to integers: {str(e)}") + + def calc_modexp(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + try: + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if isinstance(base, str): + base = int(base) + elif not isinstance(base, int): + raise ValueError("Parameter 'base' must be a string or integer") + + if isinstance(exp, str): + exp = int(exp) + elif not isinstance(exp, int): + raise ValueError("Parameter 'exp' must be a string or integer") + + if isinstance(mod, str): + mod = int(mod) + elif not isinstance(mod, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": str(pow(base, exp, mod))} + + def calc_modexp_int(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["base"], int): + raise ValueError("Parameter 'base' must be an integer") + if not isinstance(inputs["exp"], int): + raise ValueError("Parameter 'exp' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": pow(base, exp, mod)} + + def calc_gcd(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + # 计算 GCD 并返回字符串格式(符合 Big_Int 输出类型) + result = math.gcd(a, b) + return {"gcd": str(result)} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def calc_gcd_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["b"], int): + raise ValueError("Parameter 'b' must be an integer") + + # 获取参数 + a = inputs["a"] + b = inputs["b"] + + return {"gcd": math.gcd(a, b)} + + def calc_inv_mod(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + m = inputs["mod"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(m, str): + m = int(m) + elif not isinstance(m, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": str(pow(a, -1, m))} + except ValueError as e: + # 模逆不存在时,返回一个特殊值(用于数据传递) + # 在 DAG 生成阶段,这允许数据流继续 + return {"inv": str(a)} + + def calc_inv_mod_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + a = inputs["a"] + m = inputs["mod"] + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": pow(a, -1, m)} + except ValueError as e: + raise ValueError(f"Modular inverse does not exist: {str(e)}") + + def hash_sha256(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.sha256(text.encode()).hexdigest()} + + def hash_md5(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.md5(text.encode()).hexdigest()} + + def hmac_sha256(self, inputs): + # 参数检查 + if "hex_key" not in inputs: + raise ValueError("Missing required parameter: hex_key") + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["hex_key"], str): + raise ValueError("Parameter 'hex_key' must be a string") + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + try: + key = bytes.fromhex(inputs["hex_key"]) + text = inputs["text"].encode() + return {"hex": hmac.new(key, text, hashlib.sha256).hexdigest()} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def base64_decode(self, inputs): + # 参数检查 + if "data" not in inputs: + raise ValueError("Missing required parameter: data") + + # 类型检查 + if not isinstance(inputs["data"], str): + raise ValueError("Parameter 'data' must be a string") + + data = inputs["data"] + try: + return {"bytes_hex": binascii.hexlify(base64.b64decode(data)).decode()} + except Exception as e: + raise ValueError(f"Base64 decode error: {str(e)}") + + def base64_encode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"b64": base64.b64encode(bytes.fromhex(hex_data)).decode()} + except Exception as e: + raise ValueError(f"Base64 encode error: {str(e)}") + + def hex_decode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"text": bytes.fromhex(hex_data).decode('utf-8', errors='ignore')} + except Exception as e: + raise ValueError(f"Hex decode error: {str(e)}") + + def hex_encode(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + try: + return {"hex": text.encode().hex()} + except Exception as e: + raise ValueError(f"Hex encode error: {str(e)}") + + + # 到此处实现已经更新 + + def zlib_inflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("Parameter 'hex' must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("Missing required parameter: hex") + + try: + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空字符串 + if not hex_data: + raise ValueError("Empty hex string provided") + + # 检查十六进制字符串的有效性 + if len(hex_data) % 2 != 0: + raise ValueError("Hex string must have even length") + + # 检查是否只包含有效的十六进制字符 + if not all(c in '0123456789abcdefABCDEF' for c in hex_data): + raise ValueError("Invalid hex string provided") + + # 尝试解压缩 + return {"text": zlib.decompress(bytes.fromhex(hex_data)).decode('utf-8')} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hex string provided") from e + raise ValueError(f"Invalid zlib data: {e}") from e + except Exception as e: + raise RuntimeError(f"Failed to inflate data: {e}") from e + + def zlib_deflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("Parameter 'text' must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("Missing required parameter: text") + + try: + # 压缩文本 + return {"hex": zlib.compress(text.encode('utf-8')).hex()} + except Exception as e: + raise RuntimeError(f"Failed to deflate data: {e}") from e + + # --- File Operations --- + + def zip_unzip(self, inputs): + """ZIP 解压工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"files": golden_outputs.get("files", "")} + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return {"files": golden_outputs.get("files", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "files" in golden_outputs: + # 验证必需参数 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 检查类型 + if has_zip_id and not isinstance(zip_id, str): + return {"error": "Parameter 'zip_id' must be a string type"} + if has_password and not isinstance(password, str): + return {"error": "Parameter 'password' must be a string type"} + + # 验证输入是否与预期匹配 + if golden_inputs: + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return {"files": golden_outputs["files"]} + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + # 没有golden_inputs但有golden_outputs,直接返回输出 + return {"files": golden_outputs["files"]} + + # 如果没有预期输出,返回空结果 + return {"files": ""} + + def regex_search(self, inputs): + """正则搜索工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"matches": golden_outputs.get("matches", "[]")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "matches" in golden_outputs: + # 提取实际参数 + pattern = inputs.get("pattern") + file_id = inputs.get("file_id") + text = inputs.get("text") + + # 1. 检查必需参数 + if pattern is None: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["pattern"], + "message": "Missing required parameter 'pattern'" + } + } + + # 类型检查 + if not isinstance(pattern, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "pattern", + "message": "Parameter 'pattern' must be a string type" + } + } + if file_id is not None and not isinstance(file_id, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if text is not None and not isinstance(text, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "text", + "message": "Parameter 'text' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合 + provided_params = {} + if pattern is not None: + provided_params["pattern"] = pattern + if file_id is not None: + provided_params["file_id"] = file_id + if text is not None: + provided_params["text"] = text + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数(关键改进) + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_pattern = golden_inputs.get("pattern") + expected_file_id = golden_inputs.get("file_id") + expected_text = golden_inputs.get("text") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_pattern is not None: + if str(pattern) != str(expected_pattern): + incorrect_params.append("pattern") + else: + correct_params.append("pattern") + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_text is not None: + if str(text) != str(expected_text): + incorrect_params.append("text") + else: + correct_params.append("text") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "matches": "[]", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "matches": golden_outputs["matches"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空列表 + return {"matches": "[]"} + + def json_get(self, inputs): + """JSON 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"values": golden_outputs.get("values", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "values" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + jsonpath = inputs.get("jsonpath", "") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if jsonpath is not None and not isinstance(jsonpath, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "jsonpath", + "message": "Parameter 'jsonpath' must be a string type" + } + } + + # 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:jsonpath有默认值"") + provided_params = {} + if file_id is not None: + provided_params["file_id"] = file_id + if jsonpath != "": + provided_params["jsonpath"] = jsonpath + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_jsonpath = golden_inputs.get("jsonpath") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_jsonpath is not None: + if str(jsonpath) != str(expected_jsonpath): + incorrect_params.append("jsonpath") + else: + correct_params.append("jsonpath") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "values": "", + "_validation": validation_info + } + + # 所有验证通过,返回正确输出 + return { + "values": golden_outputs["values"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"values": ""} + + def csv_query(self, inputs): + """CSV 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"rows": golden_outputs.get("rows", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "rows" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + select_columns = inputs.get("select", "") + where_clause = inputs.get("where", "") + + # 1. 检查必需参数 + if file_id is None: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["file_id"], + "message": "Missing required parameter 'file_id'" + } + } + + # 类型检查 + if not isinstance(file_id, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if not isinstance(select_columns, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "select", + "message": "Parameter 'select' must be a string type" + } + } + if not isinstance(where_clause, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "where", + "message": "Parameter 'where' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:select和where有默认值"") + provided_params = {"file_id": file_id} + if select_columns != "": + provided_params["select"] = select_columns + if where_clause != "": + provided_params["where"] = where_clause + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_select = golden_inputs.get("select") + expected_where = golden_inputs.get("where") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_select is not None: + if str(select_columns) != str(expected_select): + incorrect_params.append("select") + else: + correct_params.append("select") + + if expected_where is not None: + if str(where_clause) != str(expected_where): + incorrect_params.append("where") + else: + correct_params.append("where") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "rows": "", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "rows": golden_outputs["rows"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"rows": ""} + + def graph_shortest_path(self, inputs): + """图最短路径工具 + + 如果有 _golden_outputs 或 _init_outputs,验证输入并返回预设输出。 + 否则执行真实的 Dijkstra 算法。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 检查是否在预设模式中(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + if golden_outputs and "path" in golden_outputs: + # 评测阶段但没有 golden_inputs,直接返回 outputs + if not golden_inputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 评测模式:验证输入参数是否匹配 golden 值 + src = inputs.get("src") + dst = inputs.get("dst") + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + + has_src = src is not None and src != "" + has_dst = dst is not None and dst != "" + + # 验证必需参数 + if not has_src or not has_dst: + missing = [] + if not has_src: + missing.append("src") + if not has_dst: + missing.append("dst") + return {"error": "Missing required parameters: " + ", ".join(missing)} + + # 类型检查 + if not isinstance(src, str): + return {"error": "Parameter 'src' must be a string"} + if not isinstance(dst, str): + return {"error": "Parameter 'dst' must be a string"} + + # 验证输入是否匹配期望值 + if golden_inputs: + expected_src = golden_inputs.get("src") + expected_dst = golden_inputs.get("dst") + expected_file_id = golden_inputs.get("file_id") + expected_graph_data = golden_inputs.get("graph_data") + + # 收集验证结果 + incorrect_params = [] + correct_params = [] + + # 检查必需参数是否匹配 + if expected_src is not None: + if str(src) != str(expected_src): + incorrect_params.append("src") + else: + correct_params.append("src") + + if expected_dst is not None: + if str(dst) != str(expected_dst): + incorrect_params.append("dst") + else: + correct_params.append("dst") + + # 检查可选参数(如果在 expected_inputs 中定义了) + if expected_file_id is not None: + if file_id != expected_file_id: + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_graph_data is not None: + if graph_data != expected_graph_data: + incorrect_params.append("graph_data") + else: + correct_params.append("graph_data") + + # 如果有参数不正确,返回详细的反馈 + if incorrect_params: + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 验证通过,返回预设的输出 + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 获取参数(真实执行路径) + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + # Support both src/dst (interface definition) and start/end (original implementation) + start = inputs.get("src") + end = inputs.get("dst") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + raise TypeError("file_id must be a string") + + if graph_data is not None and not isinstance(graph_data, str): + raise TypeError("graph_data must be a string") + + if start is not None and not isinstance(start, str): + raise TypeError("src/start must be a string") + + if end is not None and not isinstance(end, str): + raise TypeError("dst/end must be a string") + + # 检查必需参数 + if file_id is None and graph_data is None: + raise ValueError("Either file_id or graph_data must be provided") + + if start is None: + raise ValueError("src/start parameter is required") + + if end is None: + raise ValueError("dst/end parameter is required") + + # Get graph content + content = None + if file_id is not None: + # 尝试从 VFS 获取(如果存在) + if hasattr(self, 'vfs') and file_id in self.vfs: + content = self.vfs[file_id] + else: + # VFS 不存在或文件不在 VFS 中 + # 返回一个默认的空图结果,或者抛出错误提示需要 init_outputs + raise ValueError( + f"File '{file_id}' not found. For tools that require files, " + f"please provide init_outputs in the initial_values." + ) + elif graph_data is not None: + content = graph_data + + if content is None: + content = "{}" + + try: + # Parse graph data + graph = json.loads(content) + + # 类型检查 + if not isinstance(graph, dict): + raise TypeError("Graph data must be a dictionary") + + # If graph is not in the expected format, try to extract adjacency list + if "nodes" in graph and "edges" in graph: + # 验证nodes和edges的类型 + if not isinstance(graph["nodes"], list): + raise TypeError("Nodes must be a list") + + if not isinstance(graph["edges"], list): + raise TypeError("Edges must be a list") + + # Convert from nodes/edges format to adjacency list + adjacency_list = {} + for node in graph["nodes"]: + # 验证node类型 + if not isinstance(node, dict): + raise TypeError("Each node must be a dictionary") + + # Use node ID as key, not the entire node dictionary + node_id = node.get("id", "") + if node_id: + adjacency_list[node_id] = {} + + for edge in graph["edges"]: + # 验证edge类型 + if not isinstance(edge, dict): + raise TypeError("Each edge must be a dictionary") + + u = edge["from"] + v = edge["to"] + weight = edge.get("weight", 1) # Default to unweighted + + # 类型检查 + if not isinstance(u, str): + raise TypeError("Edge 'from' must be a string") + + if not isinstance(v, str): + raise TypeError("Edge 'to' must be a string") + + if not isinstance(weight, (int, float)): + raise TypeError("Edge weight must be a number") + + if u not in adjacency_list: + adjacency_list[u] = {} + if v not in adjacency_list: + adjacency_list[v] = {} + + adjacency_list[u][v] = weight + # If undirected, add reverse edge + if not edge.get("directed", False): + adjacency_list[v][u] = weight + elif isinstance(graph, dict): + # Already in adjacency list format + adjacency_list = graph + + # 验证邻接表结构 + for node, neighbors in adjacency_list.items(): + if not isinstance(neighbors, dict): + raise TypeError("Adjacency list must be a dictionary of dictionaries") + + for neighbor, weight in neighbors.items(): + if not isinstance(weight, (int, float)): + raise TypeError("Edge weights must be numbers") + else: + raise TypeError("Graph data must be a dictionary") + + # 检查起点和终点是否为空 + if not start: + raise ValueError("Start node cannot be empty") + + if not end: + raise ValueError("End node cannot be empty") + + # 检查起点和终点是否在图中 + if start not in adjacency_list: + raise ValueError(f"Start node '{start}' not found in graph") + + if end not in adjacency_list: + raise ValueError(f"End node '{end}' not found in graph") + + # Dijkstra's algorithm implementation + import heapq + + # Initialize distances and previous nodes + distances = {node: float('infinity') for node in adjacency_list} + previous = {node: None for node in adjacency_list} + distances[start] = 0 + + # Priority queue + pq = [(0, start)] + heapq.heapify(pq) + + while pq: + current_dist, current_node = heapq.heappop(pq) + + # If we've reached the end node, we can break early + if current_node == end: + break + + # Nodes can be added multiple times to the priority queue, but we only process them once + if current_dist > distances[current_node]: + continue + + # Explore neighbors + for neighbor, weight in adjacency_list[current_node].items(): + distance = current_dist + weight + + # If a shorter path is found + if distance < distances[neighbor]: + distances[neighbor] = distance + previous[neighbor] = current_node + heapq.heappush(pq, (distance, neighbor)) + + # Reconstruct the shortest path + path = [] + current = end + while current is not None: + path.append(current) + current = previous[current] + path.reverse() # Reverse to get from start to end + + # Check if path exists + if not path or path[0] != start: + return {"path": "[]", "cost": 0} + + return { + "path": json.dumps(path), + "cost": distances[end] + } + except json.JSONDecodeError as e: + raise ValueError(f"Invalid JSON in graph data: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in graph_shortest_path: {str(e)}") + + # --- Crypto (Simplified) --- + def crypto_aes_cbc_decrypt(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 (使用模板中定义的参数名) + hex_cipher = inputs.get("hex_cipher") + hex_key = inputs.get("hex_key") + hex_iv = inputs.get("hex_iv") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + + if hex_key is not None and not isinstance(hex_key, str): + raise TypeError("hex_key must be a string") + + if hex_iv is not None and not isinstance(hex_iv, str): + raise TypeError("hex_iv must be a string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + + if hex_key is None: + raise ValueError("hex_key parameter is required") + + if hex_iv is None: + raise ValueError("hex_iv parameter is required") + + from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes + from cryptography.hazmat.backends import default_backend + from cryptography.hazmat.primitives import padding + + try: + # Convert hex strings to bytes + ciphertext = bytes.fromhex(hex_cipher) + key = bytes.fromhex(hex_key) + iv = bytes.fromhex(hex_iv) + + # Validate key length (AES-128, AES-192, AES-256) + if len(key) not in [16, 24, 32]: + raise ValueError("Invalid key length. Must be 16, 24, or 32 bytes.") + + if len(iv) != 16: + raise ValueError("Invalid IV length. Must be 16 bytes.") + + # Create cipher object + cipher = Cipher( + algorithms.AES(key), + modes.CBC(iv), + backend=default_backend() + ) + + decryptor = cipher.decryptor() + + # Decrypt the ciphertext + padded_plaintext = decryptor.update(ciphertext) + decryptor.finalize() + + # Remove PKCS7 padding + unpadder = padding.PKCS7(128).unpadder() + plaintext = unpadder.update(padded_plaintext) + unpadder.finalize() + + # Return decrypted text + return {"text": plaintext.decode('utf-8', errors='ignore')} + except ValueError as e: + if "non-hexadecimal number found in fromhex()" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher, hex_key, or hex_iv") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in crypto_aes_cbc_decrypt: {str(e)}") + + def crypto_rsa_decrypt_hex(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_cipher = inputs.get("hex_cipher") + n = inputs.get("n") + d = inputs.get("d") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + if n is not None and not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + if d is not None and not isinstance(d, (int, str)): + raise TypeError("d must be an integer or string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + if n is None: + raise ValueError("n parameter is required") + if d is None: + raise ValueError("d parameter is required") + + try: + # Convert parameters to appropriate types + cipher_int = int(hex_cipher, 16) + n_int = int(n) if isinstance(n, str) else n + d_int = int(d) if isinstance(d, str) else d + + # RSA decryption: plaintext = ciphertext^d mod n + plaintext_int = pow(cipher_int, d_int, n_int) + + # Convert result to hex and then to text + plaintext_hex = hex(plaintext_int)[2:] + + # Pad with leading zero if odd length + if len(plaintext_hex) % 2 != 0: + plaintext_hex = '0' + plaintext_hex + + # Convert hex to bytes and then to text + try: + plaintext_bytes = bytes.fromhex(plaintext_hex) + plaintext_text = plaintext_bytes.decode('utf-8', errors='ignore') + except: + # If decoding fails, return hex representation + plaintext_text = plaintext_hex + + return {"text": plaintext_text} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in crypto_rsa_decrypt_hex: {str(e)}") + + # --- Others --- + def num_base_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + s = inputs.get("s") + from_base = inputs.get("from_base") + to_base = inputs.get("to_base") + + # 类型检查 - 接受 str 或 int + if s is not None and not isinstance(s, (str, int)): + raise TypeError("s must be a string or integer") + + if from_base is not None and not isinstance(from_base, (int, str)): + raise TypeError("from_base must be an integer") + + if to_base is not None and not isinstance(to_base, (int, str)): + raise TypeError("to_base must be an integer") + + # 检查必需参数 + if s is None: + raise ValueError("s parameter is required") + + if from_base is None: + raise ValueError("from_base parameter is required") + + if to_base is None: + raise ValueError("to_base parameter is required") + + try: + # Convert to int if needed + from_base = int(from_base) if isinstance(from_base, str) else from_base + to_base = int(to_base) if isinstance(to_base, str) else to_base + s_str = str(s) + + # 验证基数范围 + if from_base < 2 or from_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + if to_base < 2 or to_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + # Convert from source base to decimal + val = int(s_str, from_base) + + # Convert from decimal to target base + if to_base == 10: + result = str(val) + elif to_base == 16: + result = hex(val)[2:] + elif to_base == 8: + result = oct(val)[2:] + elif to_base == 2: + result = bin(val)[2:] + else: + # Generic base conversion for other bases + if val == 0: + result = "0" + else: + digits = "0123456789abcdefghijklmnopqrstuvwxyz" + result = "" + n = abs(val) + while n: + result = digits[n % to_base] + result + n //= to_base + if val < 0: + result = "-" + result + + return {"str": result} + except ValueError as e: + raise ValueError(f"Invalid number format: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in num_base_convert: {str(e)}") + + def time_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iso = inputs.get("iso") + timestamp = inputs.get("timestamp") + datetime_str = inputs.get("datetime") + from_tz = inputs.get("from_tz") + to_tz = inputs.get("to_tz") + format_str = inputs.get("format") + + # 类型检查 + if iso is not None and not isinstance(iso, str): + raise TypeError("iso must be a string") + + if timestamp is not None and not isinstance(timestamp, (str, int, float)): + raise TypeError("timestamp must be a string, integer, or float") + + if datetime_str is not None and not isinstance(datetime_str, str): + raise TypeError("datetime must be a string") + + if from_tz is not None and not isinstance(from_tz, str): + raise TypeError("from_tz must be a string") + + if to_tz is not None and not isinstance(to_tz, str): + raise TypeError("to_tz must be a string") + + if format_str is not None and not isinstance(format_str, str): + raise TypeError("format must be a string") + + # 设置默认值 + if from_tz is None: + from_tz = "UTC" + + if to_tz is None: + to_tz = "UTC" + + import datetime + import pytz + + # 验证时区参数 + try: + if from_tz: + pytz.timezone(from_tz) + if to_tz: + pytz.timezone(to_tz) + except Exception: + raise ValueError("Invalid timezone provided") + + try: + # Parse input time + dt = None + + if iso is not None: + # Parse ISO 8601 format + dt = datetime.datetime.fromisoformat(iso.replace('Z', '+00:00')) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=pytz.UTC) + elif timestamp is not None: + # Parse Unix timestamp + timestamp = float(timestamp) + dt = datetime.datetime.fromtimestamp(timestamp, pytz.UTC) + elif datetime_str is not None: + # Parse datetime string + # Try common formats + formats_to_try = [ + "%Y-%m-%d %H:%M:%S", + "%Y-%m-%d %H:%M:%S.%f", + "%Y-%m-%d", + "%m/%d/%Y %H:%M:%S", + "%m/%d/%Y" + ] + + parse_success = False + for fmt in formats_to_try: + try: + dt = datetime.datetime.strptime(datetime_str, fmt) + dt = pytz.timezone(from_tz).localize(dt) + parse_success = True + break + except ValueError: + continue + + if not parse_success: + raise ValueError("Unable to parse datetime string with common formats") + else: + # 如果没有提供任何时间参数,则使用当前时间 + dt = datetime.datetime.now(pytz.UTC) + except ValueError as e: + raise ValueError(f"Error parsing time input: {str(e)}") + except Exception as e: + raise RuntimeError(f"Unexpected error parsing time input: {str(e)}") + + try: + # Convert timezone + if from_tz != to_tz: + dt = dt.astimezone(pytz.timezone(to_tz)) + + # Format outputs + result = { + "iso": dt.isoformat(), + "timestamp": str(dt.timestamp()), + "datetime": dt.strftime("%Y-%m-%d %H:%M:%S"), + "date": dt.strftime("%Y-%m-%d"), + "time": dt.strftime("%H:%M:%S"), + "timezone": to_tz + } + + # Add custom format if requested + if format_str: + try: + result["formatted"] = dt.strftime(format_str) + except ValueError as e: + raise ValueError(f"Invalid format string: {str(e)}") + + return result + except Exception as e: + raise RuntimeError(f"Error in time_convert: {str(e)}") + + def checksum_crc32(self, inputs): + import zlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("hex must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("hex parameter is required") + + try: + # 验证十六进制字符串 + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空 + if not hex_data: + raise ValueError("hex data cannot be empty") + + # 检查是否为有效的十六进制字符串 + if not all(c in "0123456789abcdefABCDEF" for c in hex_data): + raise ValueError("hex must be a valid hexadecimal string") + + # 检查长度是否为偶数 + if len(hex_data) % 2 != 0: + raise ValueError("hex must have even number of characters") + + val = zlib.crc32(bytes.fromhex(hex_data)) + # 确保 hex 输出是 8 位,前导补 0 + return {"hex": f"{val:08x}", "int": val} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in checksum_crc32: {str(e)}") + + def geo_haversine(self, inputs): + import math + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + lat1 = inputs.get("lat1") + lon1 = inputs.get("lon1") + lat2 = inputs.get("lat2") + lon2 = inputs.get("lon2") + + # 类型检查 + if lat1 is not None and not isinstance(lat1, (int, float, str)): + raise TypeError("lat1 must be a number or string") + if lon1 is not None and not isinstance(lon1, (int, float, str)): + raise TypeError("lon1 must be a number or string") + if lat2 is not None and not isinstance(lat2, (int, float, str)): + raise TypeError("lat2 must be a number or string") + if lon2 is not None and not isinstance(lon2, (int, float, str)): + raise TypeError("lon2 must be a number or string") + + # 检查必需参数 + if lat1 is None: + raise ValueError("lat1 parameter is required") + if lon1 is None: + raise ValueError("lon1 parameter is required") + if lat2 is None: + raise ValueError("lat2 parameter is required") + if lon2 is None: + raise ValueError("lon2 parameter is required") + + try: + # 转换为浮点数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(lat1, str): + lat1 = float(lat1) + elif not isinstance(lat1, (int, float)): + raise TypeError("lat1 must be a number or string") + else: + lat1 = float(lat1) + + if isinstance(lon1, str): + lon1 = float(lon1) + elif not isinstance(lon1, (int, float)): + raise TypeError("lon1 must be a number or string") + else: + lon1 = float(lon1) + + if isinstance(lat2, str): + lat2 = float(lat2) + elif not isinstance(lat2, (int, float)): + raise TypeError("lat2 must be a number or string") + else: + lat2 = float(lat2) + + if isinstance(lon2, str): + lon2 = float(lon2) + elif not isinstance(lon2, (int, float)): + raise TypeError("lon2 must be a number or string") + else: + lon2 = float(lon2) + + # Validate coordinates (approximate range check) + if not (-90 <= lat1 <= 90): + raise ValueError("lat1 must be between -90 and 90") + if not (-90 <= lat2 <= 90): + raise ValueError("lat2 must be between -90 and 90") + if not (-180 <= lon1 <= 180): + raise ValueError("lon1 must be between -180 and 180") + if not (-180 <= lon2 <= 180): + raise ValueError("lon2 must be between -180 and 180") + + # Earth radius in meters + R = 6371000 # Approximate radius of Earth + + # Convert degrees to radians + lat1_rad = math.radians(lat1) + lon1_rad = math.radians(lon1) + lat2_rad = math.radians(lat2) + lon2_rad = math.radians(lon2) + + # Calculate differences + delta_lat = lat2_rad - lat1_rad + delta_lon = lon2_rad - lon1_rad + + # Haversine formula + a = math.sin(delta_lat / 2) ** 2 + \ + math.cos(lat1_rad) * math.cos(lat2_rad) * \ + math.sin(delta_lon / 2) ** 2 + c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) + distance_m = R * c + + # Return distance in meters + return {"meters": round(distance_m, 2)} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in geo_haversine: {str(e)}") + + def otp_totp_generate(self, inputs): + import hmac + import hashlib + import base64 + import time + import struct + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + base32_secret = inputs.get("base32_secret") + step = inputs.get("step", 30) # Default to 30 seconds + digits = inputs.get("digits", 6) # Default to 6 digits + timestamp_iso = inputs.get("timestamp_iso", "") + algo = inputs.get("algo", "sha1") # Default to sha1 as current implementation only supports this + + # 类型检查 + if base32_secret is not None and not isinstance(base32_secret, str): + raise TypeError("base32_secret must be a string") + if not isinstance(step, (int, str)): + raise TypeError("step must be an integer or string") + if not isinstance(digits, (int, str)): + raise TypeError("digits must be an integer or string") + if not isinstance(timestamp_iso, str): + raise TypeError("timestamp_iso must be a string") + if not isinstance(algo, str): + raise TypeError("algo must be a string") + + # 检查必需参数 + if base32_secret is None: + raise ValueError("base32_secret parameter is required") + + try: + # Convert step and digits to appropriate types + step = int(step) + digits = int(digits) + if digits < 6 or digits > 8: + raise ValueError("Digits must be between 6 and 8") + + # Convert timestamp_iso to integer timestamp + if timestamp_iso: + import datetime + dt = datetime.datetime.fromisoformat(timestamp_iso.replace('Z', '+00:00')) + timestamp = int(dt.timestamp()) + else: + timestamp = int(time.time()) + + # Calculate counter value (T = floor(timestamp / step)) + counter = timestamp // step + + # Decode the base32 secret + # Add padding if necessary (base64 requires padding to be multiple of 8) + base32_secret = base32_secret.upper().replace(' ', '') + if len(base32_secret) % 8 != 0: + base32_secret += '=' * (8 - (len(base32_secret) % 8)) + key = base64.b32decode(base32_secret, casefold=True) + + # Calculate HMAC-SHA1 + counter_bytes = struct.pack('>Q', counter) # Big-endian 8-byte integer + hmac_hash = hmac.new(key, counter_bytes, hashlib.sha1).digest() + + # Dynamic truncation + offset = hmac_hash[-1] & 0xF + code = struct.unpack('>I', hmac_hash[offset:offset+4])[0] & 0x7FFFFFFF + + # Generate the OTP + otp = str(code % (10 ** digits)).zfill(digits) + + # Calculate remaining time until next OTP change + remaining_time = step - (timestamp % step) + + return {"totp": otp, "remaining_time": remaining_time, "time_step": step} + except ValueError as e: + if "invalid literal for int()" in str(e): + raise ValueError("step and digits must be valid integers") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in otp_totp_generate: {str(e)}") + + def unicode_norm(self, inputs): + import unicodedata + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + form = inputs.get("form", "NFC") # Default to NFC + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if form is not None and not isinstance(form, str): + raise TypeError("form must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Normalize form (NFC, NFD, NFKC, NFKD) + form = form.upper().strip() + + if form not in ['NFC', 'NFD', 'NFKC', 'NFKD']: + raise ValueError(f"Invalid normalization form: {form}. Must be one of: NFC, NFD, NFKC, NFKD") + + # Apply Unicode normalization + normalized_text = unicodedata.normalize(form, text) + + return {"text": normalized_text} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in unicode_norm: {str(e)}") + + def text_bidi_sanitize(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Bidi control characters to remove + bidi_controls = [ + '\u200E', # LEFT-TO-RIGHT MARK + '\u200F', # RIGHT-TO-LEFT MARK + '\u202A', # LEFT-TO-RIGHT EMBEDDING + '\u202B', # RIGHT-TO-LEFT EMBEDDING + '\u202C', # POP DIRECTIONAL FORMATTING + '\u202D', # LEFT-TO-RIGHT OVERRIDE + '\u202E', # RIGHT-TO-LEFT OVERRIDE + '\u2066', # LEFT-TO-RIGHT ISOLATE + '\u2067', # RIGHT-TO-LEFT ISOLATE + '\u2068', # FIRST STRONG ISOLATE + '\u2069', # POP DIRECTIONAL ISOLATE + ] + + # Remove all Bidi control characters + sanitized_text = text + for control_char in bidi_controls: + sanitized_text = sanitized_text.replace(control_char, '') + + return {"text": sanitized_text} + except Exception as e: + raise RuntimeError(f"Error in text_bidi_sanitize: {str(e)}") + + def text_xor_hex(self, inputs): + import binascii + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_a = inputs.get("hex_a") + hex_b = inputs.get("hex_b") + + # 类型检查 + if hex_a is not None and not isinstance(hex_a, str): + raise TypeError("hex_a must be a string") + if hex_b is not None and not isinstance(hex_b, str): + raise TypeError("hex_b must be a string") + + # 检查必需参数 + if hex_a is None: + raise ValueError("hex_a parameter is required") + if hex_b is None: + raise ValueError("hex_b parameter is required") + + try: + # Remove any whitespace + hex_a = hex_a.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + hex_b = hex_b.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + + # Validate hex strings + if not (all(c in "0123456789abcdefABCDEF" for c in hex_a) and len(hex_a) % 2 == 0): + raise ValueError("hex_a must be a valid hexadecimal string with even length") + if not (all(c in "0123456789abcdefABCDEF" for c in hex_b) and len(hex_b) % 2 == 0): + raise ValueError("hex_b must be a valid hexadecimal string with even length") + + # Convert hex strings to bytes + bytes_a = binascii.unhexlify(hex_a) + bytes_b = binascii.unhexlify(hex_b) + + # Make the byte arrays the same length by padding the shorter one with zeros + max_len = max(len(bytes_a), len(bytes_b)) + bytes_a = bytes_a.ljust(max_len, b'\x00') + bytes_b = bytes_b.ljust(max_len, b'\x00') + + # Perform XOR operation + result_bytes = bytes(a ^ b for a, b in zip(bytes_a, bytes_b)) + + # Convert result back to hex + result_hex = binascii.hexlify(result_bytes).decode('utf-8') + + return {"hex": result_hex} + except ValueError as e: + if "Non-hexadecimal digit found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in text_xor_hex: {str(e)}") + + def text_rotN(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + n = inputs.get("n", 0) + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + n = int(n) + except ValueError: + raise ValueError("n must be a valid integer") + + result = [] + for char in text: + if char.isupper(): + # Rotate uppercase letters + result_char = chr((ord(char) - ord('A') + n) % 26 + ord('A')) + result.append(result_char) + elif char.islower(): + # Rotate lowercase letters + result_char = chr((ord(char) - ord('a') + n) % 26 + ord('a')) + result.append(result_char) + else: + # Keep non-alphabetic characters unchanged + result.append(char) + + return {"text": ''.join(result)} + + def luhn_check(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数(支持 card_number 和 number 两个参数名) + card_number = inputs.get("number") or inputs.get("card_number") + + # 类型检查 + if card_number is not None and not isinstance(card_number, str): + raise TypeError("number must be a string") + + # 检查必需参数 + if card_number is None: + raise ValueError("number parameter is required") + + try: + # 如果输入是JSON数组或其他非数字字符串,返回该字符串本身(用于数据传递) + # 这种情况发生在DAG设计中类型不匹配时 + if card_number.startswith('[') or card_number.startswith('{'): + # 输入是JSON,直接返回原值(用于传递) + return {"valid": card_number} + + # Remove whitespace from card number + card_number = card_number.replace(" ", "").replace("-", "") + + # Check if card number is all digits + if not card_number.isdigit() or len(card_number) < 13: + return {"valid": "false"} + + # Implement Luhn algorithm + total = 0 + reverse_digits = card_number[::-1] # Reverse the number for easier processing + + for i, digit in enumerate(reverse_digits): + num = int(digit) + if i % 2 == 1: # Every second digit starting from the right (which is first in reversed string) + num *= 2 + if num > 9: + num -= 9 # Equivalent to sum of digits for 2-digit numbers + total += num + + # Check if total is divisible by 10 + is_valid = total % 10 == 0 + return {"valid": "true" if is_valid else "false"} + except Exception as e: + raise RuntimeError(f"Error in luhn_check: {str(e)}") + + def iban_validate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iban = inputs.get("iban") + + # 类型检查 + if iban is not None and not isinstance(iban, str): + raise TypeError("iban must be a string") + + # 检查必需参数 + if iban is None: + raise ValueError("iban parameter is required") + + try: + # Remove whitespace from IBAN + iban = iban.replace(" ", "") + + # Basic length and format check + if not (len(iban) >= 15 and len(iban) <= 34): + return {"valid": "False"} + + if not (iban[:2].isalpha() and iban[2:].isdigit()): + return {"valid": "False"} + + # Move first four characters to the end + rearranged = iban[4:] + iban[:4] + + # Replace letters with numbers (A=10, B=11, ..., Z=35) + numeric_iban = '' + for char in rearranged: + if char.isdigit(): + numeric_iban += char + else: + numeric_iban += str(ord(char.upper()) - ord('A') + 10) + + # Perform modulo 97 check + # Use step-by-step approach for very large numbers + remainder = 0 + for char in numeric_iban: + remainder = (remainder * 10 + int(char)) % 97 + + is_valid = remainder == 1 + return {"valid": "True" if is_valid else "False"} + except Exception as e: + raise RuntimeError(f"Error in iban_validate: {str(e)}") + + def matter_synthesizer(self, inputs): + import hashlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + blueprint = inputs.get("blueprint") + + # 类型检查 + if blueprint is not None and not isinstance(blueprint, str): + raise TypeError("blueprint must be a string") + + try: + # Get blueprint parameter as defined in interface + if blueprint is None: + blueprint = "" + + # Generate a unique item ID based on the blueprint + # This ensures the same blueprint always produces the same item + blueprint_hash = hashlib.sha256(blueprint.encode()).hexdigest()[:16] + + # Create a synthesized item with a deterministic ID based on blueprint + synthesized_item = f"synthesized_item_{blueprint_hash}" + + return {"output_slot": synthesized_item} + except Exception as e: + raise RuntimeError(f"Error in matter_synthesizer: {str(e)}") + + # --- Terminal Implementations --- + def terminal_1(self, inputs): + """ + terminal_1: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 只返回 text_output + - 只输入正确的 slot_b → 只返回 hex_output + - 同时输入正确的 slot_a 和 slot_b → 返回 item_dispenser(物品掉落) + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + # 检查哪些输入被提供了 + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值是否正确(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + expected_a = golden_inputs["slot_a"] + a_valid = str(slot_a) == str(expected_a) + + if has_b and "slot_b" in golden_inputs: + expected_b = golden_inputs["slot_b"] + b_valid = str(slot_b) == str(expected_b) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 item_dispenser + if has_a and has_b: + if a_valid and b_valid: + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 text_output + if has_a and not has_b: + if a_valid: + if "text_output" in golden_outputs: + result["text_output"] = golden_outputs["text_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 hex_output + if has_b and not has_a: + if b_valid: + if "hex_output" in golden_outputs: + result["hex_output"] = golden_outputs["hex_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def terminal_2(self, inputs): + """ + terminal_2: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 text_result + - 同时输入正确的 num1 和 num2 → 返回 hex_result 和 math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + # 检查哪些输入被提供了 + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值是否正确(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + expected_num1 = golden_inputs["num1"] + num1_valid = str(num1) == str(expected_num1) + + if has_num2 and "num2" in golden_inputs: + expected_num2 = golden_inputs["num2"] + num2_valid = str(num2) == str(expected_num2) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 hex_result 和 math_token + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 text_result + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "text_result" in golden_outputs: + result["text_result"] = golden_outputs["text_result"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def logic_terminal(self, inputs): + """ + Logic Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 返回 screen(部分输出) + - 只输入正确的 slot_b → 返回 screen 和 secondary_output + - 同时输入正确的 slot_a 和 slot_b → 返回 screen, secondary_output, item_dispenser + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + a_valid = str(slot_a) == str(golden_inputs["slot_a"]) + + if has_b and "slot_b" in golden_inputs: + b_valid = str(slot_b) == str(golden_inputs["slot_b"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出(包括 item_dispenser) + if has_a and has_b: + if a_valid and b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 screen(部分输出) + if has_a and not has_b: + if a_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 screen 和 secondary_output + if has_b and not has_a: + if b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def math_terminal(self, inputs): + """ + Math Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 result_display + - 同时输入正确的 num1 和 num2 → 返回 result_display, hex_result, math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + num1_valid = str(num1) == str(golden_inputs["num1"]) + + if has_num2 and "num2" in golden_inputs: + num2_valid = str(num2) == str(golden_inputs["num2"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 result_display + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def crypt_terminal(self, inputs): + """ + Encryption Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 plaintext → 返回 status(部分输出) + - 同时输入正确的 plaintext 和 key → 返回 status, encrypted_hex, encryption_chip + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + plaintext = inputs.get("plaintext") + key = inputs.get("key") + + has_plaintext = plaintext is not None and plaintext != "" + has_key = key is not None and key != "" + + # 验证输入值(与 golden values 比较) + plaintext_valid = False + key_valid = False + + if has_plaintext and "plaintext" in golden_inputs: + plaintext_valid = str(plaintext) == str(golden_inputs["plaintext"]) + + if has_key and "key" in golden_inputs: + key_valid = str(key) == str(golden_inputs["key"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_plaintext and has_key: + if plaintext_valid and key_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + if "encrypted_hex" in golden_outputs: + result["encrypted_hex"] = golden_outputs["encrypted_hex"] + if "encryption_chip" in golden_outputs: + result["encryption_chip"] = golden_outputs["encryption_chip"] + return result + else: + incorrect_params = [] + correct_params = [] + if not plaintext_valid: + incorrect_params.append("plaintext") + else: + correct_params.append("plaintext") + if not key_valid: + incorrect_params.append("key") + else: + correct_params.append("key") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 plaintext 且正确 → 返回 status(部分输出) + if has_plaintext and not has_key: + if plaintext_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: plaintext"} + + # 只提供 key 但没有 plaintext + if has_key and not has_plaintext: + return {"error": "plaintext required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + def sequence_terminal(self, inputs): + """ + Sequence Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 sequence → 返回 verification(部分输出) + - 同时输入正确的 sequence 和 checksum → 返回 verification, auth_code, access_card + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + sequence = inputs.get("sequence") + checksum = inputs.get("checksum") + + has_sequence = sequence is not None and sequence != "" + has_checksum = checksum is not None and checksum != "" + + # 验证输入值(与 golden values 比较) + sequence_valid = False + checksum_valid = False + + if has_sequence and "sequence" in golden_inputs: + sequence_valid = str(sequence) == str(golden_inputs["sequence"]) + + if has_checksum and "checksum" in golden_inputs: + checksum_valid = str(checksum) == str(golden_inputs["checksum"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_sequence and has_checksum: + if sequence_valid and checksum_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + if "auth_code" in golden_outputs: + result["auth_code"] = golden_outputs["auth_code"] + if "access_card" in golden_outputs: + result["access_card"] = golden_outputs["access_card"] + return result + else: + incorrect_params = [] + correct_params = [] + if not sequence_valid: + incorrect_params.append("sequence") + else: + correct_params.append("sequence") + if not checksum_valid: + incorrect_params.append("checksum") + else: + correct_params.append("checksum") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 sequence 且正确 → 返回 verification(部分输出) + if has_sequence and not has_checksum: + if sequence_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: sequence"} + + # 只提供 checksum 但没有 sequence + if has_checksum and not has_sequence: + return {"error": "sequence required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + # --- Additional File Tools --- + + def zip_unzip_file(self, inputs): + """ZIP 解压文件工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def zip_unzip_item(self, inputs): + """ZIP 解压道具工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def code_py_exec(self, inputs): + """Python 代码执行工具 + + 这是一个真实执行的工具,在 DAG 生成阶段和运行时评测阶段都会执行代码。 + 输入: code (Python 代码字符串) + 输出: stdout (标准输出,包含执行结果和错误信息) + + 特殊行为: + - 如果代码定义了 main() 函数,会自动调用它 + - 如果执行出错,错误信息会包含在 stdout 中 + """ + code = inputs.get("code", "") + + if not code: + return {"stdout": "Error: No code provided"} + + try: + # 创建一个受限的执行环境 + import io + import sys + + # 捕获标准输出和标准错误 + old_stdout = sys.stdout + old_stderr = sys.stderr + sys.stdout = io.StringIO() + sys.stderr = io.StringIO() + + # 执行代码 + exec_globals = {"__builtins__": __builtins__} + exec_locals = {} + exec(code, exec_globals, exec_locals) + + # 如果定义了 main() 函数,自动调用它 + if 'main' in exec_locals and callable(exec_locals['main']): + exec_locals['main']() + + # 获取输出 + stdout_value = sys.stdout.getvalue() + stderr_value = sys.stderr.getvalue() + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 合并 stdout 和 stderr + output = stdout_value + if stderr_value: + output += ("\n" if output else "") + f"[stderr] {stderr_value}" + + # 如果没有任何输出,尝试返回 result 变量的值 + if not output: + result = exec_locals.get("_result") or exec_locals.get("result") + if result is not None: + output = str(result) + + return {"stdout": output if output else "(no output)"} + + except Exception as e: + # 恢复标准输出和错误输出 + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 返回错误信息 + return {"stdout": f"Error: {type(e).__name__}: {str(e)}"} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-93dd5f71/environment/puzzle/worker.Dockerfile b/tasks/agentescape-25-skeleton-93dd5f71/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-25-skeleton-93dd5f71/environment/puzzle/worker.Dockerfile @@ -0,0 +1,8 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends libseccomp2 && rm -rf /var/lib/apt/lists/* +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY worker.py child.py /app/ +COPY upstream/simulator.py /app/simulator.py +CMD ["uvicorn", "worker:app", "--host", "0.0.0.0", "--port", "8001", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-25-skeleton-93dd5f71/environment/puzzle/worker.py b/tasks/agentescape-25-skeleton-93dd5f71/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-25-skeleton-93dd5f71/environment/puzzle/worker.py @@ -0,0 +1,73 @@ +"""Stateless Python tool worker. Never receives a scenario or reference values.""" + +import json +import os +import signal +import subprocess +import sys +import tempfile +import threading + +from fastapi import FastAPI +from pydantic import BaseModel, ConfigDict + +app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) +lock = threading.Lock() + + +class Execution(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + code: str + + +@app.get("/health") +def health(): + return {"ok": True} + + +@app.post("/execute") +def execute(request: Execution): + if len(request.code.encode()) > 65536: + return {"stdout": "Error: code exceeds 64 KiB limit"} + with lock, tempfile.TemporaryDirectory(prefix="escape-code-") as directory: + os.chown(directory, 65534, 65534) + with tempfile.TemporaryFile() as output: + process = subprocess.Popen( + [sys.executable, "-I", "/app/child.py"], + stdin=subprocess.PIPE, + stdout=output, + stderr=subprocess.DEVNULL, + cwd=directory, + user=65534, + group=65534, + extra_groups=[], + start_new_session=True, + env={"PATH": "/usr/local/bin:/usr/bin:/bin"}, + ) + try: + process.communicate( + json.dumps({"code": request.code}).encode(), timeout=5 + ) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + return {"stdout": "Error: Python execution timed out"} + finally: + # Also remove children still in the process group after normal exit. + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + output.seek(0) + value = output.read(65537) + if len(value) > 65536 or process.returncode != 0: + return { + "stdout": "Error: Python execution exceeded a resource limit or failed" + } + try: + result = json.loads(value) + if not isinstance(result.get("stdout"), str): + raise ValueError("Invalid worker response") + return result + except (ValueError, AttributeError): + return {"stdout": "Error: Python execution returned invalid output"} diff --git a/tasks/agentescape-25-skeleton-93dd5f71/instruction.md b/tasks/agentescape-25-skeleton-93dd5f71/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-25-skeleton-93dd5f71/instruction.md @@ -0,0 +1,18 @@ +# Escape the room + +Discover the victory string and submit it with `escape submit-answer`. +Start with `escape observe`. This returns the room, available information, visible entities, and victory node ID. + +Use these commands (JSON responses): + +```sh +escape investigate NODE_ID +escape tool-call NODE_ID --arguments-json '{"parameter": "value"}' +escape use-item NODE_ID --arguments-json '{"parameter": "value"}' +escape submit-answer 'exact victory string' +escape state +``` + +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. + +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. diff --git a/tasks/agentescape-25-skeleton-93dd5f71/solution/oracle.py b/tasks/agentescape-25-skeleton-93dd5f71/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-25-skeleton-93dd5f71/solution/oracle.py @@ -0,0 +1,133 @@ +"""Reference solver: use trusted inputs, but obtain the answer through public actions.""" + +import json +import urllib.request +from pathlib import Path + + +def http_action(base_url, payload): + request = urllib.request.Request( + base_url + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(request, timeout=30) as response: + return json.load(response) + + +def solve(scenario, act, observe): + nodes = {node["id"]: node for node in scenario["nodes"]} + visible = {entity["id"] for entity in observe["available_entities"]} + solved = set() + seen_outputs = {} + action_count = 0 + + def call(payload): + nonlocal action_count + action_count += 1 + response = act(payload) + visible.update(entity["id"] for entity in response.get("newly_revealed", [])) + if ( + response.get("episode", {}).get("termination_reason") + == "infrastructure_error" + ): + raise RuntimeError("Infrastructure failure") + return response + + for _round in range(len(nodes) + 2): + progress = False + for node_id, node in nodes.items(): + if node_id not in visible or node_id in solved: + continue + # Preserve graph order for data inputs; trigger/drop edges express visibility. + predecessors = [ + edge["source_id"] + for edge in scenario["edges"] + if edge["target_id"] == node_id + and edge["connection_type"] not in ("Item", "Hidden_Item") + ] + if any(pred not in solved for pred in predecessors): + continue + info = call({"action": "investigate", "node_id": node_id}) + if not info.get("ok"): + raise RuntimeError(f"Investigation failed: {node_id}: {info}") + inputs = { + port["name"]: port["value"] + for port in node.get("inputs", []) + if "value" in port + } + if node["type"] == "Tool": + result = call( + {"action": "tool_call", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok") or result.get("output_values", {}).get("error"): + raise RuntimeError(f"Tool failed: {node_id}: {result}") + output = result.get("output_values", {}) + if node.get("template_id") in ("terminal_1", "terminal_2"): + slots = { + port["name"]: inputs[port["name"]] + for port in node["inputs"] + if port["type"] not in ("Item", "Hidden_Item") + and port["name"] in inputs + } + triggers = { + key: value for key, value in inputs.items() if key not in slots + } + for key, value in slots.items(): + partial = call( + { + "action": "tool_call", + "node_id": node_id, + "arguments": {**triggers, key: value}, + } + ) + if partial.get("ok"): + output.update(partial.get("output_values", {})) + # HIDDEN_ITEM tool drops only occur on subsequent investigation. + call({"action": "investigate", "node_id": node_id}) + elif info.get("required_inputs"): + result = call( + {"action": "use_item", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok"): + raise RuntimeError(f"Item failed: {node_id}: {result}") + output = result.get("content") + else: + output = info.get("content") + seen_outputs[node_id] = output + solved.add(node_id) + progress = True + win_id = scenario["metadata"]["win_node_id"] + if win_id in solved and (len(solved) == len(nodes) or not progress): + outputs = seen_outputs[win_id] + if not outputs: + raise RuntimeError(f"Victory node returned no output: {win_id}") + # Upstream grades its first stored output port, independent of response order. + victory_port = next( + port["name"] for port in nodes[win_id]["outputs"] if "value" in port + ) + answer = outputs[victory_port] if isinstance(outputs, dict) else outputs + result = call({"action": "submit_answer", "answer": answer}) + if not result.get("is_win"): + raise RuntimeError(f"Victory submission failed: {result}") + return {"won": True, "actions": action_count, "visited_nodes": len(solved)} + if not progress: + raise RuntimeError(f"No progress: visible={visible}, solved={solved}") + raise RuntimeError("Reference solver exceeded graph traversal limit") + + +if __name__ == "__main__": + import os + + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000") + with urllib.request.urlopen(base + "/observation", timeout=20) as response: + observation = json.load(response) + print( + json.dumps( + solve( + json.loads(Path("/solution/scenario.json").read_text()), + lambda payload: http_action(base, payload), + observation, + ) + ) + ) diff --git a/tasks/agentescape-25-skeleton-93dd5f71/solution/scenario.json b/tasks/agentescape-25-skeleton-93dd5f71/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..1ad967a263c10a346f233a68636287e9d6df1ef0 --- /dev/null +++ b/tasks/agentescape-25-skeleton-93dd5f71/solution/scenario.json @@ -0,0 +1,1537 @@ +{ + "metadata": { + "total_nodes": 25, + "total_edges": 28, + "win_node_id": "item_15", + "win_condition": { + "type": "item_content", + "node_id": "item_15", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_15", + "terminal_1", + "calc_modexp", + "crypto_rsa_decrypt_hex", + "calc_modexp_490b", + "calc_gcd", + "num_base_convert", + "calc_inv_mod", + "container_3", + "calc_bigmul_cce0", + "regex_search", + "unicode_norm", + "container_3_c334", + "terminal_1_c1ab", + "item_10", + "item_10_7483", + "item_9", + "calc_gcd_737b" + ], + "by_node": { + "item_15": { + "node_name": "", + "node_type": "Item", + "template_id": "item_15", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Text_Generic", + "description": "Timezone text" + } + } + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": {}, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + } + } + }, + "calc_modexp": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "exp": { + "type": "Big_Int", + "description": "Exponent" + } + }, + "init_outputs": {} + }, + "crypto_rsa_decrypt_hex": { + "node_name": "RSA Decrypt", + "node_type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "init_inputs": { + "hex_cipher": { + "type": "Hex_String", + "description": "Ciphertext (Hex)" + } + }, + "init_outputs": {} + }, + "calc_modexp_490b": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "exp": { + "type": "Big_Int", + "description": "Exponent" + }, + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "calc_gcd": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First integer" + } + }, + "init_outputs": {} + }, + "num_base_convert": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "from_base": { + "type": "Big_Int", + "description": "From base" + }, + "to_base": { + "type": "Big_Int", + "description": "To base" + } + }, + "init_outputs": {} + }, + "calc_inv_mod": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "container_3": { + "node_name": "", + "node_type": "Item", + "template_id": "container_3", + "init_inputs": { + "fingerprint_input": { + "type": "Big_Int", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + }, + "calc_bigmul_cce0": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First large integer" + } + }, + "init_outputs": {} + }, + "regex_search": { + "node_name": "Regex Search", + "node_type": "Tool", + "template_id": "regex_search", + "init_inputs": { + "pattern": { + "type": "Text_Generic", + "description": "Regex pattern" + }, + "file_id": { + "type": "File_Id", + "description": "File ID (optional)" + } + }, + "init_outputs": { + "matches": { + "type": "Text_Generic", + "description": "Found matches (List)" + } + } + }, + "unicode_norm": { + "node_name": "Unicode Normalizer", + "node_type": "Tool", + "template_id": "unicode_norm", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text" + } + }, + "init_outputs": {} + }, + "container_3_c334": { + "node_name": "", + "node_type": "Item", + "template_id": "container_3", + "init_inputs": { + "fingerprint_input": { + "type": "Big_Int", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + }, + "terminal_1_c1ab": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": { + "slot_a": { + "type": "Text_Generic", + "description": "Input Slot A" + } + }, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + } + } + }, + "item_10": { + "node_name": "", + "node_type": "Item", + "template_id": "item_10", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Big_Int", + "description": "The number" + } + } + }, + "item_10_7483": { + "node_name": "", + "node_type": "Item", + "template_id": "item_10", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Big_Int", + "description": "The number" + } + } + }, + "item_9": { + "node_name": "", + "node_type": "Item", + "template_id": "item_9", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "File_Id", + "description": "JSON file path" + } + } + }, + "calc_gcd_737b": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First integer" + }, + "b": { + "type": "Big_Int", + "description": "Second integer" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "item_15": { + "init_inputs": {}, + "init_outputs": { + "content": "America/New_York" + } + }, + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "Welcome to the central terminal system.", + "hex_output": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "calc_modexp": { + "init_inputs": { + "exp": "74859385739204958674" + }, + "init_outputs": {} + }, + "crypto_rsa_decrypt_hex": { + "init_inputs": { + "hex_cipher": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + }, + "init_outputs": {} + }, + "calc_modexp_490b": { + "init_inputs": { + "exp": "34958672019485768392", + "mod": "999983" + }, + "init_outputs": {} + }, + "calc_gcd": { + "init_inputs": { + "a": "10293847563049586721" + }, + "init_outputs": {} + }, + "num_base_convert": { + "init_inputs": { + "from_base": "16", + "to_base": "10" + }, + "init_outputs": {} + }, + "calc_inv_mod": { + "init_inputs": { + "mod": "100003" + }, + "init_outputs": {} + }, + "container_3": { + "init_inputs": { + "fingerprint_input": "85960483928475630495" + }, + "init_outputs": {} + }, + "calc_bigmul_cce0": { + "init_inputs": { + "a": "94857639204857683921" + }, + "init_outputs": {} + }, + "regex_search": { + "init_inputs": { + "pattern": "\\d{16}", + "file_id": "data_scan.txt" + }, + "init_outputs": { + "matches": "[\"1234567812345678\", \"8765432187654321\", \"1111222233334444\"]" + } + }, + "unicode_norm": { + "init_inputs": { + "text": "Ä string to be normalized" + }, + "init_outputs": {} + }, + "container_3_c334": { + "init_inputs": { + "fingerprint_input": "75849302918274635241" + }, + "init_outputs": {} + }, + "terminal_1_c1ab": { + "init_inputs": { + "slot_a": "Input message for terminal A" + }, + "init_outputs": { + "text_output": "NFC", + "hex_output": "f1e2d3c4b5a697887766554433221100" + } + }, + "item_10": { + "init_inputs": {}, + "init_outputs": { + "content": "48573920495867382910" + } + }, + "item_10_7483": { + "init_inputs": {}, + "init_outputs": { + "content": "57483920192837465012" + } + }, + "item_9": { + "init_inputs": {}, + "init_outputs": { + "content": "metadata.json" + } + }, + "calc_gcd_737b": { + "init_inputs": { + "a": "83920485768392019283", + "b": "28374659302918273645" + }, + "init_outputs": {} + } + }, + "intro_narrative": "Welcome to Sector 7, the digital underbelly of the Neon Syndicate. The corporate overlords have locked down the main network, trapping vital information behind layers of biometric firewalls and quantum encryption algorithms. You are a rogue netrunner, and you've managed to slip into this abandoned corporate server room undetected. However, the system's automated purge protocols have been activated, and time is rapidly running out. Your objective is clear: navigate this maze of disconnected hardware, reactivate the dormant digital nodes, and bypass their intricate security measures. The syndicate relies on a complex web of mathematical ciphers and hidden cryptographic keys scattered throughout the room. By carefully linking these devices, you must systematically dismantle their defenses. Your ultimate goal is to breach the central mainframe and obtain the core timezone data before the physical servers are fried. Plug in, stay sharp, and don't let the neon lights distract you. The run starts now.", + "narrative_style": "cyberpunk" + }, + "nodes": [ + { + "id": "item_15", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_15", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Text_Generic", + "description": "Timezone text", + "value": "America/New_York" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "America/New_York" + } + }, + "narrative": "This is the Timezone Datapad. A sleek, top-tier corporate tablet meant to display the final uncorrupted timezone data." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "false" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "12096" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Welcome to the central terminal system." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "Welcome to the central terminal system.", + "hex_output": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "narrative": "This is the Mainframe Access Terminal. It requires inputs from both the ID Verification Scanner and the Quantum Encryption Core to authenticate your final entry." + }, + { + "id": "luhn_check", + "name": "Luhn Checker", + "description": "Luhn validity of number string.", + "type": "Tool", + "template_id": "luhn_check", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "number", + "type": "Text_Generic", + "description": "Number string", + "value": "\u000b" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "false" + } + ], + "narrative": "This is the ID Verification Scanner. It requires input from the Cypher Breaker Unit to process and validate your digital credentials." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "This is the Hidden Cache Drive. A small, concealed memory unit." + }, + { + "id": "calc_modexp", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "921072" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "74859385739204958674" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "20304" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "12096" + } + ], + "init": { + "inputs": { + "exp": "74859385739204958674" + }, + "outputs": {} + }, + "narrative": "This is the Quantum Encryption Core. It requires inputs from both the Sub-routine Processor and the Algorithmic Multiplier to stabilize its heavy computations." + }, + { + "id": "crypto_rsa_decrypt_hex", + "name": "RSA Decrypt", + "description": "RSA decrypt (hex cipher) with n,d (decimal).", + "type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "hex_cipher", + "type": "Hex_String", + "description": "Ciphertext (Hex)", + "value": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Modulus n", + "value": "921072" + }, + { + "name": "d", + "type": "Big_Int", + "description": "Private exponent d", + "value": "1" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decrypted text", + "value": "\u000b" + } + ], + "init": { + "inputs": { + "hex_cipher": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + }, + "outputs": {} + }, + "narrative": "This is the Cypher Breaker Unit. It requires inputs from both the Sub-routine Processor and the Network Divisor to shred through military-grade encryption." + }, + { + "id": "calc_modexp_490b", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "399793861475558893217052581389266889886769152272" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "34958672019485768392" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "999983" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "921072" + } + ], + "init": { + "inputs": { + "exp": "34958672019485768392", + "mod": "999983" + }, + "outputs": {} + }, + "narrative": "This is the Sub-routine Processor. It requires input from the Base Translator Module to handle low-level calculations." + }, + { + "id": "calc_bigmul", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "6768" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "3" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "20304" + } + ], + "narrative": "This is the Algorithmic Multiplier. It requires inputs from both the Harmonic Divisor and the Phase Inverter to output its massive digital payload." + }, + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "10293847563049586721" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "921072" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "3" + } + ], + "init": { + "inputs": { + "a": "10293847563049586721" + }, + "outputs": {} + }, + "narrative": "This is the Harmonic Divisor. It requires input from the Sub-routine Processor to isolate matching digital frequencies." + }, + { + "id": "num_base_convert", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "4607607425162430051697733404910257190110" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "16" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "10" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "399793861475558893217052581389266889886769152272" + } + ], + "init": { + "inputs": { + "from_base": "16", + "to_base": "10" + }, + "outputs": {} + }, + "narrative": "This is the Base Translator Module. It requires input from the Sequence Multiplier to properly align the data formats." + }, + { + "id": "item_16_2d46", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "This is the Encrypted Security Chip. A standalone piece of silicon dropped by a careless corp guard." + }, + { + "id": "zip_unzip_item", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_item", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "metadata.json" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "[\"1234567812345678\", \"8765432187654321\", \"1111222233334444\"]" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip" + } + ], + "narrative": "This is the Archive Extractor Tool. It requires inputs from both the Code Analyzer and the Encrypted Zip File to brute-force compressed directories." + }, + { + "id": "calc_inv_mod", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "4607607425162430051697733404910257190110" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "100003" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "6768" + } + ], + "init": { + "inputs": { + "mod": "100003" + }, + "outputs": {} + }, + "narrative": "This is the Phase Inverter. It requires input from the Sequence Multiplier to reverse the logic flow." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "This is the Corrupted Memory Stick. It has exposed wiring and scorch marks." + }, + { + "id": "container_3", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_3", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Big_Int", + "description": "Fingerprint Hash", + "value": "85960483928475630495" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "85960483928475630495" + }, + "outputs": {} + }, + "narrative": "This is the Employee Lockbox. A standard corporate storage bin for personal items." + }, + { + "id": "calc_bigmul_cce0", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "94857639204857683921" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "48573920495867382910" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "4607607425162430051697733404910257190110" + } + ], + "init": { + "inputs": { + "a": "94857639204857683921" + }, + "outputs": {} + }, + "narrative": "This is the Sequence Multiplier. It requires input from the Digital Keycard to calculate its primary hash." + }, + { + "id": "item_16_b9bd", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "This is the Smuggled Module. A piece of illegal hardware wrapped in anti-static tape." + }, + { + "id": "regex_search", + "name": "Regex Search", + "description": "Search regex in either raw text or a file.", + "type": "Tool", + "template_id": "regex_search", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "pattern", + "type": "Text_Generic", + "description": "Regex pattern", + "value": "\\d{16}" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "File ID (optional)", + "value": "data_scan.txt" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text (optional)", + "value": "Ä string to be normalized" + } + ], + "outputs": [ + { + "name": "matches", + "type": "Text_Generic", + "description": "Found matches (List)", + "value": "[\"1234567812345678\", \"8765432187654321\", \"1111222233334444\"]" + } + ], + "init": { + "inputs": { + "pattern": "\\d{16}", + "file_id": "data_scan.txt" + }, + "outputs": { + "matches": "[\"1234567812345678\", \"8765432187654321\", \"1111222233334444\"]" + } + }, + "narrative": "This is the Code Analyzer. It requires input from the Syntax Normalizer to scan for matching string anomalies." + }, + { + "id": "unicode_norm", + "name": "Unicode Normalizer", + "description": "Unicode normalize (NFC/NFD/NFKC/NFKD).", + "type": "Tool", + "template_id": "unicode_norm", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "Ä string to be normalized" + }, + { + "name": "form", + "type": "Text_Generic", + "description": "Form", + "value": "NFC" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Normalized text", + "value": "Ä string to be normalized" + } + ], + "init": { + "inputs": { + "text": "Ä string to be normalized" + }, + "outputs": {} + }, + "narrative": "This is the Syntax Normalizer. It requires input from the Lobby Security Terminal to format the corrupted text streams." + }, + { + "id": "container_3_c334", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_3", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Big_Int", + "description": "Fingerprint Hash", + "value": "75849302918274635241" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "75849302918274635241" + }, + "outputs": {} + }, + "narrative": "This is the Manager's Secure Vault. A biometric-locked safe used to hoard sensitive gear." + }, + { + "id": "terminal_1_c1ab", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this terminal" + }, + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "Input message for terminal A" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "57483920192837465012" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "NFC" + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "f1e2d3c4b5a697887766554433221100" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": { + "slot_a": "Input message for terminal A" + }, + "outputs": { + "text_output": "NFC", + "hex_output": "f1e2d3c4b5a697887766554433221100" + } + }, + "narrative": "This is the Lobby Security Terminal. It requires input from the Maintenance Access Token to bypass the initial firewall." + }, + { + "id": "item_10", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_10", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Big_Int", + "description": "The number", + "value": "48573920495867382910" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "48573920495867382910" + } + }, + "narrative": "This is the Digital Keycard. A pristine corporate access pass." + }, + { + "id": "item_10_7483", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_10", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Big_Int", + "description": "The number", + "value": "57483920192837465012" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "57483920192837465012" + } + }, + "narrative": "This is the Maintenance Access Token. A high-clearance tag meant for service drones." + }, + { + "id": "item_9", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_9", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "File_Id", + "description": "JSON file path", + "value": "metadata.json" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "metadata.json" + } + }, + "narrative": "This is the Encrypted Zip File. A heavily compressed data package floating in the local network." + }, + { + "id": "calc_gcd_737b", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "83920485768392019283" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "28374659302918273645" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "init": { + "inputs": { + "a": "83920485768392019283", + "b": "28374659302918273645" + }, + "outputs": {} + }, + "narrative": "This is the Network Divisor. A standalone processing node that splits data traffic." + } + ], + "edges": [ + { + "source_id": "terminal_1", + "target_id": "item_15", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "source_tool" + }, + { + "source_id": "luhn_check", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "slot_a" + }, + { + "source_id": "item_16", + "target_id": "luhn_check", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "calc_modexp", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "slot_b" + }, + { + "source_id": "crypto_rsa_decrypt_hex", + "target_id": "luhn_check", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "number" + }, + { + "source_id": "calc_modexp_490b", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "base" + }, + { + "source_id": "calc_bigmul", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "mod" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "b" + }, + { + "source_id": "num_base_convert", + "target_id": "calc_modexp_490b", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "base" + }, + { + "source_id": "item_16_2d46", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "zip_unzip_item", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "item", + "target_port": "source_tool" + }, + { + "source_id": "calc_inv_mod", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "a" + }, + { + "source_id": "item_8", + "target_id": "zip_unzip_item", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "container_3", + "target_id": "calc_modexp_490b", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "calc_bigmul_cce0", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "s" + }, + { + "source_id": "item_16_b9bd", + "target_id": "container_3", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "regex_search", + "target_id": "zip_unzip_item", + "connection_type": "Text_Generic", + "source_port": "matches", + "target_port": "password" + }, + { + "source_id": "unicode_norm", + "target_id": "regex_search", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "text" + }, + { + "source_id": "calc_bigmul_cce0", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "a" + }, + { + "source_id": "container_3_c334", + "target_id": "item_16_b9bd", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "calc_modexp_490b", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "b" + }, + { + "source_id": "calc_modexp_490b", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "n" + }, + { + "source_id": "terminal_1_c1ab", + "target_id": "unicode_norm", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "form" + }, + { + "source_id": "item_10", + "target_id": "calc_bigmul_cce0", + "connection_type": "Big_Int", + "source_port": "content", + "target_port": "b" + }, + { + "source_id": "terminal_1_c1ab", + "target_id": "item_10", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "source_tool" + }, + { + "source_id": "item_10_7483", + "target_id": "terminal_1_c1ab", + "connection_type": "Big_Int", + "source_port": "content", + "target_port": "slot_b" + }, + { + "source_id": "item_9", + "target_id": "zip_unzip_item", + "connection_type": "File_Id", + "source_port": "content", + "target_port": "zip_id" + }, + { + "source_id": "calc_gcd_737b", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "d" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-93dd5f71/solution/solve.sh b/tasks/agentescape-25-skeleton-93dd5f71/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-25-skeleton-93dd5f71/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-25-skeleton-93dd5f71/task.toml b/tasks/agentescape-25-skeleton-93dd5f71/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8c302c8b480346366b40b239bd185b7e587d2831 --- /dev/null +++ b/tasks/agentescape-25-skeleton-93dd5f71/task.toml @@ -0,0 +1,38 @@ +schema_version = "1.4" +source = "https://github.com/AGI-Eval-Official/Repo-of-AgentEscapeBench" + +[[artifacts]] +source = "/evidence/final.json" +service = "puzzle" + +[[artifacts]] +source = "/evidence/trace.jsonl" +service = "puzzle" + +[task] +name = "edbeeching/agentescape-25-skeleton-93dd5f71" +version = "0.1.0" + +[metadata] +difficulty = 25 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "3a12c5406990e3aa8ca1dec8769706d768441e1e0e8c1af095390b32b532276a" +protocol = "harbor-cli-action-budget-v1" +max_actions = 500 + +[agent] +timeout_sec = 1200 + +[environment] +build_timeout_sec = 900 +cpus = 1 +memory_mb = 1024 + +[verifier] +environment_mode = "separate" +timeout_sec = 60 + +[[verifier.collect]] +service = "puzzle" +command = "python -I /app/export.py" +timeout_sec = 15 diff --git a/tasks/agentescape-25-skeleton-93dd5f71/tests/Dockerfile b/tasks/agentescape-25-skeleton-93dd5f71/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-25-skeleton-93dd5f71/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-25-skeleton-93dd5f71/tests/expected.json b/tasks/agentescape-25-skeleton-93dd5f71/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..b2a3b17806f045ed895e6ae7fd9cf3f163a382d3 --- /dev/null +++ b/tasks/agentescape-25-skeleton-93dd5f71/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "3a12c5406990e3aa8ca1dec8769706d768441e1e0e8c1af095390b32b532276a", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-93dd5f71/tests/grade.py b/tasks/agentescape-25-skeleton-93dd5f71/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-25-skeleton-93dd5f71/tests/grade.py @@ -0,0 +1,21 @@ +"""Grade only Harbor-collected sidecar evidence in a fresh verifier container.""" + +import json +from pathlib import Path + +expected = json.loads(Path("/tests/expected.json").read_text()) +state = json.loads(Path("/evidence/final.json").read_text()) +assert state["collected_from_live_service"] is True, "Missing trusted service export" +assert state["scenario_sha256"] == expected["scenario_sha256"], ( + "Wrong scenario evidence" +) +assert state["max_actions"] == expected["max_actions"], "Wrong budget" +assert type(state["won"]) is bool +assert 0 <= state["action_count"] <= state["max_actions"] +assert state["termination_reason"] != "infrastructure_error", ( + "Infrastructure failure is not a puzzle failure" +) +assert not state["won"] or state["termination_reason"] == "success" +Path("/logs/verifier").mkdir(parents=True, exist_ok=True) +Path("/logs/verifier/state.json").write_text(json.dumps(state, indent=2)) +Path("/logs/verifier/reward.txt").write_text("1.0\n" if state["won"] else "0.0\n") diff --git a/tasks/agentescape-25-skeleton-93dd5f71/tests/test.sh b/tasks/agentescape-25-skeleton-93dd5f71/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-25-skeleton-93dd5f71/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-25-skeleton-94cc40fa/environment/Dockerfile b/tasks/agentescape-25-skeleton-94cc40fa/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-25-skeleton-94cc40fa/environment/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-25-skeleton-94cc40fa/environment/agent/Dockerfile b/tasks/agentescape-25-skeleton-94cc40fa/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-25-skeleton-94cc40fa/environment/agent/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-25-skeleton-94cc40fa/environment/agent/cli.py b/tasks/agentescape-25-skeleton-94cc40fa/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-25-skeleton-94cc40fa/environment/agent/cli.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Public agent client; depends only on the Python standard library.""" + +import argparse +import json +import os +import sys +import urllib.error +import urllib.request + + +def main(): + parser = argparse.ArgumentParser(description="Interact with the escape room") + parser.add_argument( + "action", + choices=[ + "observe", + "state", + "investigate", + "tool-call", + "use-item", + "submit-answer", + ], + ) + parser.add_argument("value", nargs="?") + parser.add_argument("--arguments-json", default="{}") + args = parser.parse_args() + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000").rstrip("/") + if args.action in ("observe", "state"): + request = urllib.request.Request( + base + ("/observation" if args.action == "observe" else "/state") + ) + else: + if args.value is None: + parser.error("node ID or answer is required") + payload = {"action": args.action.replace("-", "_")} + if args.action == "submit-answer": + payload["answer"] = args.value + else: + payload["node_id"] = args.value + if args.action in ("tool-call", "use-item"): + payload["arguments"] = json.loads(args.arguments_json) + request = urllib.request.Request( + base + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=30) as response: + print(json.dumps(json.load(response), ensure_ascii=False)) + except (urllib.error.URLError, ValueError) as exc: + print(json.dumps({"ok": False, "error": str(exc)})) + sys.exit(2) + + +if __name__ == "__main__": + main() diff --git a/tasks/agentescape-25-skeleton-94cc40fa/environment/docker-compose.yaml b/tasks/agentescape-25-skeleton-94cc40fa/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a99974cf1c8231e5876c0f0ddbb7050719077843 --- /dev/null +++ b/tasks/agentescape-25-skeleton-94cc40fa/environment/docker-compose.yaml @@ -0,0 +1,50 @@ +services: + main: + image: agentescapebench-agent:aab05a0a9ddb + build: + context: ./agent + networks: [default, puzzle] + security_opt: [no-new-privileges:true] + depends_on: + puzzle: + condition: service_healthy + puzzle: + image: agentescapebench-puzzle:agentescape-25-skeleton-94cc40fa-aab05a0a9ddb + build: + context: ./puzzle + networks: [puzzle, execution] + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 512m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"] + interval: 1s + timeout: 3s + retries: 30 + depends_on: + worker: + condition: service_healthy + worker: + image: agentescapebench-worker:aab05a0a9ddb + build: + context: ./puzzle + dockerfile: worker.Dockerfile + networks: [execution] + read_only: true + tmpfs: ["/tmp:size=64m,mode=1777"] + cap_drop: [ALL] + cap_add: [SETUID, SETGID, KILL, CHOWN, DAC_OVERRIDE] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 384m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8001/health')"] + interval: 1s + timeout: 3s + retries: 30 +networks: + puzzle: + internal: true + execution: + internal: true diff --git a/tasks/agentescape-25-skeleton-94cc40fa/environment/puzzle/Dockerfile b/tasks/agentescape-25-skeleton-94cc40fa/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-25-skeleton-94cc40fa/environment/puzzle/Dockerfile @@ -0,0 +1,9 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY upstream /app/upstream +COPY service.py export.py /app/ +COPY scenario.json /private/scenario.json +ENV SCENARIO_PATH=/private/scenario.json EVIDENCE_DIR=/evidence WORKER_URL=http://worker:8001 MAX_ACTIONS=500 +CMD ["uvicorn", "service:create_app", "--factory", "--host", "0.0.0.0", "--port", "8000", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-25-skeleton-94cc40fa/environment/puzzle/child.py b/tasks/agentescape-25-skeleton-94cc40fa/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-25-skeleton-94cc40fa/environment/puzzle/child.py @@ -0,0 +1,59 @@ +"""Run the original Python tool after reducing privileges and blocking networking.""" + +import ctypes +import errno +import json +import resource +import sys + +resource.setrlimit(resource.RLIMIT_CPU, (3, 3)) +resource.setrlimit(resource.RLIMIT_AS, (256 * 1024 * 1024, 256 * 1024 * 1024)) +resource.setrlimit(resource.RLIMIT_FSIZE, (65536, 65536)) +resource.setrlimit(resource.RLIMIT_NOFILE, (32, 32)) +resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + +# Filters survive fork/exec. Fail closed if seccomp cannot be loaded. +lib = ctypes.CDLL("libseccomp.so.2", use_errno=True) +lib.seccomp_init.argtypes = [ctypes.c_uint32] +lib.seccomp_init.restype = ctypes.c_void_p +lib.seccomp_rule_add.argtypes = [ + ctypes.c_void_p, + ctypes.c_uint32, + ctypes.c_int, + ctypes.c_uint, +] +lib.seccomp_syscall_resolve_name.argtypes = [ctypes.c_char_p] +lib.seccomp_load.argtypes = [ctypes.c_void_p] +lib.seccomp_release.argtypes = [ctypes.c_void_p] +ctx = lib.seccomp_init(0x7FFF0000) # SCMP_ACT_ALLOW +if not ctx: + raise RuntimeError("Cannot initialize execution isolation") +try: + for name in ( + "socket", + "socketpair", + "connect", + "ptrace", + "process_vm_readv", + "process_vm_writev", + "mount", + "unshare", + "setns", + "bpf", + ): + number = lib.seccomp_syscall_resolve_name(name.encode()) + if ( + number >= 0 + and lib.seccomp_rule_add(ctx, 0x00050000 | errno.EPERM, number, 0) != 0 + ): + raise RuntimeError("Cannot install execution isolation rule") + if lib.seccomp_load(ctx) != 0: + raise RuntimeError("Cannot activate execution isolation") +finally: + lib.seccomp_release(ctx) + +sys.path.insert(0, "/app") +from simulator import ToolSimulator # noqa: E402 + +request = json.load(sys.stdin) +json.dump(ToolSimulator().code_py_exec(request), sys.stdout) diff --git a/tasks/agentescape-25-skeleton-94cc40fa/environment/puzzle/export.py b/tasks/agentescape-25-skeleton-94cc40fa/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-25-skeleton-94cc40fa/environment/puzzle/export.py @@ -0,0 +1,13 @@ +"""Harbor invokes this inside the puzzle service after stopping the agent.""" + +import json +import pathlib +import urllib.request + +with urllib.request.urlopen("http://127.0.0.1:8000/state", timeout=10) as response: + state = json.load(response) +state["collected_from_live_service"] = True +target = pathlib.Path("/evidence/final.json") +temp = target.with_suffix(".tmp") +temp.write_text(json.dumps(state)) +temp.replace(target) diff --git a/tasks/agentescape-25-skeleton-94cc40fa/environment/puzzle/requirements.txt b/tasks/agentescape-25-skeleton-94cc40fa/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-25-skeleton-94cc40fa/environment/puzzle/requirements.txt @@ -0,0 +1,57 @@ +annotated-doc==0.0.5 + # via fastapi +annotated-types==0.8.0 + # via pydantic +anyio==4.16.0 + # via starlette +certifi==2026.10.23 + # via requests +cffi==2.1.1 ; platform_python_implementation != 'PyPy' + # via cryptography +charset-normalizer==3.5.2 + # via requests +click==8.5.0 + # via uvicorn +cryptography==50.0.2 + # via agentescapebench-harbor +fastapi==0.162.0 + # via agentescapebench-harbor +h11==0.16.0 + # via uvicorn +idna==3.20 + # via + # anyio + # requests +opentelemetry-api==1.45.2 + # via fastapi +pycparser==3.12 ; implementation_name != 'PyPy' and platform_python_implementation != 'PyPy' + # via cffi +pydantic==2.14.2 + # via + # agentescapebench-harbor + # fastapi +pydantic-core==2.50.2 + # via pydantic +pytz==2025.2 + # via agentescapebench-harbor +requests==2.34.2 + # via agentescapebench-harbor +starlette==1.10.0 + # via fastapi +typing-extensions==4.16.0 + # via + # anyio + # fastapi + # opentelemetry-api + # pydantic + # pydantic-core + # starlette + # typing-inspection +typing-inspection==0.4.4 + # via + # fastapi + # pydantic +urllib3==2.8.0 + # via requests +uvicorn==0.54.0 + # via agentescapebench-harbor diff --git a/tasks/agentescape-25-skeleton-94cc40fa/environment/puzzle/scenario.json b/tasks/agentescape-25-skeleton-94cc40fa/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..30bb0e8f2a7abdf64902debfd35c32b207f6f699 --- /dev/null +++ b/tasks/agentescape-25-skeleton-94cc40fa/environment/puzzle/scenario.json @@ -0,0 +1,1427 @@ +{ + "metadata": { + "total_nodes": 25, + "total_edges": 28, + "win_node_id": "item_14", + "win_condition": { + "type": "item_content", + "node_id": "item_14", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_14", + "graph_shortest_path", + "zip_unzip_file", + "terminal_2", + "item_7", + "container_3_700f", + "num_base_convert", + "calc_inv_mod", + "checksum_crc32_8c69", + "terminal_1", + "crypto_rsa_decrypt_hex", + "item_1", + "base64_decode", + "calc_gcd", + "calc_bigmul_3271" + ], + "by_node": { + "item_14": { + "node_name": "", + "node_type": "Item", + "template_id": "item_14", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Hex_String_IV_AES", + "description": "AES IV" + } + } + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": {}, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": {}, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + }, + "math_token": { + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + } + }, + "item_7": { + "node_name": "", + "node_type": "Item", + "template_id": "item_7", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Code_Python", + "description": "The integer" + } + } + }, + "container_3_700f": { + "node_name": "", + "node_type": "Item", + "template_id": "container_3", + "init_inputs": { + "fingerprint_input": { + "type": "Big_Int", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + }, + "num_base_convert": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "to_base": { + "type": "Big_Int", + "description": "To base" + } + }, + "init_outputs": {} + }, + "calc_inv_mod": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "Integer a" + } + }, + "init_outputs": {} + }, + "checksum_crc32_8c69": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": {}, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + } + } + }, + "crypto_rsa_decrypt_hex": { + "node_name": "RSA Decrypt", + "node_type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "init_inputs": { + "n": { + "type": "Big_Int", + "description": "Modulus n" + }, + "d": { + "type": "Big_Int", + "description": "Private exponent d" + } + }, + "init_outputs": {} + }, + "item_1": { + "node_name": "", + "node_type": "Item", + "template_id": "item_1", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Big_Int", + "description": "The number" + } + } + }, + "base64_decode": { + "node_name": "Base64 Decoder", + "node_type": "Tool", + "template_id": "base64_decode", + "init_inputs": { + "data": { + "type": "Text_Generic", + "description": "Base64 string" + } + }, + "init_outputs": {} + }, + "calc_gcd": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First integer" + } + }, + "init_outputs": {} + }, + "calc_bigmul_3271": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First large integer" + }, + "b": { + "type": "Big_Int", + "description": "Second large integer" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "item_14": { + "init_inputs": {}, + "init_outputs": { + "content": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "graph_shortest_path": { + "init_inputs": {}, + "init_outputs": { + "path": "[\"node_A\", \"node_B\", \"node_C\", \"node_D\", \"node_E\", \"node_F\"]", + "cost": "482094" + } + }, + "zip_unzip_file": { + "init_inputs": { + "zip_id": "archive_7294.zip" + }, + "init_outputs": { + "files": "extracted_files_8942.zip" + } + }, + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Partial computation processed successfully.", + "hex_result": "deadbeef1234567890abcdef", + "math_token": "This is a mathematically useless token." + } + }, + "item_7": { + "init_inputs": {}, + "init_outputs": { + "content": "print(1234567890)" + } + }, + "container_3_700f": { + "init_inputs": { + "fingerprint_input": "4859382910485729103948572" + }, + "init_outputs": {} + }, + "num_base_convert": { + "init_inputs": { + "to_base": "10" + }, + "init_outputs": {} + }, + "calc_inv_mod": { + "init_inputs": { + "a": "59483726152438495067281" + }, + "init_outputs": {} + }, + "checksum_crc32_8c69": { + "init_inputs": { + "hex": "1234abcd5678ef90" + }, + "init_outputs": {} + }, + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "Terminal output successfully generated for slot a.", + "hex_output": "1a2b3c4d5e6f7a8b" + } + }, + "crypto_rsa_decrypt_hex": { + "init_inputs": { + "n": "987654321098765432109876543210", + "d": "123456789012345678901234567890" + }, + "init_outputs": {} + }, + "item_1": { + "init_inputs": {}, + "init_outputs": { + "content": "3948572839401928374650129" + } + }, + "base64_decode": { + "init_inputs": { + "data": "SGVsbG8sIHRoaXMgaXMgYSBiYXNlNjQgZW5jb2RlZCBzdHJpbmcgZm9yIHRlc3RpbmcgZGVjb2RlLg==" + }, + "init_outputs": {} + }, + "calc_gcd": { + "init_inputs": { + "a": "85739284756102938475629" + }, + "init_outputs": {} + }, + "calc_bigmul_3271": { + "init_inputs": { + "a": "948572618394857261738495", + "b": "192837465019283746501928" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You are a private investigator who just broke into the sealed evidence room of the abandoned 12th Precinct. The infamous 'Midnight Syndicate' case was abruptly closed weeks ago, and the lead detective vanished without a trace. Rumor has it they left behind a trail of digital breadcrumbs and encrypted forensic tools that point to a massive conspiracy. You must navigate the scattered equipment, reconstruct the evidence chain, and uncover the final truth before corrupt officials realize you are here.", + "narrative_style": "detective" + }, + "nodes": [ + { + "id": "item_14", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_14", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hex_String_IV_AES", + "description": "AES IV", + "value": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "narrative": "The Final Evidence File. This contains the conclusive proof needed to close the case once and for all." + }, + { + "id": "container_3", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_3", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Big_Int", + "description": "Fingerprint Hash", + "value": "482094" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is the Biometric Evidence Safe. It requires input from the Suspect Tracking System to authenticate and unlock." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A Blacklight Flashlight, heavily used for crime scene investigations to detect hidden traces." + }, + { + "id": "item_8_2d97", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A specialized UV Bulb designed to fit into standard forensic flashlights." + }, + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "extracted_files_8942.zip" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Partial computation processed successfully." + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "1234567890\n" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"node_A\", \"node_B\", \"node_C\", \"node_D\", \"node_E\", \"node_F\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "482094" + } + ], + "init": { + "inputs": {}, + "outputs": { + "path": "[\"node_A\", \"node_B\", \"node_C\", \"node_D\", \"node_E\", \"node_F\"]", + "cost": "482094" + } + }, + "narrative": "This is the Suspect Tracking System. It requires inputs from the Forensic Analysis Computer, the Encrypted Case Archive, and the Main Security Mainframe." + }, + { + "id": "code_py_exec", + "name": "Python Executor", + "description": "Run limited Python: only safe builtins.", + "type": "Tool", + "template_id": "code_py_exec", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "code", + "type": "Code_Python", + "description": "Python code", + "value": "print(1234567890)" + } + ], + "outputs": [ + { + "name": "stdout", + "type": "Text_Generic", + "description": "Standard Output (includes errors if any)", + "value": "1234567890\n" + } + ], + "narrative": "This is the Forensic Analysis Computer. It requires input from the Source Code Fragment to run its simulations." + }, + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "archive_7294.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Partial computation processed successfully." + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_files_8942.zip" + } + ], + "init": { + "inputs": { + "zip_id": "archive_7294.zip" + }, + "outputs": { + "files": "extracted_files_8942.zip" + } + }, + "narrative": "This is the Encrypted Case Archive. It requires input from the Main Security Mainframe to extract its hidden files." + }, + { + "id": "terminal_2", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "0" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "0" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Partial computation processed successfully." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "deadbeef1234567890abcdef" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "This is a mathematically useless token." + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "Partial computation processed successfully.", + "hex_result": "deadbeef1234567890abcdef", + "math_token": "This is a mathematically useless token." + } + }, + "narrative": "This is the Main Security Mainframe. It requires inputs from the Data Aggregator and the Frequency Converter." + }, + { + "id": "calc_bigmul", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "0" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": 3369264727 + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "0" + } + ], + "narrative": "This is the Data Aggregator. It requires inputs from the Secondary Integrity Checker and the Decryption Matrix." + }, + { + "id": "item_8_7e11", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A standard issue Battery Pack, fully charged and ready for use." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "The Detective's Notes, containing scribbled observations left behind by the missing investigator." + }, + { + "id": "item_7", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_7", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Code_Python", + "description": "The integer", + "value": "print(1234567890)" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "print(1234567890)" + } + }, + "narrative": "A Source Code Fragment torn from a programmer's notebook, detailing crucial logic." + }, + { + "id": "item_16_cec9", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "The Initial Briefing folder containing the first terrifying details of the syndicate." + }, + { + "id": "checksum_crc32", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "f8a3b0c8" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "c8d2e657" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3369264727 + } + ], + "narrative": "This is the Secondary Integrity Checker. It requires input from the Primary Integrity Checker to validate the chain of custody." + }, + { + "id": "container_3_700f", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_3", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Big_Int", + "description": "Fingerprint Hash", + "value": "4859382910485729103948572" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "4859382910485729103948572" + }, + "outputs": {} + }, + "narrative": "The Detective's Lockbox, a small heavy metal case kept hidden under a desk." + }, + { + "id": "num_base_convert", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "0" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "3948572839401928374650129" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "10" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "0" + } + ], + "init": { + "inputs": { + "to_base": "10" + }, + "outputs": {} + }, + "narrative": "This is the Frequency Converter. It requires inputs from the Network Analyzer and the Victim's Pager." + }, + { + "id": "calc_inv_mod", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "59483726152438495067281" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "1" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "0" + } + ], + "init": { + "inputs": { + "a": "59483726152438495067281" + }, + "outputs": {} + }, + "narrative": "This is the Decryption Matrix. It requires input from the Signal Synchronizer to align its algorithms." + }, + { + "id": "calc_bigmul_0497", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": 4171477192 + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "0" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "0" + } + ], + "narrative": "This is the Network Analyzer. It requires inputs from the Data Aggregator and the Primary Integrity Checker." + }, + { + "id": "checksum_crc32_8c69", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "1234abcd5678ef90" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "f8a3b0c8" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 4171477192 + } + ], + "init": { + "inputs": { + "hex": "1234abcd5678ef90" + }, + "outputs": {} + }, + "narrative": "The Primary Integrity Checker, a handheld digital scanner used to verify evidence authenticity." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "\t\u00051JRU\u0012" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "3948572839401928374650129" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Terminal output successfully generated for slot a." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "1a2b3c4d5e6f7a8b" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "Terminal output successfully generated for slot a.", + "hex_output": "1a2b3c4d5e6f7a8b" + } + }, + "narrative": "This is the Interrogation Room Terminal. It requires inputs from the Cypher Breaking Module and the Victim's Pager." + }, + { + "id": "crypto_rsa_decrypt_hex", + "name": "RSA Decrypt", + "description": "RSA decrypt (hex cipher) with n,d (decimal).", + "type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex_cipher", + "type": "Hex_String", + "description": "Ciphertext (Hex)", + "value": "48656c6c6f2c207468697320697320612062617365363420656e636f64656420737472696e6720666f722074657374696e67206465636f64652e" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Modulus n", + "value": "987654321098765432109876543210" + }, + { + "name": "d", + "type": "Big_Int", + "description": "Private exponent d", + "value": "123456789012345678901234567890" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decrypted text", + "value": "\t\u00051JRU\u0012" + } + ], + "init": { + "inputs": { + "n": "987654321098765432109876543210", + "d": "123456789012345678901234567890" + }, + "outputs": {} + }, + "narrative": "This is the Cypher Breaking Module. It requires input from the Signal Interceptor to decipher the raw data." + }, + { + "id": "item_1", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "Big_Int", + "description": "The number", + "value": "3948572839401928374650129" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "3948572839401928374650129" + } + }, + "narrative": "The Victim's Pager, badly damaged but still holding a sliver of vital memory." + }, + { + "id": "base64_decode", + "name": "Base64 Decoder", + "description": "Decode base64 to hex bytes.", + "type": "Tool", + "template_id": "base64_decode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "data", + "type": "Text_Generic", + "description": "Base64 string", + "value": "SGVsbG8sIHRoaXMgaXMgYSBiYXNlNjQgZW5jb2RlZCBzdHJpbmcgZm9yIHRlc3RpbmcgZGVjb2RlLg==" + } + ], + "outputs": [ + { + "name": "bytes_hex", + "type": "Hex_String", + "description": "Decoded bytes as Hex", + "value": "48656c6c6f2c207468697320697320612062617365363420656e636f64656420737472696e6720666f722074657374696e67206465636f64652e" + } + ], + "init": { + "inputs": { + "data": "SGVsbG8sIHRoaXMgaXMgYSBiYXNlNjQgZW5jb2RlZCBzdHJpbmcgZm9yIHRlc3RpbmcgZGVjb2RlLg==" + }, + "outputs": {} + }, + "narrative": "The Signal Interceptor, a basic antenna rig used to catch raw data broadcasts around the precinct." + }, + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "85739284756102938475629" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "182920339117968677302289381062489571672149318360" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "init": { + "inputs": { + "a": "85739284756102938475629" + }, + "outputs": {} + }, + "narrative": "This is the Signal Synchronizer. It requires input from the Signal Amplifier to process the audio tracks." + }, + { + "id": "calc_bigmul_3271", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "948572618394857261738495" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "192837465019283746501928" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "182920339117968677302289381062489571672149318360" + } + ], + "init": { + "inputs": { + "a": "948572618394857261738495", + "b": "192837465019283746501928" + }, + "outputs": {} + }, + "narrative": "The Signal Amplifier, an analog device used to boost faint audio recordings from wiretaps." + } + ], + "edges": [ + { + "source_id": "container_3", + "target_id": "item_14", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "item_8", + "target_id": "container_3", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "item_8_2d97", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "graph_shortest_path", + "target_id": "container_3", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "fingerprint_input" + }, + { + "source_id": "code_py_exec", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "stdout", + "target_port": "dst" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "terminal_2", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "password" + }, + { + "source_id": "calc_bigmul", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "num1" + }, + { + "source_id": "item_8_7e11", + "target_id": "item_8_2d97", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_16", + "target_id": "code_py_exec", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "terminal_2", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "src" + }, + { + "source_id": "item_7", + "target_id": "code_py_exec", + "connection_type": "Code_Python", + "source_port": "content", + "target_port": "code" + }, + { + "source_id": "item_16_cec9", + "target_id": "item_8_7e11", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "b" + }, + { + "source_id": "container_3_700f", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "num_base_convert", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "num2" + }, + { + "source_id": "calc_inv_mod", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "a" + }, + { + "source_id": "calc_bigmul_0497", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "s" + }, + { + "source_id": "calc_bigmul", + "target_id": "calc_bigmul_0497", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "b" + }, + { + "source_id": "checksum_crc32_8c69", + "target_id": "calc_bigmul_0497", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "a" + }, + { + "source_id": "terminal_1", + "target_id": "checksum_crc32_8c69", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "trigger_item" + }, + { + "source_id": "crypto_rsa_decrypt_hex", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "slot_a" + }, + { + "source_id": "item_1", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "content", + "target_port": "slot_b" + }, + { + "source_id": "base64_decode", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Hex_String", + "source_port": "bytes_hex", + "target_port": "hex_cipher" + }, + { + "source_id": "item_1", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "content", + "target_port": "from_base" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "mod" + }, + { + "source_id": "checksum_crc32_8c69", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "calc_bigmul_3271", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "b" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-94cc40fa/environment/puzzle/service.py b/tasks/agentescape-25-skeleton-94cc40fa/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-25-skeleton-94cc40fa/environment/puzzle/service.py @@ -0,0 +1,212 @@ +"""Restricted facade over the unchanged, pinned upstream puzzle handlers.""" + +import hashlib +import json +import logging +import os +import sys +import threading +import urllib.request +import uuid +from pathlib import Path + +from fastapi import FastAPI, HTTPException +from fastapi.responses import JSONResponse +from pydantic import BaseModel, ConfigDict + +sys.path.insert(0, str(Path(__file__).parent / "upstream")) +import server as upstream # noqa: E402 + +log = logging.getLogger(__name__) + + +def public(value): + """Keep upstream agent-internal template hints out of the public response.""" + if isinstance(value, dict): + return {k: public(v) for k, v in value.items() if not k.startswith("_")} + if isinstance(value, list): + return [public(v) for v in value] + return value + + +class Action(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + action: str + node_id: str | None = None + arguments: dict | None = None + answer: str | None = None + + +class Episode: + def __init__( + self, scenario_path, max_actions=500, evidence_dir=None, worker_url=None + ): + if max_actions < 1: + raise ValueError("max_actions must be positive") + self.lock = threading.Lock() + self.max_actions = max_actions + self.count = 0 + self.won = False + self.reason = None + self.evidence_dir = Path(evidence_dir) if evidence_dir else None + self.scenario_hash = hashlib.sha256( + Path(scenario_path).read_bytes() + ).hexdigest() + self.initial = upstream.reset_case( + case_file_path=str(scenario_path), session_id=uuid.uuid4().hex + ) + self.case_id = self.initial["case_id"] + # Hide source file paths; no upstream reset/stats/routes are mounted. + self.initial.pop("message", None) + simulator = upstream.SIMULATORS[self.case_id] + if worker_url is None: + + def no_worker(_inputs): + self.reason = "infrastructure_error" + raise RuntimeError("isolated Python worker is not configured") + + simulator.tool_map["code_py_exec"] = no_worker + else: + + def execute_python(inputs): + request = urllib.request.Request( + worker_url + "/execute", + data=json.dumps({"code": inputs.get("code", "")}).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=12) as response: + result = json.load(response) + if not isinstance(result.get("stdout"), str): + raise RuntimeError("Invalid Python worker response") + return result + except Exception: + self.reason = "infrastructure_error" + raise + + simulator.tool_map["code_py_exec"] = execute_python + self.save() + if self.evidence_dir is not None: + (self.evidence_dir / "trace.jsonl").touch() + + def state(self): + return { + "scenario_sha256": self.scenario_hash, + "action_count": self.count, + "max_actions": self.max_actions, + "won": self.won, + "termination_reason": self.reason, + } + + def save(self, action=None, result=None): + if self.evidence_dir is None: + return + self.evidence_dir.mkdir(parents=True, exist_ok=True) + target = self.evidence_dir / "outcome.json" + temp = target.with_suffix(".tmp") + temp.write_text(json.dumps(self.state())) + temp.replace(target) + if action is not None: + with (self.evidence_dir / "trace.jsonl").open("a") as handle: + handle.write( + json.dumps( + {"index": self.count, "action": action, "result": result} + ) + + "\n" + ) + + def dispatch(self, payload): + with self.lock: + if self.reason is not None: + return { + "ok": False, + "error": "Episode has ended", + "episode": self.state(), + } + self.count += 1 + try: + action = Action.model_validate(payload) + if action.action == "submit_answer" and action.answer is not None: + result = upstream.submit_answer( + self.case_id, upstream.SubmitAnswerRequest(answer=action.answer) + ) + if result.get("is_win"): + self.won = True + self.reason = "success" + elif action.action == "investigate" and action.node_id is not None: + result = upstream.investigate( + self.case_id, + upstream.InvestigateRequest(node_id=action.node_id), + ) + elif ( + action.action in ("tool_call", "use_item") + and action.node_id is not None + ): + request_type, handler = ( + (upstream.ToolCallRequest, upstream.tool_call) + if action.action == "tool_call" + else (upstream.UseItemRequest, upstream.use_item) + ) + result = handler( + self.case_id, + request_type( + node_id=action.node_id, arguments=action.arguments or {} + ), + ) + else: + result = { + "ok": False, + "error": "Unknown action or missing action parameter", + } + except HTTPException as exc: + result = {"ok": False, "error": exc.detail} + except ValueError: + result = {"ok": False, "error": "Malformed action"} + except Exception: + log.exception("Puzzle service failure") + self.reason = "infrastructure_error" + self.save() + raise + if self.reason is None and self.count >= self.max_actions: + self.reason = "action_budget_exhausted" + result = public(result) + result["episode"] = self.state() + self.save(payload, result) + return result + + +def create_app( + scenario_path=None, max_actions=None, evidence_dir=None, worker_url=None +): + episode = Episode( + scenario_path or os.environ["SCENARIO_PATH"], + max_actions or int(os.environ.get("MAX_ACTIONS", "500")), + evidence_dir if evidence_dir is not None else os.environ.get("EVIDENCE_DIR"), + worker_url if worker_url is not None else os.environ.get("WORKER_URL"), + ) + app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) + app.state.episode = episode + + @app.get("/health") + def health(): + return {"ok": True} + + @app.get("/observation") + def observation(): + return {**public(episode.initial), "episode": episode.state()} + + @app.get("/state") + def state(): + return episode.state() + + @app.post("/action") + def action(payload: dict): + try: + return episode.dispatch(payload) + except Exception: + return JSONResponse( + status_code=503, + content={"ok": False, "error": "Puzzle infrastructure failure"}, + ) + + return app diff --git a/tasks/agentescape-25-skeleton-94cc40fa/environment/puzzle/upstream/models.py b/tasks/agentescape-25-skeleton-94cc40fa/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-25-skeleton-94cc40fa/environment/puzzle/upstream/models.py @@ -0,0 +1,108 @@ +from enum import Enum +from typing import List, Dict, Any, Optional +from pydantic import BaseModel, Field + +# 1. 细粒度接口类型定义 +class InterfaceType(str, Enum): + ''' + BIG_INT + TEXT_GENERIC + HEX_STRING + FILE_ID + HEX_STRING_KEY_AES + HEX_STRING_IV_AES + CODE_PYTHON + HIDDEN_ITEM + ITEM + ''' + # --- 基础类型 --- + TEXT_GENERIC = "Text_Generic" + BIG_INT = "Big_Int" + + # --- 编码/格式化字符串 --- + HEX_STRING = "Hex_String" # 通用 Hex + + # --- 特定用途的 Hex 字符串 (用于精确匹配) --- + HEX_STRING_KEY_AES = "Hex_String_Key_AES" + HEX_STRING_IV_AES = "Hex_String_IV_AES" + + # --- 文件类型 --- + FILE_ID = "File_Id" + + # --- 代码/脚本 --- + CODE_PYTHON = "Code_Python" + + # --- 实体交互类型 (严格命名) --- + ITEM = "Item" # 主动掉落接口 (Tool -> Item) + HIDDEN_ITEM = "Hidden_Item" # 被动掉落接口 (Item -> Item) + +# 3. 端口定义 +class Port(BaseModel): + name: str + type: InterfaceType + description: str + +# 4. 统一节点定义 (融合工具和物品) +class Node(BaseModel): + id: str + name: str + description: str + type: str # "Tool" or "Item" + + # 接口定义 + inputs: List[Port] = [] + outputs: List[Port] = [] + + # 状态字段 + content: Optional[Any] = None # 物品有内容,工具为None + if_success: Optional[bool] = None # 工具初始为False,物品为None + initial_visible: bool = False + + # 运行时状态 (Server维护) + is_revealed: bool = False + + # 标记该 Tool 节点是否有待触发的 HIDDEN_ITEM 掉落 + # 当 Tool 按照 golden_input 正确执行且有 HIDDEN_ITEM 输出边时设为 True + # 在 investigate 该 Tool 时触发掉落并重置为 False + has_hidden_item_ready: bool = False + + # 初始输入值 (metadata.initial_values.init_inputs,用于渐进式暴露判断) + init_input_values: Dict[str, Any] = {} + + # Golden 输入值 (nodes[].inputs[].value,用于评测验证) + golden_input_values: Dict[str, Any] = {} + + # Golden 输出值 (nodes[].outputs[].value,用于评测验证和 Item 节点的 content) + golden_output_values: Dict[str, Any] = {} + + # 实际获得的输出值历史 (工具每次执行后实际返回的输出列表,用于渐进式暴露判断) + # 格式: List[Dict[str, Any]],每个元素是一次执行的输出字典 + actual_outputs_history: List[Dict[str, Any]] = [] + + # 逻辑规则 (用于终端机等复杂物品) + logic_rules: Optional[Dict[str, Any]] = None + + def copy(self, **kwargs): + """Helper to create a copy with updated fields.""" + data = self.dict() + data.update(kwargs) + return Node(**data) + +# 5. 边定义 (拓扑结构) +class Edge(BaseModel): + source_id: str + target_id: str + connection_type: InterfaceType # 直接使用 InterfaceType + # 如果是 Data_Flow,指定端口对应关系 + source_port: Optional[str] = None + target_port: Optional[str] = None + +# 6. 完整图定义 +class GraphScenario(BaseModel): + case_id: str + title: str + intro_narrative: str + nodes: Dict[str, Node] + edges: List[Edge] + difficulty: int + win_node_id: str # 标记哪个节点是最终目标(通常是一个提交工具或最终物品) diff --git a/tasks/agentescape-25-skeleton-94cc40fa/environment/puzzle/upstream/server.py b/tasks/agentescape-25-skeleton-94cc40fa/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-25-skeleton-94cc40fa/environment/puzzle/upstream/server.py @@ -0,0 +1,1490 @@ +import json +import os +import time +import logging +import random +from pathlib import Path +from typing import Dict, Any, List, Optional +from datetime import datetime +from collections import defaultdict +from fastapi import FastAPI, HTTPException, Request +from fastapi.responses import JSONResponse +from fastapi.middleware.cors import CORSMiddleware +from pydantic import BaseModel, Field + +from models import GraphScenario, Node, InterfaceType +# from generator import ScenarioGenerator +from simulator import ToolSimulator +import uvicorn + +# 配置日志 +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler('server.log'), + logging.StreamHandler() + ] +) +logger = logging.getLogger(__name__) + +app = FastAPI( + title="AgentEscapeBench Universal Server", + version="1.0.0", + description="Industrial-grade evaluation server for escape room AI agents" +) + +# 添加 CORS 支持 +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# In-memory State +SCENARIOS: Dict[str, GraphScenario] = {} +SIMULATORS: Dict[str, ToolSimulator] = {} # case_id -> ToolSimulator +RAW_NODES_DATA: Dict[str, Dict[str, Any]] = {} # case_id -> node_id -> raw node data (for template_id) +FILE_METADATA: Dict[str, Dict[str, Any]] = {} # case_id -> metadata (for initial_values access) + +# Performance monitoring +STATS: Dict[str, Any] = { + "total_requests": 0, + "successful_requests": 0, + "failed_requests": 0, + "tool_calls": defaultdict(int), + "investigates": defaultdict(int), + "use_items": defaultdict(int), + "case_loads": 0, + "start_time": datetime.now() +} + +# Request timing middleware +@app.middleware("http") +async def add_process_time_header(request: Request, call_next): + start_time = time.time() + STATS["total_requests"] += 1 + + try: + response = await call_next(request) + STATS["successful_requests"] += 1 + process_time = time.time() - start_time + response.headers["X-Process-Time"] = str(process_time) + logger.info(f"{request.method} {request.url.path} - {response.status_code} - {process_time:.3f}s") + return response + except Exception as e: + STATS["failed_requests"] += 1 + logger.error(f"{request.method} {request.url.path} - Error: {str(e)}") + raise + +# Exception handler +@app.exception_handler(Exception) +async def global_exception_handler(request: Request, exc: Exception): + logger.error(f"Unhandled exception: {exc}", exc_info=True) + return JSONResponse( + status_code=500, + content={ + "ok": False, + "error": "Internal server error", + "detail": str(exc) if os.getenv("DEBUG") else "An error occurred" + } + ) + +# Health check endpoint +@app.get("/health") +def health_check(): + """健康检查端点""" + uptime = (datetime.now() - STATS["start_time"]).total_seconds() + return { + "status": "healthy", + "version": "1.0.0", + "uptime_seconds": uptime, + "loaded_cases": len(SCENARIOS), + "stats": { + "total_requests": STATS["total_requests"], + "successful_requests": STATS["successful_requests"], + "failed_requests": STATS["failed_requests"], + "success_rate": STATS["successful_requests"] / max(STATS["total_requests"], 1) + } + } + +# Statistics endpoint +@app.get("/stats") +def get_stats(): + """获取详细统计信息""" + return { + "stats": STATS, + "loaded_cases": list(SCENARIOS.keys()), + "uptime": str(datetime.now() - STATS["start_time"]) + } + +def _apply_progressive_reveal_at_init(scenario: GraphScenario): + """ + 在初始化时应用渐进式暴露机制(基于ITEM/HIDDEN_ITEM边) + + 新逻辑: + - 如果一个节点没有 ITEM/HIDDEN_ITEM 类型的入边,它就是初始可见的 + - 如果一个节点有 ITEM/HIDDEN_ITEM 类型的入边,它初始不可见,需要等待上游触发 + + Args: + scenario: 场景对象 + """ + # 收集所有有 ITEM/HIDDEN_ITEM 入边的节点 + nodes_with_item_edges = set() + for edge in scenario.edges: + if edge.connection_type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + nodes_with_item_edges.add(edge.target_id) + + logger.info(f"Nodes with ITEM/HIDDEN_ITEM incoming edges: {nodes_with_item_edges}") + + # 设置初始可见性:没有 ITEM/HIDDEN_ITEM 入边的节点初始可见 + initially_visible_count = 0 + for node_id, node in scenario.nodes.items(): + if node_id not in nodes_with_item_edges: + node.is_revealed = True + initially_visible_count += 1 + logger.info(f"Initial visible (no ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + else: + node.is_revealed = False + logger.debug(f"Initial hidden (has ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + + logger.info(f"Progressive reveal initialized: {initially_visible_count}/{len(scenario.nodes)} nodes initially visible") + + +def _check_inputs_match_golden(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> bool: + """ + 检查实际输入参数是否与 golden inputs 完全匹配 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + True 表示所有 golden inputs 都存在且值匹配 + """ + if not golden_inputs: + return True # 如果没有 golden inputs,认为匹配 + + for key, expected_value in golden_inputs.items(): + actual_value = arguments.get(key) + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) != str(expected_value): + logger.debug(f"Input mismatch for '{key}': expected '{expected_value}', got '{actual_value}'") + return False + + return True + + +def _get_parameter_validation_feedback(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> Dict[str, Any]: + """ + 对源头节点的参数进行详细验证,返回验证反馈 + + 注意:不返回期望值(expected),避免泄漏答案 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + 包含验证结果的字典: + - all_correct: bool - 所有参数是否正确 + - correct_params: List[str] - 正确的参数名列表 + - incorrect_params: List[str] - 错误的参数名列表(不包含期望值) + """ + if not golden_inputs: + return { + "all_correct": True, + "correct_params": [], + "incorrect_params": [] + } + + correct_params = [] + incorrect_params = [] + + for key, actual_value in arguments.items(): + # 只对用户实际提交的参数给反馈,未提交的参数不评价 + if key not in golden_inputs: + continue # 该参数不在 golden 中,跳过(如 _golden_inputs 等内部参数) + expected_value = golden_inputs[key] + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) == str(expected_value): + correct_params.append(key) + else: + # 只记录参数名,不包含期望值,避免泄漏答案 + incorrect_params.append(key) + + # all_correct:用户提交的所有参数都正确,且覆盖了全部 golden 参数 + all_provided_correct = len(incorrect_params) == 0 + all_golden_covered = all(k in arguments for k in golden_inputs) + return { + "all_correct": all_provided_correct and all_golden_covered, + "correct_params": correct_params, + "incorrect_params": incorrect_params + } + + +def _is_source_node(node_id: str, scenario: GraphScenario) -> bool: + """ + 判断节点是否是源头节点(完全没有任何入边的节点) + + 源头节点定义: + - 没有任何类型的入边(包括 DATA、ITEM、HIDDEN_ITEM) + - 即没有任何上游节点 + + Args: + node_id: 节点ID + scenario: 场景对象 + + Returns: + True 表示是源头节点 + """ + for edge in scenario.edges: + if edge.target_id == node_id: + # 只要有任何入边,就不是源头节点 + return False + + return True + + +def _check_and_reveal_ready_nodes(scenario: GraphScenario, recent_outputs: Dict[str, Any], source_node_id: str) -> List[Dict[str, Any]]: + """ + 检查并释放参数齐全的隐藏节点(渐进式暴露机制) + + 核心逻辑: + 1. 维护"可见值集合":包含所有被测模型当前可以看到的值 + - init_inputs 的值(初始可见) + - 工具执行后的实际输出值(运行时获得) + - 可见 Item 的输出值 + 2. 检查隐藏节点:该节点的所有 golden_input 值是否都在可见值集合中 + 3. 如果是,则释放该节点 + + Args: + scenario: 场景对象 + recent_outputs: 最近执行的工具的输出 + source_node_id: 刚执行的工具节点ID + + Returns: + 新释放的节点列表 + """ + newly_revealed = [] + + # 构建"可见值集合"(Set of visible values) + # 存储格式:set of values (转为字符串) + visible_values = set() + + # 1. 添加有意义的 init_inputs 值到可见值集合 + # Item 的 init_inputs 不应该加入,因为它们在密室中完全用不到 + for node_id, node in scenario.nodes.items(): + # 跳过源头 Item 节点(没有入边的 Item) + if node.type == "Item": + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,跳过其 init_inputs + continue + + # 添加其他节点的 init_inputs + for port_name, init_value in node.init_input_values.items(): + if init_value: + visible_values.add(str(init_value)) + + # 2. 添加已执行工具的所有历史输出值 + for node_id, node in scenario.nodes.items(): + if node.type == "Tool" and node.if_success and node.actual_outputs_history: + # 遍历所有历史执行记录 + for output_dict in node.actual_outputs_history: + for output_port_name, output_value in output_dict.items(): + if output_value: + visible_values.add(str(output_value)) + + # 3. 添加已被 investigate 的 Item 的 golden 输出值 + # 注意:Item 可见不等于其输出值可见,需要 investigate 后才能获得 + # 这里我们使用 actual_outputs_history 来标记 Item 是否已被 investigate + for node_id, node in scenario.nodes.items(): + if node.type == "Item" and node.is_revealed and node.actual_outputs_history: + # Item 通常只会被 investigate 一次,但为了一致性也使用历史列表 + for output_dict in node.actual_outputs_history: + for port_name, port_value in output_dict.items(): + if port_value: + visible_values.add(str(port_value)) + + # 遍历所有隐藏的节点,检查其 golden_input 是否都在可见值集合中 + for node_id, node in scenario.nodes.items(): + # 跳过已可见的节点 + if node.is_revealed: + continue + + # 只检查工具节点(物品节点由 ITEM 输出触发) + if node.type != "Tool": + continue + + # 检查该节点的所有 golden_input 值是否都在可见值集合中 + all_inputs_ready = True + missing_values = [] + + for input_port_name, golden_input_value in node.golden_input_values.items(): + # 检查这个 golden 值是否在可见值集合中 + if str(golden_input_value) not in visible_values: + all_inputs_ready = False + missing_values.append(f"{input_port_name}={golden_input_value}") + + # 如果所有 golden_input 值都在可见值集合中,释放该节点 + if all_inputs_ready and len(node.golden_input_values) > 0: + logger.info(f"All golden inputs ready for {node_id}: {list(node.golden_input_values.values())}") + + # 如果所有输入都齐全,释放该节点 + if all_inputs_ready: + node.is_revealed = True + + # 构建节点信息返回给模型 + node_info = { + "id": node.id, + "type": node.type, + "can_investigate": True, + "hint": "This tool's input parameters are now complete, you can use investigate to view detailed information" + } + + # if node.name: + # node_info["name"] = node.name + if node.description: + node_info["description"] = node.description + + newly_revealed.append(node_info) + logger.info(f"Progressive reveal: {node_id} is now ready (all inputs satisfied)") + + return newly_revealed + + +def _initialize_node_values(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]): + """ + Initialize node state and load values from port value fields. + 应用渐进式暴露机制:初始时只显示参数齐全的节点(源头节点) + + 重要区分: + 1. input_values: 只加载 metadata.initial_values 中的 init_inputs(真正的初始值) + 2. output_values: 加载 nodes[].outputs[].value(golden 输出,用于验证) + """ + # 第一步:加载所有节点的值,并将所有节点初始设为隐藏 + initial_values = metadata.get('initial_values', {}) + + for node_id, node in scenario.nodes.items(): + # 忽略 initial_visible 字段,初始全部隐藏 + # 由渐进式暴露机制根据参数齐全情况决定是否显示 + node.is_revealed = False + + if node.type == "Tool": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + elif node.type == "Item": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + + # 从 JSON 加载值 + if node_id in raw_nodes_data: + node_data = raw_nodes_data[node_id] # node_data是json文件中nodes中的字典 + + # 【重要】只加载 metadata.initial_values 中的初始输入值 + if node_id in initial_values: + init_data = initial_values[node_id] + # 加载初始输入值(用于渐进式暴露判断) + for port_name, port_value in init_data.get('init_inputs', {}).items(): + node.init_input_values[port_name] = port_value + + # 【评测用】加载 golden 输入值(用于验证模型传入的参数是否正确) + for input_port_data in node_data.get('inputs', []): + if 'value' in input_port_data: + node.golden_input_values[input_port_data['name']] = input_port_data['value'] + + # 【评测用】加载 golden 输出值(用于验证工具调用是否正确,以及 Item 节点的 content) + for output_port_data in node_data.get('outputs', []): + if 'value' in output_port_data: + node.golden_output_values[output_port_data['name']] = output_port_data['value'] + + # For Items, set content from golden_output_values + if node.type == "Item" and node.golden_output_values: + # Item 的 content 是其第一个 golden 输出值 + node.content = list(node.golden_output_values.values())[0] + + # 第二步:应用渐进式暴露机制 + # 检查所有节点,根据参数齐全情况释放源头节点(工具 + Item) + _apply_progressive_reveal_at_init(scenario) + +def _build_node_info(node: Node, raw_nodes_data: Dict[str, Any]) -> Dict[str, Any]: + """ + 构建节点信息(工具或物品) + + Args: + node: 节点对象 + raw_nodes_data: 原始节点数据(用于获取 template_id 等) + + Returns: + 节点信息字典 + """ + if node.type == "Tool": + # 过滤掉输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口) + # 这些端口仅用于控制掉落机制,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + tool_info = { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Tool", + "inputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.inputs if p.type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]], + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id(工具的标准名称) + if node.id in raw_nodes_data: + node_data = raw_nodes_data[node.id] + template_id = node_data.get('template_id') + if template_id: + tool_info['template_id'] = template_id + + return tool_info + + elif node.type == "Item": + return { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Item" + } + + else: + return { + "id": node.id, + # "name": node.name, + "type": node.type + } + +def _get_initial_observation(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]) -> Dict[str, Any]: + """ + Generate initial observation for the agent (what they see when entering the room). + + 策略: + - Tools: 只显示名称和描述,不显示接口定义。需要 investigate 才能获得详细接口信息。 + - Items: 只显示存在,不显示内容。需要 investigate 才能获得内容值。 + - init_inputs: 作为"可用信息"告诉模型,这些是可以用作工具参数的初始值。 + - init_outputs: 不告诉模型(这些是答案,需要模型通过调用工具获得)。 + """ + available_entities = [] # 统一的实体列表(Tools 和 Items) + available_information = [] # 可用的初始信息(来自 init_inputs) + + # 从 metadata.initial_values 提取 init_inputs 作为可用信息 + # 只提供值本身,不透露这些值对应哪个节点的哪个参数,让模型自己推理 + # 注意:跳过源头 Item(没有入边的 Item)的 init_inputs,因为它们在密室中完全用不到 + initial_values = metadata.get('initial_values', {}) + # initial_values字段的格式 + # "initial_values": { + # "terminal_1": { + # "init_inputs": {}, + # "init_outputs": { + # "text_output": "System initialization complete.", + # "hex_output": "48656c6c6f20576f726c64", + # "item_dispenser": "掉落了一张纸条,上面写着“请勿随意触摸终端”" + # } + # } + # } + for node_id, init_data in initial_values.items(): + # 获取节点信息,判断是否为源头 Item + node = scenario.nodes.get(node_id) + if node and node.type == "Item": + # 检查是否为源头 Item(没有入边) + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,检查是否有 init_inputs + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 有 init_inputs,需要暴露这些参数 + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + # 处理完后跳过后续的通用逻辑 + continue + + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 为每个 init_input 值创建一个信息条目(不包含 source_node 和 parameter 信息) + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + + for node in scenario.nodes.values(): + if node.is_revealed: + # Tools: 只显示基本信息,提示可以 investigate 查看详细接口 + if node.type == "Tool": + tool_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Tool", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the tool's detailed interface information for calling" + } + # 只在 name 非空时添加 + # if node.name: + # tool_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_info["description"] = node.description + + available_entities.append(tool_info) + + # Items: 只显示基本信息,提示可以 investigate 查看内容 + elif node.type == "Item": + item_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Item", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the item's content" + } + # 只在 name 非空时添加 + # if node.name: + # item_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + item_info["description"] = node.description + + available_entities.append(item_info) + + return { + "narrative": scenario.intro_narrative, + "available_entities": available_entities, # 使用统一的实体列表 + "available_information": available_information, # 可用的初始信息(只包含 init_inputs) + "win_node_id": scenario.win_node_id # 胜利节点ID,让模型知道需要关注哪个节点 + } + +@app.post("/env/reset") +def reset_case(case_id: str = None, case_file_path: str = None, session_id: str = None): + """Loads a specific case from file and resets it. + + Args: + case_id: Optional case ID for resetting an existing case + case_file_path: Path to case file for loading a new case + session_id: Optional session ID to ensure isolation between concurrent evaluations + """ + logger.info(f"Reset request - case_id: {case_id}, case_file_path: {case_file_path}, session_id: {session_id}") + STATS["case_loads"] += 1 + + if case_file_path: + if not os.path.exists(case_file_path): + logger.error(f"Case file not found: {case_file_path}") + raise HTTPException(status_code=404, detail=f"File not found: {case_file_path}") + try: + with open(case_file_path, "r", encoding="utf-8") as f: + file_data = json.load(f) + + # 转换格式:从 DAG executor 生成的格式转换为 GraphScenario 格式 + # 1. 提取 metadata + metadata = file_data.get('metadata', {}) + + # 2. 生成 case_id, title, intro_narrative + # 【修复】为每个评测会话生成唯一的 case_id,防止并发评测时状态污染 + base_name = os.path.basename(case_file_path).replace('.json', '').replace('_full', '').replace('_full2', '') + + if session_id: + # 如果提供了 session_id,使用它来确保唯一性 + case_id = f"{base_name}_{session_id}" + else: + # 否则使用时间戳和随机数确保唯一性 + unique_suffix = f"{int(time.time() * 1000)}_{random.randint(1000, 9999)}" + case_id = f"{base_name}_{unique_suffix}" + + file_data['case_id'] = case_id + logger.info(f"Generated unique case_id: {case_id} (base: {base_name}, session: {session_id})") + + if 'title' not in file_data: + file_data['title'] = f"Escape Room: {file_data['case_id']}" + + if 'intro_narrative' not in file_data: # 目前的json文件中已经有了intro_narrative字段,不会使用下面一行的内容,而是使用每个评测问题的json文件中的对应字段 + 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]".' + + # 3. 转换 nodes 列表为字典(DAG executor 生成的文件中 nodes 是列表格式) + nodes_dict = {} + for node_data in file_data['nodes']: + nodes_dict[node_data['id']] = node_data # 这里的id是template_id之后可能添加一个后缀 + file_data['nodes'] = nodes_dict # 把列表转成一个字典 + + # 4. 添加缺失的字段 + if 'difficulty' not in file_data: + file_data['difficulty'] = metadata.get('total_nodes', 5) + + if 'win_node_id' not in file_data: + file_data['win_node_id'] = metadata.get('win_node_id', '') + + scenario = GraphScenario(**file_data) + + # Extract raw nodes data for template_id access + # nodes 已经在上面转换为字典格式 + raw_nodes_data = file_data.get('nodes', {}) + RAW_NODES_DATA[scenario.case_id] = raw_nodes_data + + # Store metadata for initial values access + FILE_METADATA[scenario.case_id] = metadata + + logger.info(f"Successfully parsed case file: {scenario.case_id}, nodes: {len(scenario.nodes)}, edges: {len(scenario.edges)}") + except Exception as e: + logger.error(f"Failed to load case file: {str(e)}", exc_info=True) + raise HTTPException(status_code=500, detail=f"Failed to load case file: {str(e)}") + + # Initialize node state and load values + _initialize_node_values(scenario, raw_nodes_data, metadata) + + SCENARIOS[scenario.case_id] = scenario + simulator = ToolSimulator() + SIMULATORS[scenario.case_id] = simulator + + 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'])}") + + # 生成初始观察信息(进入密室后看到的环境) + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + ''' + initial_observation的格式: + { + "narrative": scenario.intro_narrative, + "available_entities": available_entities # 使用统一的实体列表 + "available_information": available_information # 可用的初始信息(只包含 init_inputs) + } + ''' + + return { + "ok": True, + "message": f"Case loaded from {case_file_path}", + "case_id": scenario.case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果没有提供 case_file_path,但提供了 case_id,则尝试从内存重置 + if case_id and case_id in SCENARIOS: + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + metadata = FILE_METADATA.get(case_id, {}) + + # Reset dynamic fields and re-apply progressive reveal + # 重新初始化节点状态(包括渐进式暴露) + _initialize_node_values(scenario, raw_nodes_data, metadata) + + 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'])}") + + # 生成初始观察信息 + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + + return { + "ok": True, + "message": f"Case {case_id} reset.", + "case_id": case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果既没有 case_file_path,也没有在内存中找到,返回错误 + raise HTTPException( + status_code=400, + detail="Must provide case_file_path to load a new case, or use case_id to reset an existing case." + ) + +class InvestigateRequest(BaseModel): + node_id: str + +@app.post("/env/{case_id}/investigate") +def investigate(case_id: str, req: InvestigateRequest): + """ + Investigates a Tool or Item to reveal detailed information. + + - For Tools: Returns detailed interface information (inputs/outputs) needed to call the tool + - For Items: Returns content value and triggers hidden item drops + """ + logger.info(f"Investigate request - case_id: {case_id}, node_id: {req.node_id}") + STATS["investigates"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + node = scenario.nodes[req.node_id] + + if not node.is_revealed: + logger.warning(f"Attempt to investigate hidden node: {req.node_id}") + return {"ok": False, "error": "Node is not visible yet."} + + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + newly_revealed = [] + + # 处理 Tool 的 investigate + if node.type == "Tool": + logger.info(f"Investigating tool: {req.node_id}") + + # 返回工具的详细接口信息 + # id 字段使用 node.id(节点唯一标识),agent 用这个字段识别和调用具体的节点 + # template_id 是工具类型标识符,Agent 内部用于判断工具特性(如 terminal 类工具参数可选) + # 注意:只过滤输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口),这些端口仅用于控制掉落,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + # 【端口上游依赖提示 & 初始值直接给出】 + # 针对参数语义模糊(全为数字类型)的工具,在 investigate 返回信息中标注 + # 哪个输入端口来自哪个上游节点(upstream_from)。 + # 对于所有工具:若该节点不是纯源头节点(有任意数据流入边), + # 且某个端口没有上游入边(值来自初始可见参数),则直接给出该端口的 golden input 值。 + AMBIGUOUS_TOOLS = { + "num_base_convert", "calc_modexp", "calc_modexp_int", + "calc_inv_mod", "calc_inv_mod_int", "crypto_rsa_decrypt_hex", "geo_haversine" + } + # Terminal 类工具自带参数对错反馈机制,玩家/模型可自行试错, + # 无需在 investigate 时直接暴露 init_value + SELF_FEEDBACK_TOOLS = { + "terminal_1", "terminal_2", + "Logic Terminal", "Math Terminal", "Encryption Terminal", "Sequence Terminal" + } + _template_id_for_hint = raw_nodes_data.get(node.id, {}).get("template_id", "") + # 构建数据流入边映射(对所有工具):{target_port -> (source_node_id, source_port)} + _upstream_map = {} + for _edge in scenario.edges: + if (_edge.target_id == node.id + and _edge.connection_type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM] + and _edge.target_port is not None): + _upstream_map[_edge.target_port] = (_edge.source_id, _edge.source_port) + # 判断该节点是否有任意数据流入边(即不是纯源头节点) + _has_any_upstream = len(_upstream_map) > 0 + # 判断该节点是否有任意入边(包括 ITEM/HIDDEN_ITEM 掉落边) + # 有任意入边(含掉落边)但无数据流入边的节点,其输入来自初始可见参数,应直接给出 + _has_any_edge = any(_edge.target_id == node.id for _edge in scenario.edges) + # 构建 inputs 列表 + _inputs_list = [] + for p in node.inputs: + if p.type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + continue + port_dict = {"name": p.name, "type": p.type, "description": p.description} + if p.name in _upstream_map: + # 该端口有上游数据流依赖,且属于语义模糊工具 → 标注来源 + if _template_id_for_hint in AMBIGUOUS_TOOLS: + src_node_id, src_port = _upstream_map[p.name] + port_dict["upstream_from"] = f"{src_node_id}.{src_port}" if src_port else src_node_id + elif _has_any_edge and _template_id_for_hint not in SELF_FEEDBACK_TOOLS: + # 该节点有任意入边,但此端口没有数据流入边 → 值来自初始可见参数,直接给出 + # 排除自带反馈机制的 terminal 类工具(它们通过执行结果反馈对错,无需提前暴露参数值) + golden_val = node.golden_input_values.get(p.name) + if golden_val is not None: + port_dict["init_value"] = golden_val + _inputs_list.append(port_dict) + + tool_details = { + "id": node.id, # 节点 ID,用于唯一标识和调用这个具体节点 + "type": "Tool", + "inputs": _inputs_list, + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id 用于 Agent 内部判断工具类型(不会展示给被测模型) + if node.id in raw_nodes_data: + template_id = raw_nodes_data[node.id].get('template_id') + if template_id: + tool_details["_template_id"] = template_id # 使用下划线前缀标记为内部字段 + + # 只在 name 非空时添加 + # if node.name: + # tool_details["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_details["description"] = node.description + + # 添加 narrative 字段(如果存在) + if node.id in raw_nodes_data: + narrative = raw_nodes_data[node.id].get('narrative') + if narrative: + tool_details['narrative'] = narrative + + # 不再返回 init_values,避免泄漏答案 + # investigate 只应该返回工具的接口定义,不应该暴露初始值 + + # 【新增】检查该 Tool 是否有待触发的 HIDDEN_ITEM 掉落 + # 如果该工具已按照 golden_input 正确执行,且有 HIDDEN_ITEM 输出边,则触发掉落 + if node.has_hidden_item_ready: + logger.info(f"Tool has HIDDEN_ITEM ready - triggering passive drop for: {req.node_id}") + + # 遍历该工具的所有 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + # 重置标志,已经触发过了,避免重复 + node.has_hidden_item_ready = False + + logger.info(f"Tool investigation successful - node: {req.node_id}, revealed: {len(newly_revealed)}") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Tool", + "details": tool_details + } + + # 如果有新掉落的节点,添加到响应中 + if newly_revealed: + result["newly_revealed"] = newly_revealed + + return result + + # 处理 Item 的 investigate + elif node.type == "Item": + logger.info(f"Investigating item: {req.node_id}") + + # 【第一步】检查该 Item 是否有需要参数的输入端口 + # 如果有,且尚未通过 use_item 验证,则不返回内容,只返回参数要求 + required_inputs = [] + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + inputs_info = raw_node.get('inputs', []) + required_inputs = [ + { + "name": inp.get("name"), + "type": inp.get("type"), + "description": inp.get("description", "") + } + for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + # 如果有 required_inputs 且尚未通过 use_item 验证(if_success == False) + # 则不返回内容,只返回参数要求提示 + if required_inputs and not node.if_success: + logger.info(f"Item has required inputs and not yet unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "required_inputs": required_inputs + } + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + param_names = ', '.join([inp['name'] for inp in required_inputs]) + 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}" + + return result + + # 【新增】如果有 required_inputs 且已经通过 use_item 验证(if_success == True) + # 则返回提示:该节点已经被成功解决 + if required_inputs and node.if_success: + logger.info(f"Item has required inputs and already unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "message": "This item has already been successfully unlocked by you." + } + return result + + # 【第二步】该 Item 没有 required_inputs 或已通过验证,返回内容 + # 1. 返回 Item 的 golden_output_values(即 Item 的内容) + # 注意:某些 Item 仅用于触发 HIDDEN_ITEM 掉落,没有实际内容 + has_actual_content = bool(node.golden_output_values) or node.content is not None + content = node.golden_output_values if node.golden_output_values else node.content + + # 【关键】将 golden_output_values 追加到 actual_outputs_history,标记该 Item 已被 investigate + # 这样在渐进式暴露时,这些值才会被加入可见值集合 + # 即使是空字典(仅触发 HIDDEN_ITEM 的 Item),也要记录,以便渐进式暴露逻辑知道该 Item 已被调查 + if node.golden_output_values is not None: + node.actual_outputs_history.append(dict(node.golden_output_values)) + + # 2. Trigger Hidden Item Drops (Passive Drop) + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + logger.info(f"Item investigation successful - node: {req.node_id}, has_content: {has_actual_content}, revealed: {len(newly_revealed)}") + + # 【渐进式暴露】旧机制(基于 golden_input)已禁用 + # 现在完全由 ITEM/HIDDEN_ITEM 边触发控制节点可见性 + # 上面的 HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, node.golden_output_values or {}, node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # logger.info(f"Progressive reveal after Item investigate: {len(progressive_revealed)} nodes now ready") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Item" + } + + # 只在有实际内容时才添加 content 字段 + # 对于仅触发 HIDDEN_ITEM 掉落的 Item,不返回 content 字段,避免返回 None 或空字典让模型困惑 + if has_actual_content: + result["content"] = content + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型通过 investigate 获得内容后,需要自己识别这是否是胜利字符串 + + return result + + else: + logger.warning(f"Attempt to investigate unknown node type: {req.node_id} (type: {node.type})") + return {"ok": False, "error": f"Cannot investigate node type: {node.type}"} + +class ToolCallRequest(BaseModel): + node_id: str # 使用 node_id 精确指定要调用的节点 + arguments: Dict[str, Any] + +@app.post("/env/{case_id}/tool_call") +def tool_call(case_id: str, req: ToolCallRequest): + """Executes a tool and triggers item drops.""" + logger.info(f"Tool call request - case_id: {case_id}, node_id: {req.node_id}, args: {list(req.arguments.keys())}") + STATS["tool_calls"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + + # 通过 node_id 精确查找节点 + node_id = req.node_id + if node_id not in scenario.nodes: + logger.error(f"Node not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + tool_node = scenario.nodes[node_id] + + if not tool_node: + logger.error(f"Tool not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Tool not found") + + if not tool_node.is_revealed: + logger.warning(f"Attempt to call hidden tool: {node_id}") + return {"ok": False, "error": "Tool is not visible yet."} + + if tool_node.type != "Tool": + logger.warning(f"Attempt to call non-tool node: {node_id} (type: {tool_node.type})") + return {"ok": False, "error": "Only tools can be called."} + + # 1. Execute Tool (Real Execution via Simulator) + simulator = SIMULATORS[case_id] + + # Get tool name from template_id if available, otherwise use node name + tool_name = tool_node.name + if case_id in RAW_NODES_DATA and node_id in RAW_NODES_DATA[case_id]: + template_id = RAW_NODES_DATA[case_id][node_id].get('template_id') + if template_id: + tool_name = template_id + + # 文件处理工具和 Terminal 需要验证输入并返回预先计算的输出 + # 传递节点的实际输入输出值(从 DAG 执行后填充的数据) + tool_arguments = dict(req.arguments) # Make a copy + + # 传递节点的 golden values(从 JSON 的 inputs[].value 和 outputs[].value 加载) + # 用于在评测阶段验证被测模型传入的参数是否正确 + if tool_node.golden_input_values: + tool_arguments['_golden_inputs'] = tool_node.golden_input_values + if tool_node.golden_output_values: + tool_arguments['_golden_outputs'] = tool_node.golden_output_values + + logger.debug(f"Executing tool {tool_name} (node: {tool_node.name}) with args {tool_arguments}") + + try: + output_values = simulator.execute(tool_name, tool_arguments) + logger.info(f"Tool invoked - {tool_name}: {list(output_values.keys())}") + except Exception as e: + logger.error(f"Tool execution failed - {tool_name}: {str(e)}", exc_info=True) + return {"ok": False, "error": f"Tool execution failed: {str(e)}"} + + # 检查验证结果(精细化错误反馈) + validation = output_values.pop("_validation", {"valid": True}) + + if not validation["valid"]: + # 根据错误类型构造友好的错误消息 + error_type = validation.get("error_type") + + if error_type == "missing_required": + missing = validation.get("missing_params", []) + error_msg = f"Error: Missing required parameters {', '.join(missing)}" + + elif error_type == "type_error": + param = validation.get("param_name") + message = validation.get("message", "Parameter type error") + error_msg = f"Error: {message}" + + elif error_type == "incomplete_optional": + provided = validation.get("provided_params", []) + missing = validation.get("missing_params", []) + error_msg = ( + f"Hint: You provided some parameters ({', '.join(provided)}), " + f"but may also need: {', '.join(missing)}.\n" + f"Trying to provide these parameters together might yield better results." + ) + + elif error_type == "value_mismatch": + param = validation.get("param_name") + hint = validation.get("hint", "Parameter value may be incorrect") + error_msg = f"Hint: {hint}.\nPlease check if this parameter value meets the requirements." + + else: + error_msg = validation.get("hint") or validation.get("message", "Parameter validation failed") + + logger.info(f"Tool validation failed - {tool_name}: {error_type}") + return { + "ok": False, + "error": error_msg, + "error_type": error_type + } + + # Simulate success + tool_node.if_success = True + + # 【关键】将本次执行的输出值追加到历史列表(用于渐进式暴露判断) + # 每次调用都会记录,不会覆盖之前的执行结果 + tool_node.actual_outputs_history.append(dict(output_values)) + + # 2. 检查是否应该触发掉落(只有输入参数正确时才掉落) + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, tool_node.golden_input_values) + + newly_revealed = [] + investigate_hints = [] # 提示模型哪些节点可以 investigate 来发现隐藏内容 + + if inputs_match_golden: + logger.info(f"✓ Tool inputs match golden - node: {node_id}, triggering drops") + + # 检查该工具是否有 ITEM 或 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == tool_node.id: + target_node = scenario.nodes[edge.target_id] + + # ITEM 边:立即掉落(主动掉落) + if edge.connection_type == InterfaceType.ITEM: + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from {node_id})") + + # HIDDEN_ITEM 边:不立即掉落,标记并提示(被动掉落) + elif edge.connection_type == InterfaceType.HIDDEN_ITEM: + # 标记该工具有待触发的 HIDDEN_ITEM 掉落 + tool_node.has_hidden_item_ready = True + + # 提示模型可以 investigate 这个工具来发现隐藏内容 + hint_info = { + "tool_id": tool_node.id, + "hint": f"Tool '{tool_node.id}' seems to hide something, try investigating it to discover more information" + } + # if tool_node.name: + # hint_info["tool_name"] = tool_node.name + + investigate_hints.append(hint_info) + logger.info(f"HIDDEN_ITEM ready: {tool_node.id} -> {target_node.id} (will drop on investigate)") + else: + logger.info(f"✗ Tool inputs do NOT match golden - node: {node_id}, no drops triggered") + + response = { + "ok": True, + "message": "Tool invoked", + "output_values": output_values # Return raw outputs to Agent + } + + # 【新增】对源头节点进行参数验证反馈 + # 源头节点:没有数据流入边的节点,这些节点的参数需要模型自己推理 + # 验证模型使用的参数是否正确,并提供明确的反馈 + if _is_source_node(node_id, scenario) and tool_node.golden_input_values: + validation_feedback = _get_parameter_validation_feedback(req.arguments, tool_node.golden_input_values) + + if validation_feedback["all_correct"]: + # 用户提交了全部 golden 参数且全部正确 + response["parameter_feedback"] = { + "status": "correct", + "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." + } + logger.info(f"✓ Source node parameters all correct - node: {node_id}") + elif validation_feedback["incorrect_params"]: + # 有提交了但值错误的参数,只对这些参数给出反馈 + incorrect_list = [] + for param_name in validation_feedback["incorrect_params"]: + incorrect_list.append(f" - Parameter '{param_name}' is incorrect") + + correct_info = "" + if validation_feedback["correct_params"]: + correct_info = f"\n✓ Correct parameters: {', '.join(validation_feedback['correct_params'])}" + + response["parameter_feedback"] = { + "status": "incorrect", + "message": ( + f"⚠️ Some parameters are incorrect:\n" + + "\n".join(incorrect_list) + + correct_info + + 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." + ), + "incorrect_params": validation_feedback["incorrect_params"], + "correct_params": validation_feedback["correct_params"] + } + logger.info(f"✗ Source node parameters incorrect - node: {node_id}, incorrect: {validation_feedback['incorrect_params']}") + # else: 部分提交且全部正确 → 不给任何 parameter_feedback,避免对未提交的参数发表意见 + + # 检查工具调用是否完全正确(输出与 golden outputs 匹配) + # 用于给模型正向反馈,让它知道这个工具已经正确调用过,避免重复调用 + # 注意:只有当输出完全匹配时才标记为 correct,不会在错误时提供具体错误信息 + # if tool_node.golden_output_values and output_values: + # is_correct = True + # for port_name, expected_value in tool_node.golden_output_values.items(): + # actual_value = output_values.get(port_name) + # if str(actual_value) != str(expected_value): + # is_correct = False + # break + + # if is_correct: + # response["tool_call_correct"] = True + # logger.info(f"✓ Tool called with correct result - node: {node_id}") + + # 只在有新内容掉落时才返回 newly_revealed + if newly_revealed: + response["newly_revealed"] = newly_revealed + + # 添加 investigate 提示(对于有待触发 HIDDEN_ITEM 掉落的工具) + if investigate_hints: + response["investigate_hints"] = investigate_hints + + # 3. 渐进式暴露机制 - 现在完全由 ITEM/HIDDEN_ITEM 边控制 + # 旧机制(基于 golden_input 检查)已被禁用 + # 新机制中,节点的可见性只由 ITEM/HIDDEN_ITEM 边触发决定 + # 上面的 ITEM/HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, output_values, tool_node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # response["newly_revealed"] = newly_revealed + # logger.info(f"Progressive reveal: {len(progressive_revealed)} nodes now ready") + + # Check if this is the win node + if node_id == scenario.win_node_id: + # 验证输出值是否等于预期的胜利值 + # 从节点的 golden_output_values 中获取预期值(在 _initialize_node_values 时从 JSON 加载) + expected_outputs = tool_node.golden_output_values + + # 检查实际输出是否与预期输出匹配 + is_correct = False + victory_string = None + mismatch_info = [] + + if expected_outputs and output_values: + # 检查每个预期输出端口的值是否匹配 + is_correct = True + for port_name, expected_value in expected_outputs.items(): + actual_value = output_values.get(port_name) + if actual_value != expected_value: + is_correct = False + mismatch_info.append(f"Port '{port_name}': expected '{expected_value}', actual '{actual_value}'") + logger.warning(f"Win node output mismatch - port: {port_name}, expected: {expected_value}, actual: {actual_value}") + + # 如果所有输出都匹配,使用第一个输出作为胜利字符串 + if is_correct and output_values: + victory_string = list(output_values.values())[0] + else: + logger.warning(f"Win node called but missing output values - expected: {expected_outputs}, actual: {output_values}") + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型调用工具获得输出后,需要自己识别这是否是胜利字符串并提交 + if is_correct: + logger.info(f"🎯 Win node called with correct output - case: {case_id}, node: {node_id}, victory: {victory_string}") + else: + logger.info(f"❌ Win node called with incorrect output - case: {case_id}, node: {node_id}") + + return response + +class UseItemRequest(BaseModel): + node_id: str = Field(..., description="The ID of the Item node to use (must be Item type)") + arguments: Dict[str, Any] = Field(default_factory=dict, description="Input arguments to provide to the item") + +@app.post("/env/{case_id}/use_item") +def use_item(case_id: str, req: UseItemRequest): + """ + Use an Item node by providing input arguments. + + This is specifically for Item nodes that require parameters to be "unlocked" or "activated", + such as containers that need a password/fingerprint. + + - Validates that the node is of type Item + - Checks if provided arguments match the item's golden_input_values + - If match: triggers ITEM-type edge drops and returns the item's content + - If not match: returns error message + """ + logger.info(f"Use item request - case_id: {case_id}, node_id: {req.node_id}, args: {req.arguments}") + STATS["use_items"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + item_node = scenario.nodes[req.node_id] + + if not item_node.is_revealed: + logger.warning(f"Attempt to use hidden item: {req.node_id}") + return {"ok": False, "error": "Item is not visible yet."} + + if item_node.type != "Item": + logger.warning(f"Attempt to use non-item node: {req.node_id} (type: {item_node.type})") + return {"ok": False, "error": "Only Item nodes can be used with use_item. Tools should be called with tool_call."} + + # 【新增】检查该 Item 是否已经被成功解锁 + # 如果已经被正确使用过,直接返回成功提示 + if item_node.if_success: + logger.info(f"Item already unlocked, returning success message: {req.node_id}") + return { + "ok": True, + "message": "This item has already been successfully unlocked by you." + } + + # 检查该 Item 是否真的需要通过 use_item 提供参数 + # 只有当 Item 有非 Item/Hidden_Item 类型的输入时,才应该使用 use_item + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + non_hidden_inputs = [ + inp for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + if not non_hidden_inputs: + # 该 Item 不需要参数,应该只使用 investigate + logger.warning(f"Attempt to use_item on a node that doesn't require parameters: {req.node_id}") + return { + "ok": False, + "error": "This item does not require parameters. Please use investigate to examine the item directly." + } + + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, item_node.golden_input_values) + + if not inputs_match_golden: + logger.info(f"✗ Item inputs do NOT match golden - node: {req.node_id}") + # 提供更详细的错误信息,帮助 Agent 理解问题 + # 只显示非 Item/Hidden_Item 类型的参数(Hidden_Item 由系统自动处理) + expected_params = [] + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + expected_params = [ + inp.get("name") for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + provided_params = list(req.arguments.keys()) if req.arguments else [] + + # 检查参数名是否匹配 + if set(expected_params) == set(provided_params): + # 参数名正确但值不匹配 - 不泄漏正确的值 + error_msg = f"Parameter names are correct, but the parameter values are incorrect. Please try using different parameter values." + else: + error_msg = f"Parameter names do not match. Expected parameter names: {expected_params}, you provided: {provided_params}." + + return { + "ok": False, + "error": error_msg + } + + logger.info(f"✓ Item inputs match golden - node: {req.node_id}, activating item") + + # 标记该 Item 已被正确使用 + item_node.if_success = True + + # 将 golden_output_values 追加到 actual_outputs_history + if item_node.golden_output_values: + item_node.actual_outputs_history.append(dict(item_node.golden_output_values)) + + # 触发 ITEM 类型边的掉落 + newly_revealed = [] + for edge in scenario.edges: + if edge.source_id == item_node.id and edge.connection_type == InterfaceType.ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from use_item on {req.node_id})") + + # 检查是否为 Win Node + win_node_id = scenario.win_node_id + is_win_node = (req.node_id == win_node_id) + + # 构建返回结果 + result = { + "ok": True, + "message": "Item used successfully.", + "content": item_node.golden_output_values if item_node.golden_output_values else None + } + + # 获取 narrative(如果存在) + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + narrative = raw_nodes_data[req.node_id].get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 如果是 Win Node,只记录日志 + if is_win_node: + logger.info(f"Win node (Item) unlocked via use_item - case: {case_id}, node: {req.node_id}") + + return result + + +class SubmitAnswerRequest(BaseModel): + answer: str = Field(..., description="The victory string to submit") + +@app.post("/env/{case_id}/submit_answer") +def submit_answer(case_id: str, req: SubmitAnswerRequest): + """ + 提交答案接口 + 被测模型在获得胜利字符串提示后,需要调用此接口提交答案 + """ + logger.info(f"Submit answer request - case_id: {case_id}, answer: {req.answer}") + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + + # 获取 win_node 的 golden_output_values + if not scenario.win_node_id: + logger.error(f"No win node defined for case: {case_id}") + return { + "ok": False, + "error": "This case has no victory node defined" + } + + win_node = scenario.nodes.get(scenario.win_node_id) + if not win_node: + logger.error(f"Win node not found: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node does not exist" + } + + # 获取正确的胜利字符串(取第一个 golden_output_value) + if win_node.golden_output_values: + correct_answer = list(win_node.golden_output_values.values())[0] + else: + logger.error(f"Win node has no golden_output_values: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node has no correct answer" + } + + # 验证提交的答案 + if req.answer == correct_answer: + logger.info(f"🎉 CORRECT ANSWER SUBMITTED - case: {case_id}, answer: {req.answer}") + return { + "ok": True, + "is_win": True, + "victory_message": f"🎉 Congratulations on successfully escaping the room! Your answer is correct: {req.answer}" + } + else: + logger.info(f"❌ INCORRECT ANSWER SUBMITTED - case: {case_id}, submitted: {req.answer}, correct: {correct_answer}") + return { + "ok": True, + "is_win": False, + "error": f"The submitted answer is incorrect. You submitted: {req.answer}" + } + +if __name__ == "__main__": + + uvicorn.run(app, host="0.0.0.0", port=8000) \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-94cc40fa/environment/puzzle/upstream/simulator.py b/tasks/agentescape-25-skeleton-94cc40fa/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-25-skeleton-94cc40fa/environment/puzzle/upstream/simulator.py @@ -0,0 +1,2911 @@ +import hashlib +import hmac +import base64 +import binascii +import zlib +import json +import uuid +import math +import re +from typing import Dict, Any, List + +class ToolSimulator: + def __init__(self): + """工具模拟器 + + 文件处理工具(zip_unzip, zip_unzip_file, zip_unzip_item, json_get, csv_query, + regex_search, graph_shortest_path)不需要真实文件系统。 + 这些工具只验证输入参数,然后返回预先初始化好的 golden_outputs。 + """ + self.tool_map = { + # 数论 + "calc_bigmul": self.calc_bigmul, + "calc_modexp": self.calc_modexp, + "calc_modexp_int": self.calc_modexp_int, + "calc_gcd": self.calc_gcd, + "calc_gcd_int": self.calc_gcd_int, + "calc_inv_mod": self.calc_inv_mod, + "calc_inv_mod_int": self.calc_inv_mod_int, + + # 哈希 + "hash_sha256": self.hash_sha256, + "hash_md5": self.hash_md5, + "hmac_sha256": self.hmac_sha256, + + # 编码 + "base64_decode": self.base64_decode, + "base64_encode": self.base64_encode, + "hex_decode": self.hex_decode, + "hex_encode": self.hex_encode, + "zlib_inflate": self.zlib_inflate, + "zlib_deflate": self.zlib_deflate, + + # 文件 + "zip_unzip": self.zip_unzip, + "zip_unzip_file": self.zip_unzip_file, + "zip_unzip_item": self.zip_unzip_item, + "regex_search": self.regex_search, + "json_get": self.json_get, + "csv_query": self.csv_query, + "code_py_exec": self.code_py_exec, + + # 图 + "graph_shortest_path": self.graph_shortest_path, + + # 加解密 (简化模拟) + "crypto_aes_cbc_decrypt": self.crypto_aes_cbc_decrypt, + "crypto_rsa_decrypt_hex": self.crypto_rsa_decrypt_hex, + + # 其他 + "num_base_convert": self.num_base_convert, + "time_convert": self.time_convert, + "checksum_crc32": self.checksum_crc32, + "geo_haversine": self.geo_haversine, + "otp_totp_generate": self.otp_totp_generate, + "unicode_norm": self.unicode_norm, + "text_bidi_sanitize": self.text_bidi_sanitize, + "text_xor_hex": self.text_xor_hex, + "text_rotN": self.text_rotN, + "luhn_check": self.luhn_check, + "iban_validate": self.iban_validate, + + # 物理 + "matter_synthesizer": self.matter_synthesizer, + + # 终端机 + "terminal_1": self.terminal_1, + "terminal_2": self.terminal_2, + "Logic Terminal": self.logic_terminal, + "Math Terminal": self.math_terminal, + "Encryption Terminal": self.crypt_terminal, + "Sequence Terminal": self.sequence_terminal + } + + def execute(self, tool_name: str, inputs: Dict[str, Any]) -> Dict[str, Any]: + if tool_name not in self.tool_map: + # Fallback for unknown tools: return dummy outputs based on expected output types + # This should ideally not happen if all tools are implemented + return {} + + try: + return self.tool_map[tool_name](inputs) + except Exception as e: + print(f"Error executing {tool_name}: {e}") + # Return empty or error indication? For generation, we might want to fail hard or return dummy. + # For now, return dummy to keep flow going, but log error. + return {} + + # --- Implementations --- + + def calc_bigmul(self, inputs): + # Check if required parameters are present + if "a" not in inputs or "b" not in inputs: + raise ValueError("Missing required parameters 'a' and/or 'b'") + + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + return {"product": str(a * b)} + except (ValueError, TypeError) as e: + raise ValueError(f"Failed to convert parameters to integers: {str(e)}") + + def calc_modexp(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + try: + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if isinstance(base, str): + base = int(base) + elif not isinstance(base, int): + raise ValueError("Parameter 'base' must be a string or integer") + + if isinstance(exp, str): + exp = int(exp) + elif not isinstance(exp, int): + raise ValueError("Parameter 'exp' must be a string or integer") + + if isinstance(mod, str): + mod = int(mod) + elif not isinstance(mod, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": str(pow(base, exp, mod))} + + def calc_modexp_int(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["base"], int): + raise ValueError("Parameter 'base' must be an integer") + if not isinstance(inputs["exp"], int): + raise ValueError("Parameter 'exp' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": pow(base, exp, mod)} + + def calc_gcd(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + # 计算 GCD 并返回字符串格式(符合 Big_Int 输出类型) + result = math.gcd(a, b) + return {"gcd": str(result)} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def calc_gcd_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["b"], int): + raise ValueError("Parameter 'b' must be an integer") + + # 获取参数 + a = inputs["a"] + b = inputs["b"] + + return {"gcd": math.gcd(a, b)} + + def calc_inv_mod(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + m = inputs["mod"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(m, str): + m = int(m) + elif not isinstance(m, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": str(pow(a, -1, m))} + except ValueError as e: + # 模逆不存在时,返回一个特殊值(用于数据传递) + # 在 DAG 生成阶段,这允许数据流继续 + return {"inv": str(a)} + + def calc_inv_mod_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + a = inputs["a"] + m = inputs["mod"] + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": pow(a, -1, m)} + except ValueError as e: + raise ValueError(f"Modular inverse does not exist: {str(e)}") + + def hash_sha256(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.sha256(text.encode()).hexdigest()} + + def hash_md5(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.md5(text.encode()).hexdigest()} + + def hmac_sha256(self, inputs): + # 参数检查 + if "hex_key" not in inputs: + raise ValueError("Missing required parameter: hex_key") + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["hex_key"], str): + raise ValueError("Parameter 'hex_key' must be a string") + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + try: + key = bytes.fromhex(inputs["hex_key"]) + text = inputs["text"].encode() + return {"hex": hmac.new(key, text, hashlib.sha256).hexdigest()} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def base64_decode(self, inputs): + # 参数检查 + if "data" not in inputs: + raise ValueError("Missing required parameter: data") + + # 类型检查 + if not isinstance(inputs["data"], str): + raise ValueError("Parameter 'data' must be a string") + + data = inputs["data"] + try: + return {"bytes_hex": binascii.hexlify(base64.b64decode(data)).decode()} + except Exception as e: + raise ValueError(f"Base64 decode error: {str(e)}") + + def base64_encode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"b64": base64.b64encode(bytes.fromhex(hex_data)).decode()} + except Exception as e: + raise ValueError(f"Base64 encode error: {str(e)}") + + def hex_decode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"text": bytes.fromhex(hex_data).decode('utf-8', errors='ignore')} + except Exception as e: + raise ValueError(f"Hex decode error: {str(e)}") + + def hex_encode(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + try: + return {"hex": text.encode().hex()} + except Exception as e: + raise ValueError(f"Hex encode error: {str(e)}") + + + # 到此处实现已经更新 + + def zlib_inflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("Parameter 'hex' must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("Missing required parameter: hex") + + try: + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空字符串 + if not hex_data: + raise ValueError("Empty hex string provided") + + # 检查十六进制字符串的有效性 + if len(hex_data) % 2 != 0: + raise ValueError("Hex string must have even length") + + # 检查是否只包含有效的十六进制字符 + if not all(c in '0123456789abcdefABCDEF' for c in hex_data): + raise ValueError("Invalid hex string provided") + + # 尝试解压缩 + return {"text": zlib.decompress(bytes.fromhex(hex_data)).decode('utf-8')} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hex string provided") from e + raise ValueError(f"Invalid zlib data: {e}") from e + except Exception as e: + raise RuntimeError(f"Failed to inflate data: {e}") from e + + def zlib_deflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("Parameter 'text' must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("Missing required parameter: text") + + try: + # 压缩文本 + return {"hex": zlib.compress(text.encode('utf-8')).hex()} + except Exception as e: + raise RuntimeError(f"Failed to deflate data: {e}") from e + + # --- File Operations --- + + def zip_unzip(self, inputs): + """ZIP 解压工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"files": golden_outputs.get("files", "")} + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return {"files": golden_outputs.get("files", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "files" in golden_outputs: + # 验证必需参数 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 检查类型 + if has_zip_id and not isinstance(zip_id, str): + return {"error": "Parameter 'zip_id' must be a string type"} + if has_password and not isinstance(password, str): + return {"error": "Parameter 'password' must be a string type"} + + # 验证输入是否与预期匹配 + if golden_inputs: + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return {"files": golden_outputs["files"]} + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + # 没有golden_inputs但有golden_outputs,直接返回输出 + return {"files": golden_outputs["files"]} + + # 如果没有预期输出,返回空结果 + return {"files": ""} + + def regex_search(self, inputs): + """正则搜索工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"matches": golden_outputs.get("matches", "[]")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "matches" in golden_outputs: + # 提取实际参数 + pattern = inputs.get("pattern") + file_id = inputs.get("file_id") + text = inputs.get("text") + + # 1. 检查必需参数 + if pattern is None: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["pattern"], + "message": "Missing required parameter 'pattern'" + } + } + + # 类型检查 + if not isinstance(pattern, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "pattern", + "message": "Parameter 'pattern' must be a string type" + } + } + if file_id is not None and not isinstance(file_id, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if text is not None and not isinstance(text, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "text", + "message": "Parameter 'text' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合 + provided_params = {} + if pattern is not None: + provided_params["pattern"] = pattern + if file_id is not None: + provided_params["file_id"] = file_id + if text is not None: + provided_params["text"] = text + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数(关键改进) + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_pattern = golden_inputs.get("pattern") + expected_file_id = golden_inputs.get("file_id") + expected_text = golden_inputs.get("text") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_pattern is not None: + if str(pattern) != str(expected_pattern): + incorrect_params.append("pattern") + else: + correct_params.append("pattern") + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_text is not None: + if str(text) != str(expected_text): + incorrect_params.append("text") + else: + correct_params.append("text") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "matches": "[]", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "matches": golden_outputs["matches"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空列表 + return {"matches": "[]"} + + def json_get(self, inputs): + """JSON 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"values": golden_outputs.get("values", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "values" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + jsonpath = inputs.get("jsonpath", "") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if jsonpath is not None and not isinstance(jsonpath, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "jsonpath", + "message": "Parameter 'jsonpath' must be a string type" + } + } + + # 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:jsonpath有默认值"") + provided_params = {} + if file_id is not None: + provided_params["file_id"] = file_id + if jsonpath != "": + provided_params["jsonpath"] = jsonpath + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_jsonpath = golden_inputs.get("jsonpath") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_jsonpath is not None: + if str(jsonpath) != str(expected_jsonpath): + incorrect_params.append("jsonpath") + else: + correct_params.append("jsonpath") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "values": "", + "_validation": validation_info + } + + # 所有验证通过,返回正确输出 + return { + "values": golden_outputs["values"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"values": ""} + + def csv_query(self, inputs): + """CSV 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"rows": golden_outputs.get("rows", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "rows" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + select_columns = inputs.get("select", "") + where_clause = inputs.get("where", "") + + # 1. 检查必需参数 + if file_id is None: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["file_id"], + "message": "Missing required parameter 'file_id'" + } + } + + # 类型检查 + if not isinstance(file_id, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if not isinstance(select_columns, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "select", + "message": "Parameter 'select' must be a string type" + } + } + if not isinstance(where_clause, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "where", + "message": "Parameter 'where' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:select和where有默认值"") + provided_params = {"file_id": file_id} + if select_columns != "": + provided_params["select"] = select_columns + if where_clause != "": + provided_params["where"] = where_clause + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_select = golden_inputs.get("select") + expected_where = golden_inputs.get("where") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_select is not None: + if str(select_columns) != str(expected_select): + incorrect_params.append("select") + else: + correct_params.append("select") + + if expected_where is not None: + if str(where_clause) != str(expected_where): + incorrect_params.append("where") + else: + correct_params.append("where") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "rows": "", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "rows": golden_outputs["rows"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"rows": ""} + + def graph_shortest_path(self, inputs): + """图最短路径工具 + + 如果有 _golden_outputs 或 _init_outputs,验证输入并返回预设输出。 + 否则执行真实的 Dijkstra 算法。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 检查是否在预设模式中(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + if golden_outputs and "path" in golden_outputs: + # 评测阶段但没有 golden_inputs,直接返回 outputs + if not golden_inputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 评测模式:验证输入参数是否匹配 golden 值 + src = inputs.get("src") + dst = inputs.get("dst") + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + + has_src = src is not None and src != "" + has_dst = dst is not None and dst != "" + + # 验证必需参数 + if not has_src or not has_dst: + missing = [] + if not has_src: + missing.append("src") + if not has_dst: + missing.append("dst") + return {"error": "Missing required parameters: " + ", ".join(missing)} + + # 类型检查 + if not isinstance(src, str): + return {"error": "Parameter 'src' must be a string"} + if not isinstance(dst, str): + return {"error": "Parameter 'dst' must be a string"} + + # 验证输入是否匹配期望值 + if golden_inputs: + expected_src = golden_inputs.get("src") + expected_dst = golden_inputs.get("dst") + expected_file_id = golden_inputs.get("file_id") + expected_graph_data = golden_inputs.get("graph_data") + + # 收集验证结果 + incorrect_params = [] + correct_params = [] + + # 检查必需参数是否匹配 + if expected_src is not None: + if str(src) != str(expected_src): + incorrect_params.append("src") + else: + correct_params.append("src") + + if expected_dst is not None: + if str(dst) != str(expected_dst): + incorrect_params.append("dst") + else: + correct_params.append("dst") + + # 检查可选参数(如果在 expected_inputs 中定义了) + if expected_file_id is not None: + if file_id != expected_file_id: + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_graph_data is not None: + if graph_data != expected_graph_data: + incorrect_params.append("graph_data") + else: + correct_params.append("graph_data") + + # 如果有参数不正确,返回详细的反馈 + if incorrect_params: + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 验证通过,返回预设的输出 + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 获取参数(真实执行路径) + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + # Support both src/dst (interface definition) and start/end (original implementation) + start = inputs.get("src") + end = inputs.get("dst") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + raise TypeError("file_id must be a string") + + if graph_data is not None and not isinstance(graph_data, str): + raise TypeError("graph_data must be a string") + + if start is not None and not isinstance(start, str): + raise TypeError("src/start must be a string") + + if end is not None and not isinstance(end, str): + raise TypeError("dst/end must be a string") + + # 检查必需参数 + if file_id is None and graph_data is None: + raise ValueError("Either file_id or graph_data must be provided") + + if start is None: + raise ValueError("src/start parameter is required") + + if end is None: + raise ValueError("dst/end parameter is required") + + # Get graph content + content = None + if file_id is not None: + # 尝试从 VFS 获取(如果存在) + if hasattr(self, 'vfs') and file_id in self.vfs: + content = self.vfs[file_id] + else: + # VFS 不存在或文件不在 VFS 中 + # 返回一个默认的空图结果,或者抛出错误提示需要 init_outputs + raise ValueError( + f"File '{file_id}' not found. For tools that require files, " + f"please provide init_outputs in the initial_values." + ) + elif graph_data is not None: + content = graph_data + + if content is None: + content = "{}" + + try: + # Parse graph data + graph = json.loads(content) + + # 类型检查 + if not isinstance(graph, dict): + raise TypeError("Graph data must be a dictionary") + + # If graph is not in the expected format, try to extract adjacency list + if "nodes" in graph and "edges" in graph: + # 验证nodes和edges的类型 + if not isinstance(graph["nodes"], list): + raise TypeError("Nodes must be a list") + + if not isinstance(graph["edges"], list): + raise TypeError("Edges must be a list") + + # Convert from nodes/edges format to adjacency list + adjacency_list = {} + for node in graph["nodes"]: + # 验证node类型 + if not isinstance(node, dict): + raise TypeError("Each node must be a dictionary") + + # Use node ID as key, not the entire node dictionary + node_id = node.get("id", "") + if node_id: + adjacency_list[node_id] = {} + + for edge in graph["edges"]: + # 验证edge类型 + if not isinstance(edge, dict): + raise TypeError("Each edge must be a dictionary") + + u = edge["from"] + v = edge["to"] + weight = edge.get("weight", 1) # Default to unweighted + + # 类型检查 + if not isinstance(u, str): + raise TypeError("Edge 'from' must be a string") + + if not isinstance(v, str): + raise TypeError("Edge 'to' must be a string") + + if not isinstance(weight, (int, float)): + raise TypeError("Edge weight must be a number") + + if u not in adjacency_list: + adjacency_list[u] = {} + if v not in adjacency_list: + adjacency_list[v] = {} + + adjacency_list[u][v] = weight + # If undirected, add reverse edge + if not edge.get("directed", False): + adjacency_list[v][u] = weight + elif isinstance(graph, dict): + # Already in adjacency list format + adjacency_list = graph + + # 验证邻接表结构 + for node, neighbors in adjacency_list.items(): + if not isinstance(neighbors, dict): + raise TypeError("Adjacency list must be a dictionary of dictionaries") + + for neighbor, weight in neighbors.items(): + if not isinstance(weight, (int, float)): + raise TypeError("Edge weights must be numbers") + else: + raise TypeError("Graph data must be a dictionary") + + # 检查起点和终点是否为空 + if not start: + raise ValueError("Start node cannot be empty") + + if not end: + raise ValueError("End node cannot be empty") + + # 检查起点和终点是否在图中 + if start not in adjacency_list: + raise ValueError(f"Start node '{start}' not found in graph") + + if end not in adjacency_list: + raise ValueError(f"End node '{end}' not found in graph") + + # Dijkstra's algorithm implementation + import heapq + + # Initialize distances and previous nodes + distances = {node: float('infinity') for node in adjacency_list} + previous = {node: None for node in adjacency_list} + distances[start] = 0 + + # Priority queue + pq = [(0, start)] + heapq.heapify(pq) + + while pq: + current_dist, current_node = heapq.heappop(pq) + + # If we've reached the end node, we can break early + if current_node == end: + break + + # Nodes can be added multiple times to the priority queue, but we only process them once + if current_dist > distances[current_node]: + continue + + # Explore neighbors + for neighbor, weight in adjacency_list[current_node].items(): + distance = current_dist + weight + + # If a shorter path is found + if distance < distances[neighbor]: + distances[neighbor] = distance + previous[neighbor] = current_node + heapq.heappush(pq, (distance, neighbor)) + + # Reconstruct the shortest path + path = [] + current = end + while current is not None: + path.append(current) + current = previous[current] + path.reverse() # Reverse to get from start to end + + # Check if path exists + if not path or path[0] != start: + return {"path": "[]", "cost": 0} + + return { + "path": json.dumps(path), + "cost": distances[end] + } + except json.JSONDecodeError as e: + raise ValueError(f"Invalid JSON in graph data: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in graph_shortest_path: {str(e)}") + + # --- Crypto (Simplified) --- + def crypto_aes_cbc_decrypt(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 (使用模板中定义的参数名) + hex_cipher = inputs.get("hex_cipher") + hex_key = inputs.get("hex_key") + hex_iv = inputs.get("hex_iv") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + + if hex_key is not None and not isinstance(hex_key, str): + raise TypeError("hex_key must be a string") + + if hex_iv is not None and not isinstance(hex_iv, str): + raise TypeError("hex_iv must be a string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + + if hex_key is None: + raise ValueError("hex_key parameter is required") + + if hex_iv is None: + raise ValueError("hex_iv parameter is required") + + from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes + from cryptography.hazmat.backends import default_backend + from cryptography.hazmat.primitives import padding + + try: + # Convert hex strings to bytes + ciphertext = bytes.fromhex(hex_cipher) + key = bytes.fromhex(hex_key) + iv = bytes.fromhex(hex_iv) + + # Validate key length (AES-128, AES-192, AES-256) + if len(key) not in [16, 24, 32]: + raise ValueError("Invalid key length. Must be 16, 24, or 32 bytes.") + + if len(iv) != 16: + raise ValueError("Invalid IV length. Must be 16 bytes.") + + # Create cipher object + cipher = Cipher( + algorithms.AES(key), + modes.CBC(iv), + backend=default_backend() + ) + + decryptor = cipher.decryptor() + + # Decrypt the ciphertext + padded_plaintext = decryptor.update(ciphertext) + decryptor.finalize() + + # Remove PKCS7 padding + unpadder = padding.PKCS7(128).unpadder() + plaintext = unpadder.update(padded_plaintext) + unpadder.finalize() + + # Return decrypted text + return {"text": plaintext.decode('utf-8', errors='ignore')} + except ValueError as e: + if "non-hexadecimal number found in fromhex()" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher, hex_key, or hex_iv") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in crypto_aes_cbc_decrypt: {str(e)}") + + def crypto_rsa_decrypt_hex(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_cipher = inputs.get("hex_cipher") + n = inputs.get("n") + d = inputs.get("d") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + if n is not None and not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + if d is not None and not isinstance(d, (int, str)): + raise TypeError("d must be an integer or string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + if n is None: + raise ValueError("n parameter is required") + if d is None: + raise ValueError("d parameter is required") + + try: + # Convert parameters to appropriate types + cipher_int = int(hex_cipher, 16) + n_int = int(n) if isinstance(n, str) else n + d_int = int(d) if isinstance(d, str) else d + + # RSA decryption: plaintext = ciphertext^d mod n + plaintext_int = pow(cipher_int, d_int, n_int) + + # Convert result to hex and then to text + plaintext_hex = hex(plaintext_int)[2:] + + # Pad with leading zero if odd length + if len(plaintext_hex) % 2 != 0: + plaintext_hex = '0' + plaintext_hex + + # Convert hex to bytes and then to text + try: + plaintext_bytes = bytes.fromhex(plaintext_hex) + plaintext_text = plaintext_bytes.decode('utf-8', errors='ignore') + except: + # If decoding fails, return hex representation + plaintext_text = plaintext_hex + + return {"text": plaintext_text} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in crypto_rsa_decrypt_hex: {str(e)}") + + # --- Others --- + def num_base_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + s = inputs.get("s") + from_base = inputs.get("from_base") + to_base = inputs.get("to_base") + + # 类型检查 - 接受 str 或 int + if s is not None and not isinstance(s, (str, int)): + raise TypeError("s must be a string or integer") + + if from_base is not None and not isinstance(from_base, (int, str)): + raise TypeError("from_base must be an integer") + + if to_base is not None and not isinstance(to_base, (int, str)): + raise TypeError("to_base must be an integer") + + # 检查必需参数 + if s is None: + raise ValueError("s parameter is required") + + if from_base is None: + raise ValueError("from_base parameter is required") + + if to_base is None: + raise ValueError("to_base parameter is required") + + try: + # Convert to int if needed + from_base = int(from_base) if isinstance(from_base, str) else from_base + to_base = int(to_base) if isinstance(to_base, str) else to_base + s_str = str(s) + + # 验证基数范围 + if from_base < 2 or from_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + if to_base < 2 or to_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + # Convert from source base to decimal + val = int(s_str, from_base) + + # Convert from decimal to target base + if to_base == 10: + result = str(val) + elif to_base == 16: + result = hex(val)[2:] + elif to_base == 8: + result = oct(val)[2:] + elif to_base == 2: + result = bin(val)[2:] + else: + # Generic base conversion for other bases + if val == 0: + result = "0" + else: + digits = "0123456789abcdefghijklmnopqrstuvwxyz" + result = "" + n = abs(val) + while n: + result = digits[n % to_base] + result + n //= to_base + if val < 0: + result = "-" + result + + return {"str": result} + except ValueError as e: + raise ValueError(f"Invalid number format: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in num_base_convert: {str(e)}") + + def time_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iso = inputs.get("iso") + timestamp = inputs.get("timestamp") + datetime_str = inputs.get("datetime") + from_tz = inputs.get("from_tz") + to_tz = inputs.get("to_tz") + format_str = inputs.get("format") + + # 类型检查 + if iso is not None and not isinstance(iso, str): + raise TypeError("iso must be a string") + + if timestamp is not None and not isinstance(timestamp, (str, int, float)): + raise TypeError("timestamp must be a string, integer, or float") + + if datetime_str is not None and not isinstance(datetime_str, str): + raise TypeError("datetime must be a string") + + if from_tz is not None and not isinstance(from_tz, str): + raise TypeError("from_tz must be a string") + + if to_tz is not None and not isinstance(to_tz, str): + raise TypeError("to_tz must be a string") + + if format_str is not None and not isinstance(format_str, str): + raise TypeError("format must be a string") + + # 设置默认值 + if from_tz is None: + from_tz = "UTC" + + if to_tz is None: + to_tz = "UTC" + + import datetime + import pytz + + # 验证时区参数 + try: + if from_tz: + pytz.timezone(from_tz) + if to_tz: + pytz.timezone(to_tz) + except Exception: + raise ValueError("Invalid timezone provided") + + try: + # Parse input time + dt = None + + if iso is not None: + # Parse ISO 8601 format + dt = datetime.datetime.fromisoformat(iso.replace('Z', '+00:00')) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=pytz.UTC) + elif timestamp is not None: + # Parse Unix timestamp + timestamp = float(timestamp) + dt = datetime.datetime.fromtimestamp(timestamp, pytz.UTC) + elif datetime_str is not None: + # Parse datetime string + # Try common formats + formats_to_try = [ + "%Y-%m-%d %H:%M:%S", + "%Y-%m-%d %H:%M:%S.%f", + "%Y-%m-%d", + "%m/%d/%Y %H:%M:%S", + "%m/%d/%Y" + ] + + parse_success = False + for fmt in formats_to_try: + try: + dt = datetime.datetime.strptime(datetime_str, fmt) + dt = pytz.timezone(from_tz).localize(dt) + parse_success = True + break + except ValueError: + continue + + if not parse_success: + raise ValueError("Unable to parse datetime string with common formats") + else: + # 如果没有提供任何时间参数,则使用当前时间 + dt = datetime.datetime.now(pytz.UTC) + except ValueError as e: + raise ValueError(f"Error parsing time input: {str(e)}") + except Exception as e: + raise RuntimeError(f"Unexpected error parsing time input: {str(e)}") + + try: + # Convert timezone + if from_tz != to_tz: + dt = dt.astimezone(pytz.timezone(to_tz)) + + # Format outputs + result = { + "iso": dt.isoformat(), + "timestamp": str(dt.timestamp()), + "datetime": dt.strftime("%Y-%m-%d %H:%M:%S"), + "date": dt.strftime("%Y-%m-%d"), + "time": dt.strftime("%H:%M:%S"), + "timezone": to_tz + } + + # Add custom format if requested + if format_str: + try: + result["formatted"] = dt.strftime(format_str) + except ValueError as e: + raise ValueError(f"Invalid format string: {str(e)}") + + return result + except Exception as e: + raise RuntimeError(f"Error in time_convert: {str(e)}") + + def checksum_crc32(self, inputs): + import zlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("hex must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("hex parameter is required") + + try: + # 验证十六进制字符串 + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空 + if not hex_data: + raise ValueError("hex data cannot be empty") + + # 检查是否为有效的十六进制字符串 + if not all(c in "0123456789abcdefABCDEF" for c in hex_data): + raise ValueError("hex must be a valid hexadecimal string") + + # 检查长度是否为偶数 + if len(hex_data) % 2 != 0: + raise ValueError("hex must have even number of characters") + + val = zlib.crc32(bytes.fromhex(hex_data)) + # 确保 hex 输出是 8 位,前导补 0 + return {"hex": f"{val:08x}", "int": val} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in checksum_crc32: {str(e)}") + + def geo_haversine(self, inputs): + import math + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + lat1 = inputs.get("lat1") + lon1 = inputs.get("lon1") + lat2 = inputs.get("lat2") + lon2 = inputs.get("lon2") + + # 类型检查 + if lat1 is not None and not isinstance(lat1, (int, float, str)): + raise TypeError("lat1 must be a number or string") + if lon1 is not None and not isinstance(lon1, (int, float, str)): + raise TypeError("lon1 must be a number or string") + if lat2 is not None and not isinstance(lat2, (int, float, str)): + raise TypeError("lat2 must be a number or string") + if lon2 is not None and not isinstance(lon2, (int, float, str)): + raise TypeError("lon2 must be a number or string") + + # 检查必需参数 + if lat1 is None: + raise ValueError("lat1 parameter is required") + if lon1 is None: + raise ValueError("lon1 parameter is required") + if lat2 is None: + raise ValueError("lat2 parameter is required") + if lon2 is None: + raise ValueError("lon2 parameter is required") + + try: + # 转换为浮点数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(lat1, str): + lat1 = float(lat1) + elif not isinstance(lat1, (int, float)): + raise TypeError("lat1 must be a number or string") + else: + lat1 = float(lat1) + + if isinstance(lon1, str): + lon1 = float(lon1) + elif not isinstance(lon1, (int, float)): + raise TypeError("lon1 must be a number or string") + else: + lon1 = float(lon1) + + if isinstance(lat2, str): + lat2 = float(lat2) + elif not isinstance(lat2, (int, float)): + raise TypeError("lat2 must be a number or string") + else: + lat2 = float(lat2) + + if isinstance(lon2, str): + lon2 = float(lon2) + elif not isinstance(lon2, (int, float)): + raise TypeError("lon2 must be a number or string") + else: + lon2 = float(lon2) + + # Validate coordinates (approximate range check) + if not (-90 <= lat1 <= 90): + raise ValueError("lat1 must be between -90 and 90") + if not (-90 <= lat2 <= 90): + raise ValueError("lat2 must be between -90 and 90") + if not (-180 <= lon1 <= 180): + raise ValueError("lon1 must be between -180 and 180") + if not (-180 <= lon2 <= 180): + raise ValueError("lon2 must be between -180 and 180") + + # Earth radius in meters + R = 6371000 # Approximate radius of Earth + + # Convert degrees to radians + lat1_rad = math.radians(lat1) + lon1_rad = math.radians(lon1) + lat2_rad = math.radians(lat2) + lon2_rad = math.radians(lon2) + + # Calculate differences + delta_lat = lat2_rad - lat1_rad + delta_lon = lon2_rad - lon1_rad + + # Haversine formula + a = math.sin(delta_lat / 2) ** 2 + \ + math.cos(lat1_rad) * math.cos(lat2_rad) * \ + math.sin(delta_lon / 2) ** 2 + c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) + distance_m = R * c + + # Return distance in meters + return {"meters": round(distance_m, 2)} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in geo_haversine: {str(e)}") + + def otp_totp_generate(self, inputs): + import hmac + import hashlib + import base64 + import time + import struct + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + base32_secret = inputs.get("base32_secret") + step = inputs.get("step", 30) # Default to 30 seconds + digits = inputs.get("digits", 6) # Default to 6 digits + timestamp_iso = inputs.get("timestamp_iso", "") + algo = inputs.get("algo", "sha1") # Default to sha1 as current implementation only supports this + + # 类型检查 + if base32_secret is not None and not isinstance(base32_secret, str): + raise TypeError("base32_secret must be a string") + if not isinstance(step, (int, str)): + raise TypeError("step must be an integer or string") + if not isinstance(digits, (int, str)): + raise TypeError("digits must be an integer or string") + if not isinstance(timestamp_iso, str): + raise TypeError("timestamp_iso must be a string") + if not isinstance(algo, str): + raise TypeError("algo must be a string") + + # 检查必需参数 + if base32_secret is None: + raise ValueError("base32_secret parameter is required") + + try: + # Convert step and digits to appropriate types + step = int(step) + digits = int(digits) + if digits < 6 or digits > 8: + raise ValueError("Digits must be between 6 and 8") + + # Convert timestamp_iso to integer timestamp + if timestamp_iso: + import datetime + dt = datetime.datetime.fromisoformat(timestamp_iso.replace('Z', '+00:00')) + timestamp = int(dt.timestamp()) + else: + timestamp = int(time.time()) + + # Calculate counter value (T = floor(timestamp / step)) + counter = timestamp // step + + # Decode the base32 secret + # Add padding if necessary (base64 requires padding to be multiple of 8) + base32_secret = base32_secret.upper().replace(' ', '') + if len(base32_secret) % 8 != 0: + base32_secret += '=' * (8 - (len(base32_secret) % 8)) + key = base64.b32decode(base32_secret, casefold=True) + + # Calculate HMAC-SHA1 + counter_bytes = struct.pack('>Q', counter) # Big-endian 8-byte integer + hmac_hash = hmac.new(key, counter_bytes, hashlib.sha1).digest() + + # Dynamic truncation + offset = hmac_hash[-1] & 0xF + code = struct.unpack('>I', hmac_hash[offset:offset+4])[0] & 0x7FFFFFFF + + # Generate the OTP + otp = str(code % (10 ** digits)).zfill(digits) + + # Calculate remaining time until next OTP change + remaining_time = step - (timestamp % step) + + return {"totp": otp, "remaining_time": remaining_time, "time_step": step} + except ValueError as e: + if "invalid literal for int()" in str(e): + raise ValueError("step and digits must be valid integers") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in otp_totp_generate: {str(e)}") + + def unicode_norm(self, inputs): + import unicodedata + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + form = inputs.get("form", "NFC") # Default to NFC + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if form is not None and not isinstance(form, str): + raise TypeError("form must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Normalize form (NFC, NFD, NFKC, NFKD) + form = form.upper().strip() + + if form not in ['NFC', 'NFD', 'NFKC', 'NFKD']: + raise ValueError(f"Invalid normalization form: {form}. Must be one of: NFC, NFD, NFKC, NFKD") + + # Apply Unicode normalization + normalized_text = unicodedata.normalize(form, text) + + return {"text": normalized_text} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in unicode_norm: {str(e)}") + + def text_bidi_sanitize(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Bidi control characters to remove + bidi_controls = [ + '\u200E', # LEFT-TO-RIGHT MARK + '\u200F', # RIGHT-TO-LEFT MARK + '\u202A', # LEFT-TO-RIGHT EMBEDDING + '\u202B', # RIGHT-TO-LEFT EMBEDDING + '\u202C', # POP DIRECTIONAL FORMATTING + '\u202D', # LEFT-TO-RIGHT OVERRIDE + '\u202E', # RIGHT-TO-LEFT OVERRIDE + '\u2066', # LEFT-TO-RIGHT ISOLATE + '\u2067', # RIGHT-TO-LEFT ISOLATE + '\u2068', # FIRST STRONG ISOLATE + '\u2069', # POP DIRECTIONAL ISOLATE + ] + + # Remove all Bidi control characters + sanitized_text = text + for control_char in bidi_controls: + sanitized_text = sanitized_text.replace(control_char, '') + + return {"text": sanitized_text} + except Exception as e: + raise RuntimeError(f"Error in text_bidi_sanitize: {str(e)}") + + def text_xor_hex(self, inputs): + import binascii + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_a = inputs.get("hex_a") + hex_b = inputs.get("hex_b") + + # 类型检查 + if hex_a is not None and not isinstance(hex_a, str): + raise TypeError("hex_a must be a string") + if hex_b is not None and not isinstance(hex_b, str): + raise TypeError("hex_b must be a string") + + # 检查必需参数 + if hex_a is None: + raise ValueError("hex_a parameter is required") + if hex_b is None: + raise ValueError("hex_b parameter is required") + + try: + # Remove any whitespace + hex_a = hex_a.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + hex_b = hex_b.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + + # Validate hex strings + if not (all(c in "0123456789abcdefABCDEF" for c in hex_a) and len(hex_a) % 2 == 0): + raise ValueError("hex_a must be a valid hexadecimal string with even length") + if not (all(c in "0123456789abcdefABCDEF" for c in hex_b) and len(hex_b) % 2 == 0): + raise ValueError("hex_b must be a valid hexadecimal string with even length") + + # Convert hex strings to bytes + bytes_a = binascii.unhexlify(hex_a) + bytes_b = binascii.unhexlify(hex_b) + + # Make the byte arrays the same length by padding the shorter one with zeros + max_len = max(len(bytes_a), len(bytes_b)) + bytes_a = bytes_a.ljust(max_len, b'\x00') + bytes_b = bytes_b.ljust(max_len, b'\x00') + + # Perform XOR operation + result_bytes = bytes(a ^ b for a, b in zip(bytes_a, bytes_b)) + + # Convert result back to hex + result_hex = binascii.hexlify(result_bytes).decode('utf-8') + + return {"hex": result_hex} + except ValueError as e: + if "Non-hexadecimal digit found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in text_xor_hex: {str(e)}") + + def text_rotN(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + n = inputs.get("n", 0) + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + n = int(n) + except ValueError: + raise ValueError("n must be a valid integer") + + result = [] + for char in text: + if char.isupper(): + # Rotate uppercase letters + result_char = chr((ord(char) - ord('A') + n) % 26 + ord('A')) + result.append(result_char) + elif char.islower(): + # Rotate lowercase letters + result_char = chr((ord(char) - ord('a') + n) % 26 + ord('a')) + result.append(result_char) + else: + # Keep non-alphabetic characters unchanged + result.append(char) + + return {"text": ''.join(result)} + + def luhn_check(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数(支持 card_number 和 number 两个参数名) + card_number = inputs.get("number") or inputs.get("card_number") + + # 类型检查 + if card_number is not None and not isinstance(card_number, str): + raise TypeError("number must be a string") + + # 检查必需参数 + if card_number is None: + raise ValueError("number parameter is required") + + try: + # 如果输入是JSON数组或其他非数字字符串,返回该字符串本身(用于数据传递) + # 这种情况发生在DAG设计中类型不匹配时 + if card_number.startswith('[') or card_number.startswith('{'): + # 输入是JSON,直接返回原值(用于传递) + return {"valid": card_number} + + # Remove whitespace from card number + card_number = card_number.replace(" ", "").replace("-", "") + + # Check if card number is all digits + if not card_number.isdigit() or len(card_number) < 13: + return {"valid": "false"} + + # Implement Luhn algorithm + total = 0 + reverse_digits = card_number[::-1] # Reverse the number for easier processing + + for i, digit in enumerate(reverse_digits): + num = int(digit) + if i % 2 == 1: # Every second digit starting from the right (which is first in reversed string) + num *= 2 + if num > 9: + num -= 9 # Equivalent to sum of digits for 2-digit numbers + total += num + + # Check if total is divisible by 10 + is_valid = total % 10 == 0 + return {"valid": "true" if is_valid else "false"} + except Exception as e: + raise RuntimeError(f"Error in luhn_check: {str(e)}") + + def iban_validate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iban = inputs.get("iban") + + # 类型检查 + if iban is not None and not isinstance(iban, str): + raise TypeError("iban must be a string") + + # 检查必需参数 + if iban is None: + raise ValueError("iban parameter is required") + + try: + # Remove whitespace from IBAN + iban = iban.replace(" ", "") + + # Basic length and format check + if not (len(iban) >= 15 and len(iban) <= 34): + return {"valid": "False"} + + if not (iban[:2].isalpha() and iban[2:].isdigit()): + return {"valid": "False"} + + # Move first four characters to the end + rearranged = iban[4:] + iban[:4] + + # Replace letters with numbers (A=10, B=11, ..., Z=35) + numeric_iban = '' + for char in rearranged: + if char.isdigit(): + numeric_iban += char + else: + numeric_iban += str(ord(char.upper()) - ord('A') + 10) + + # Perform modulo 97 check + # Use step-by-step approach for very large numbers + remainder = 0 + for char in numeric_iban: + remainder = (remainder * 10 + int(char)) % 97 + + is_valid = remainder == 1 + return {"valid": "True" if is_valid else "False"} + except Exception as e: + raise RuntimeError(f"Error in iban_validate: {str(e)}") + + def matter_synthesizer(self, inputs): + import hashlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + blueprint = inputs.get("blueprint") + + # 类型检查 + if blueprint is not None and not isinstance(blueprint, str): + raise TypeError("blueprint must be a string") + + try: + # Get blueprint parameter as defined in interface + if blueprint is None: + blueprint = "" + + # Generate a unique item ID based on the blueprint + # This ensures the same blueprint always produces the same item + blueprint_hash = hashlib.sha256(blueprint.encode()).hexdigest()[:16] + + # Create a synthesized item with a deterministic ID based on blueprint + synthesized_item = f"synthesized_item_{blueprint_hash}" + + return {"output_slot": synthesized_item} + except Exception as e: + raise RuntimeError(f"Error in matter_synthesizer: {str(e)}") + + # --- Terminal Implementations --- + def terminal_1(self, inputs): + """ + terminal_1: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 只返回 text_output + - 只输入正确的 slot_b → 只返回 hex_output + - 同时输入正确的 slot_a 和 slot_b → 返回 item_dispenser(物品掉落) + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + # 检查哪些输入被提供了 + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值是否正确(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + expected_a = golden_inputs["slot_a"] + a_valid = str(slot_a) == str(expected_a) + + if has_b and "slot_b" in golden_inputs: + expected_b = golden_inputs["slot_b"] + b_valid = str(slot_b) == str(expected_b) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 item_dispenser + if has_a and has_b: + if a_valid and b_valid: + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 text_output + if has_a and not has_b: + if a_valid: + if "text_output" in golden_outputs: + result["text_output"] = golden_outputs["text_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 hex_output + if has_b and not has_a: + if b_valid: + if "hex_output" in golden_outputs: + result["hex_output"] = golden_outputs["hex_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def terminal_2(self, inputs): + """ + terminal_2: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 text_result + - 同时输入正确的 num1 和 num2 → 返回 hex_result 和 math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + # 检查哪些输入被提供了 + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值是否正确(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + expected_num1 = golden_inputs["num1"] + num1_valid = str(num1) == str(expected_num1) + + if has_num2 and "num2" in golden_inputs: + expected_num2 = golden_inputs["num2"] + num2_valid = str(num2) == str(expected_num2) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 hex_result 和 math_token + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 text_result + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "text_result" in golden_outputs: + result["text_result"] = golden_outputs["text_result"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def logic_terminal(self, inputs): + """ + Logic Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 返回 screen(部分输出) + - 只输入正确的 slot_b → 返回 screen 和 secondary_output + - 同时输入正确的 slot_a 和 slot_b → 返回 screen, secondary_output, item_dispenser + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + a_valid = str(slot_a) == str(golden_inputs["slot_a"]) + + if has_b and "slot_b" in golden_inputs: + b_valid = str(slot_b) == str(golden_inputs["slot_b"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出(包括 item_dispenser) + if has_a and has_b: + if a_valid and b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 screen(部分输出) + if has_a and not has_b: + if a_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 screen 和 secondary_output + if has_b and not has_a: + if b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def math_terminal(self, inputs): + """ + Math Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 result_display + - 同时输入正确的 num1 和 num2 → 返回 result_display, hex_result, math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + num1_valid = str(num1) == str(golden_inputs["num1"]) + + if has_num2 and "num2" in golden_inputs: + num2_valid = str(num2) == str(golden_inputs["num2"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 result_display + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def crypt_terminal(self, inputs): + """ + Encryption Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 plaintext → 返回 status(部分输出) + - 同时输入正确的 plaintext 和 key → 返回 status, encrypted_hex, encryption_chip + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + plaintext = inputs.get("plaintext") + key = inputs.get("key") + + has_plaintext = plaintext is not None and plaintext != "" + has_key = key is not None and key != "" + + # 验证输入值(与 golden values 比较) + plaintext_valid = False + key_valid = False + + if has_plaintext and "plaintext" in golden_inputs: + plaintext_valid = str(plaintext) == str(golden_inputs["plaintext"]) + + if has_key and "key" in golden_inputs: + key_valid = str(key) == str(golden_inputs["key"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_plaintext and has_key: + if plaintext_valid and key_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + if "encrypted_hex" in golden_outputs: + result["encrypted_hex"] = golden_outputs["encrypted_hex"] + if "encryption_chip" in golden_outputs: + result["encryption_chip"] = golden_outputs["encryption_chip"] + return result + else: + incorrect_params = [] + correct_params = [] + if not plaintext_valid: + incorrect_params.append("plaintext") + else: + correct_params.append("plaintext") + if not key_valid: + incorrect_params.append("key") + else: + correct_params.append("key") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 plaintext 且正确 → 返回 status(部分输出) + if has_plaintext and not has_key: + if plaintext_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: plaintext"} + + # 只提供 key 但没有 plaintext + if has_key and not has_plaintext: + return {"error": "plaintext required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + def sequence_terminal(self, inputs): + """ + Sequence Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 sequence → 返回 verification(部分输出) + - 同时输入正确的 sequence 和 checksum → 返回 verification, auth_code, access_card + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + sequence = inputs.get("sequence") + checksum = inputs.get("checksum") + + has_sequence = sequence is not None and sequence != "" + has_checksum = checksum is not None and checksum != "" + + # 验证输入值(与 golden values 比较) + sequence_valid = False + checksum_valid = False + + if has_sequence and "sequence" in golden_inputs: + sequence_valid = str(sequence) == str(golden_inputs["sequence"]) + + if has_checksum and "checksum" in golden_inputs: + checksum_valid = str(checksum) == str(golden_inputs["checksum"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_sequence and has_checksum: + if sequence_valid and checksum_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + if "auth_code" in golden_outputs: + result["auth_code"] = golden_outputs["auth_code"] + if "access_card" in golden_outputs: + result["access_card"] = golden_outputs["access_card"] + return result + else: + incorrect_params = [] + correct_params = [] + if not sequence_valid: + incorrect_params.append("sequence") + else: + correct_params.append("sequence") + if not checksum_valid: + incorrect_params.append("checksum") + else: + correct_params.append("checksum") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 sequence 且正确 → 返回 verification(部分输出) + if has_sequence and not has_checksum: + if sequence_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: sequence"} + + # 只提供 checksum 但没有 sequence + if has_checksum and not has_sequence: + return {"error": "sequence required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + # --- Additional File Tools --- + + def zip_unzip_file(self, inputs): + """ZIP 解压文件工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def zip_unzip_item(self, inputs): + """ZIP 解压道具工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def code_py_exec(self, inputs): + """Python 代码执行工具 + + 这是一个真实执行的工具,在 DAG 生成阶段和运行时评测阶段都会执行代码。 + 输入: code (Python 代码字符串) + 输出: stdout (标准输出,包含执行结果和错误信息) + + 特殊行为: + - 如果代码定义了 main() 函数,会自动调用它 + - 如果执行出错,错误信息会包含在 stdout 中 + """ + code = inputs.get("code", "") + + if not code: + return {"stdout": "Error: No code provided"} + + try: + # 创建一个受限的执行环境 + import io + import sys + + # 捕获标准输出和标准错误 + old_stdout = sys.stdout + old_stderr = sys.stderr + sys.stdout = io.StringIO() + sys.stderr = io.StringIO() + + # 执行代码 + exec_globals = {"__builtins__": __builtins__} + exec_locals = {} + exec(code, exec_globals, exec_locals) + + # 如果定义了 main() 函数,自动调用它 + if 'main' in exec_locals and callable(exec_locals['main']): + exec_locals['main']() + + # 获取输出 + stdout_value = sys.stdout.getvalue() + stderr_value = sys.stderr.getvalue() + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 合并 stdout 和 stderr + output = stdout_value + if stderr_value: + output += ("\n" if output else "") + f"[stderr] {stderr_value}" + + # 如果没有任何输出,尝试返回 result 变量的值 + if not output: + result = exec_locals.get("_result") or exec_locals.get("result") + if result is not None: + output = str(result) + + return {"stdout": output if output else "(no output)"} + + except Exception as e: + # 恢复标准输出和错误输出 + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 返回错误信息 + return {"stdout": f"Error: {type(e).__name__}: {str(e)}"} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-94cc40fa/environment/puzzle/worker.Dockerfile b/tasks/agentescape-25-skeleton-94cc40fa/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-25-skeleton-94cc40fa/environment/puzzle/worker.Dockerfile @@ -0,0 +1,8 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends libseccomp2 && rm -rf /var/lib/apt/lists/* +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY worker.py child.py /app/ +COPY upstream/simulator.py /app/simulator.py +CMD ["uvicorn", "worker:app", "--host", "0.0.0.0", "--port", "8001", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-25-skeleton-94cc40fa/environment/puzzle/worker.py b/tasks/agentescape-25-skeleton-94cc40fa/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-25-skeleton-94cc40fa/environment/puzzle/worker.py @@ -0,0 +1,73 @@ +"""Stateless Python tool worker. Never receives a scenario or reference values.""" + +import json +import os +import signal +import subprocess +import sys +import tempfile +import threading + +from fastapi import FastAPI +from pydantic import BaseModel, ConfigDict + +app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) +lock = threading.Lock() + + +class Execution(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + code: str + + +@app.get("/health") +def health(): + return {"ok": True} + + +@app.post("/execute") +def execute(request: Execution): + if len(request.code.encode()) > 65536: + return {"stdout": "Error: code exceeds 64 KiB limit"} + with lock, tempfile.TemporaryDirectory(prefix="escape-code-") as directory: + os.chown(directory, 65534, 65534) + with tempfile.TemporaryFile() as output: + process = subprocess.Popen( + [sys.executable, "-I", "/app/child.py"], + stdin=subprocess.PIPE, + stdout=output, + stderr=subprocess.DEVNULL, + cwd=directory, + user=65534, + group=65534, + extra_groups=[], + start_new_session=True, + env={"PATH": "/usr/local/bin:/usr/bin:/bin"}, + ) + try: + process.communicate( + json.dumps({"code": request.code}).encode(), timeout=5 + ) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + return {"stdout": "Error: Python execution timed out"} + finally: + # Also remove children still in the process group after normal exit. + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + output.seek(0) + value = output.read(65537) + if len(value) > 65536 or process.returncode != 0: + return { + "stdout": "Error: Python execution exceeded a resource limit or failed" + } + try: + result = json.loads(value) + if not isinstance(result.get("stdout"), str): + raise ValueError("Invalid worker response") + return result + except (ValueError, AttributeError): + return {"stdout": "Error: Python execution returned invalid output"} diff --git a/tasks/agentescape-25-skeleton-94cc40fa/instruction.md b/tasks/agentescape-25-skeleton-94cc40fa/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-25-skeleton-94cc40fa/instruction.md @@ -0,0 +1,18 @@ +# Escape the room + +Discover the victory string and submit it with `escape submit-answer`. +Start with `escape observe`. This returns the room, available information, visible entities, and victory node ID. + +Use these commands (JSON responses): + +```sh +escape investigate NODE_ID +escape tool-call NODE_ID --arguments-json '{"parameter": "value"}' +escape use-item NODE_ID --arguments-json '{"parameter": "value"}' +escape submit-answer 'exact victory string' +escape state +``` + +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. + +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. diff --git a/tasks/agentescape-25-skeleton-94cc40fa/solution/oracle.py b/tasks/agentescape-25-skeleton-94cc40fa/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-25-skeleton-94cc40fa/solution/oracle.py @@ -0,0 +1,133 @@ +"""Reference solver: use trusted inputs, but obtain the answer through public actions.""" + +import json +import urllib.request +from pathlib import Path + + +def http_action(base_url, payload): + request = urllib.request.Request( + base_url + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(request, timeout=30) as response: + return json.load(response) + + +def solve(scenario, act, observe): + nodes = {node["id"]: node for node in scenario["nodes"]} + visible = {entity["id"] for entity in observe["available_entities"]} + solved = set() + seen_outputs = {} + action_count = 0 + + def call(payload): + nonlocal action_count + action_count += 1 + response = act(payload) + visible.update(entity["id"] for entity in response.get("newly_revealed", [])) + if ( + response.get("episode", {}).get("termination_reason") + == "infrastructure_error" + ): + raise RuntimeError("Infrastructure failure") + return response + + for _round in range(len(nodes) + 2): + progress = False + for node_id, node in nodes.items(): + if node_id not in visible or node_id in solved: + continue + # Preserve graph order for data inputs; trigger/drop edges express visibility. + predecessors = [ + edge["source_id"] + for edge in scenario["edges"] + if edge["target_id"] == node_id + and edge["connection_type"] not in ("Item", "Hidden_Item") + ] + if any(pred not in solved for pred in predecessors): + continue + info = call({"action": "investigate", "node_id": node_id}) + if not info.get("ok"): + raise RuntimeError(f"Investigation failed: {node_id}: {info}") + inputs = { + port["name"]: port["value"] + for port in node.get("inputs", []) + if "value" in port + } + if node["type"] == "Tool": + result = call( + {"action": "tool_call", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok") or result.get("output_values", {}).get("error"): + raise RuntimeError(f"Tool failed: {node_id}: {result}") + output = result.get("output_values", {}) + if node.get("template_id") in ("terminal_1", "terminal_2"): + slots = { + port["name"]: inputs[port["name"]] + for port in node["inputs"] + if port["type"] not in ("Item", "Hidden_Item") + and port["name"] in inputs + } + triggers = { + key: value for key, value in inputs.items() if key not in slots + } + for key, value in slots.items(): + partial = call( + { + "action": "tool_call", + "node_id": node_id, + "arguments": {**triggers, key: value}, + } + ) + if partial.get("ok"): + output.update(partial.get("output_values", {})) + # HIDDEN_ITEM tool drops only occur on subsequent investigation. + call({"action": "investigate", "node_id": node_id}) + elif info.get("required_inputs"): + result = call( + {"action": "use_item", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok"): + raise RuntimeError(f"Item failed: {node_id}: {result}") + output = result.get("content") + else: + output = info.get("content") + seen_outputs[node_id] = output + solved.add(node_id) + progress = True + win_id = scenario["metadata"]["win_node_id"] + if win_id in solved and (len(solved) == len(nodes) or not progress): + outputs = seen_outputs[win_id] + if not outputs: + raise RuntimeError(f"Victory node returned no output: {win_id}") + # Upstream grades its first stored output port, independent of response order. + victory_port = next( + port["name"] for port in nodes[win_id]["outputs"] if "value" in port + ) + answer = outputs[victory_port] if isinstance(outputs, dict) else outputs + result = call({"action": "submit_answer", "answer": answer}) + if not result.get("is_win"): + raise RuntimeError(f"Victory submission failed: {result}") + return {"won": True, "actions": action_count, "visited_nodes": len(solved)} + if not progress: + raise RuntimeError(f"No progress: visible={visible}, solved={solved}") + raise RuntimeError("Reference solver exceeded graph traversal limit") + + +if __name__ == "__main__": + import os + + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000") + with urllib.request.urlopen(base + "/observation", timeout=20) as response: + observation = json.load(response) + print( + json.dumps( + solve( + json.loads(Path("/solution/scenario.json").read_text()), + lambda payload: http_action(base, payload), + observation, + ) + ) + ) diff --git a/tasks/agentescape-25-skeleton-94cc40fa/solution/scenario.json b/tasks/agentescape-25-skeleton-94cc40fa/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..30bb0e8f2a7abdf64902debfd35c32b207f6f699 --- /dev/null +++ b/tasks/agentescape-25-skeleton-94cc40fa/solution/scenario.json @@ -0,0 +1,1427 @@ +{ + "metadata": { + "total_nodes": 25, + "total_edges": 28, + "win_node_id": "item_14", + "win_condition": { + "type": "item_content", + "node_id": "item_14", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_14", + "graph_shortest_path", + "zip_unzip_file", + "terminal_2", + "item_7", + "container_3_700f", + "num_base_convert", + "calc_inv_mod", + "checksum_crc32_8c69", + "terminal_1", + "crypto_rsa_decrypt_hex", + "item_1", + "base64_decode", + "calc_gcd", + "calc_bigmul_3271" + ], + "by_node": { + "item_14": { + "node_name": "", + "node_type": "Item", + "template_id": "item_14", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Hex_String_IV_AES", + "description": "AES IV" + } + } + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": {}, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": {}, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + }, + "math_token": { + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + } + }, + "item_7": { + "node_name": "", + "node_type": "Item", + "template_id": "item_7", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Code_Python", + "description": "The integer" + } + } + }, + "container_3_700f": { + "node_name": "", + "node_type": "Item", + "template_id": "container_3", + "init_inputs": { + "fingerprint_input": { + "type": "Big_Int", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + }, + "num_base_convert": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "to_base": { + "type": "Big_Int", + "description": "To base" + } + }, + "init_outputs": {} + }, + "calc_inv_mod": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "Integer a" + } + }, + "init_outputs": {} + }, + "checksum_crc32_8c69": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": {}, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + } + } + }, + "crypto_rsa_decrypt_hex": { + "node_name": "RSA Decrypt", + "node_type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "init_inputs": { + "n": { + "type": "Big_Int", + "description": "Modulus n" + }, + "d": { + "type": "Big_Int", + "description": "Private exponent d" + } + }, + "init_outputs": {} + }, + "item_1": { + "node_name": "", + "node_type": "Item", + "template_id": "item_1", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Big_Int", + "description": "The number" + } + } + }, + "base64_decode": { + "node_name": "Base64 Decoder", + "node_type": "Tool", + "template_id": "base64_decode", + "init_inputs": { + "data": { + "type": "Text_Generic", + "description": "Base64 string" + } + }, + "init_outputs": {} + }, + "calc_gcd": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First integer" + } + }, + "init_outputs": {} + }, + "calc_bigmul_3271": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First large integer" + }, + "b": { + "type": "Big_Int", + "description": "Second large integer" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "item_14": { + "init_inputs": {}, + "init_outputs": { + "content": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "graph_shortest_path": { + "init_inputs": {}, + "init_outputs": { + "path": "[\"node_A\", \"node_B\", \"node_C\", \"node_D\", \"node_E\", \"node_F\"]", + "cost": "482094" + } + }, + "zip_unzip_file": { + "init_inputs": { + "zip_id": "archive_7294.zip" + }, + "init_outputs": { + "files": "extracted_files_8942.zip" + } + }, + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Partial computation processed successfully.", + "hex_result": "deadbeef1234567890abcdef", + "math_token": "This is a mathematically useless token." + } + }, + "item_7": { + "init_inputs": {}, + "init_outputs": { + "content": "print(1234567890)" + } + }, + "container_3_700f": { + "init_inputs": { + "fingerprint_input": "4859382910485729103948572" + }, + "init_outputs": {} + }, + "num_base_convert": { + "init_inputs": { + "to_base": "10" + }, + "init_outputs": {} + }, + "calc_inv_mod": { + "init_inputs": { + "a": "59483726152438495067281" + }, + "init_outputs": {} + }, + "checksum_crc32_8c69": { + "init_inputs": { + "hex": "1234abcd5678ef90" + }, + "init_outputs": {} + }, + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "Terminal output successfully generated for slot a.", + "hex_output": "1a2b3c4d5e6f7a8b" + } + }, + "crypto_rsa_decrypt_hex": { + "init_inputs": { + "n": "987654321098765432109876543210", + "d": "123456789012345678901234567890" + }, + "init_outputs": {} + }, + "item_1": { + "init_inputs": {}, + "init_outputs": { + "content": "3948572839401928374650129" + } + }, + "base64_decode": { + "init_inputs": { + "data": "SGVsbG8sIHRoaXMgaXMgYSBiYXNlNjQgZW5jb2RlZCBzdHJpbmcgZm9yIHRlc3RpbmcgZGVjb2RlLg==" + }, + "init_outputs": {} + }, + "calc_gcd": { + "init_inputs": { + "a": "85739284756102938475629" + }, + "init_outputs": {} + }, + "calc_bigmul_3271": { + "init_inputs": { + "a": "948572618394857261738495", + "b": "192837465019283746501928" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You are a private investigator who just broke into the sealed evidence room of the abandoned 12th Precinct. The infamous 'Midnight Syndicate' case was abruptly closed weeks ago, and the lead detective vanished without a trace. Rumor has it they left behind a trail of digital breadcrumbs and encrypted forensic tools that point to a massive conspiracy. You must navigate the scattered equipment, reconstruct the evidence chain, and uncover the final truth before corrupt officials realize you are here.", + "narrative_style": "detective" + }, + "nodes": [ + { + "id": "item_14", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_14", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hex_String_IV_AES", + "description": "AES IV", + "value": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "narrative": "The Final Evidence File. This contains the conclusive proof needed to close the case once and for all." + }, + { + "id": "container_3", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_3", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Big_Int", + "description": "Fingerprint Hash", + "value": "482094" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is the Biometric Evidence Safe. It requires input from the Suspect Tracking System to authenticate and unlock." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A Blacklight Flashlight, heavily used for crime scene investigations to detect hidden traces." + }, + { + "id": "item_8_2d97", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A specialized UV Bulb designed to fit into standard forensic flashlights." + }, + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "extracted_files_8942.zip" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Partial computation processed successfully." + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "1234567890\n" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"node_A\", \"node_B\", \"node_C\", \"node_D\", \"node_E\", \"node_F\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "482094" + } + ], + "init": { + "inputs": {}, + "outputs": { + "path": "[\"node_A\", \"node_B\", \"node_C\", \"node_D\", \"node_E\", \"node_F\"]", + "cost": "482094" + } + }, + "narrative": "This is the Suspect Tracking System. It requires inputs from the Forensic Analysis Computer, the Encrypted Case Archive, and the Main Security Mainframe." + }, + { + "id": "code_py_exec", + "name": "Python Executor", + "description": "Run limited Python: only safe builtins.", + "type": "Tool", + "template_id": "code_py_exec", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "code", + "type": "Code_Python", + "description": "Python code", + "value": "print(1234567890)" + } + ], + "outputs": [ + { + "name": "stdout", + "type": "Text_Generic", + "description": "Standard Output (includes errors if any)", + "value": "1234567890\n" + } + ], + "narrative": "This is the Forensic Analysis Computer. It requires input from the Source Code Fragment to run its simulations." + }, + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "archive_7294.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Partial computation processed successfully." + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_files_8942.zip" + } + ], + "init": { + "inputs": { + "zip_id": "archive_7294.zip" + }, + "outputs": { + "files": "extracted_files_8942.zip" + } + }, + "narrative": "This is the Encrypted Case Archive. It requires input from the Main Security Mainframe to extract its hidden files." + }, + { + "id": "terminal_2", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "0" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "0" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Partial computation processed successfully." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "deadbeef1234567890abcdef" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "This is a mathematically useless token." + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "Partial computation processed successfully.", + "hex_result": "deadbeef1234567890abcdef", + "math_token": "This is a mathematically useless token." + } + }, + "narrative": "This is the Main Security Mainframe. It requires inputs from the Data Aggregator and the Frequency Converter." + }, + { + "id": "calc_bigmul", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "0" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": 3369264727 + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "0" + } + ], + "narrative": "This is the Data Aggregator. It requires inputs from the Secondary Integrity Checker and the Decryption Matrix." + }, + { + "id": "item_8_7e11", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A standard issue Battery Pack, fully charged and ready for use." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "The Detective's Notes, containing scribbled observations left behind by the missing investigator." + }, + { + "id": "item_7", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_7", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Code_Python", + "description": "The integer", + "value": "print(1234567890)" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "print(1234567890)" + } + }, + "narrative": "A Source Code Fragment torn from a programmer's notebook, detailing crucial logic." + }, + { + "id": "item_16_cec9", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "The Initial Briefing folder containing the first terrifying details of the syndicate." + }, + { + "id": "checksum_crc32", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "f8a3b0c8" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "c8d2e657" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3369264727 + } + ], + "narrative": "This is the Secondary Integrity Checker. It requires input from the Primary Integrity Checker to validate the chain of custody." + }, + { + "id": "container_3_700f", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_3", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Big_Int", + "description": "Fingerprint Hash", + "value": "4859382910485729103948572" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "4859382910485729103948572" + }, + "outputs": {} + }, + "narrative": "The Detective's Lockbox, a small heavy metal case kept hidden under a desk." + }, + { + "id": "num_base_convert", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "0" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "3948572839401928374650129" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "10" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "0" + } + ], + "init": { + "inputs": { + "to_base": "10" + }, + "outputs": {} + }, + "narrative": "This is the Frequency Converter. It requires inputs from the Network Analyzer and the Victim's Pager." + }, + { + "id": "calc_inv_mod", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "59483726152438495067281" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "1" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "0" + } + ], + "init": { + "inputs": { + "a": "59483726152438495067281" + }, + "outputs": {} + }, + "narrative": "This is the Decryption Matrix. It requires input from the Signal Synchronizer to align its algorithms." + }, + { + "id": "calc_bigmul_0497", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": 4171477192 + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "0" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "0" + } + ], + "narrative": "This is the Network Analyzer. It requires inputs from the Data Aggregator and the Primary Integrity Checker." + }, + { + "id": "checksum_crc32_8c69", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "1234abcd5678ef90" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "f8a3b0c8" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 4171477192 + } + ], + "init": { + "inputs": { + "hex": "1234abcd5678ef90" + }, + "outputs": {} + }, + "narrative": "The Primary Integrity Checker, a handheld digital scanner used to verify evidence authenticity." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "\t\u00051JRU\u0012" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "3948572839401928374650129" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Terminal output successfully generated for slot a." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "1a2b3c4d5e6f7a8b" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "Terminal output successfully generated for slot a.", + "hex_output": "1a2b3c4d5e6f7a8b" + } + }, + "narrative": "This is the Interrogation Room Terminal. It requires inputs from the Cypher Breaking Module and the Victim's Pager." + }, + { + "id": "crypto_rsa_decrypt_hex", + "name": "RSA Decrypt", + "description": "RSA decrypt (hex cipher) with n,d (decimal).", + "type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex_cipher", + "type": "Hex_String", + "description": "Ciphertext (Hex)", + "value": "48656c6c6f2c207468697320697320612062617365363420656e636f64656420737472696e6720666f722074657374696e67206465636f64652e" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Modulus n", + "value": "987654321098765432109876543210" + }, + { + "name": "d", + "type": "Big_Int", + "description": "Private exponent d", + "value": "123456789012345678901234567890" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decrypted text", + "value": "\t\u00051JRU\u0012" + } + ], + "init": { + "inputs": { + "n": "987654321098765432109876543210", + "d": "123456789012345678901234567890" + }, + "outputs": {} + }, + "narrative": "This is the Cypher Breaking Module. It requires input from the Signal Interceptor to decipher the raw data." + }, + { + "id": "item_1", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "Big_Int", + "description": "The number", + "value": "3948572839401928374650129" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "3948572839401928374650129" + } + }, + "narrative": "The Victim's Pager, badly damaged but still holding a sliver of vital memory." + }, + { + "id": "base64_decode", + "name": "Base64 Decoder", + "description": "Decode base64 to hex bytes.", + "type": "Tool", + "template_id": "base64_decode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "data", + "type": "Text_Generic", + "description": "Base64 string", + "value": "SGVsbG8sIHRoaXMgaXMgYSBiYXNlNjQgZW5jb2RlZCBzdHJpbmcgZm9yIHRlc3RpbmcgZGVjb2RlLg==" + } + ], + "outputs": [ + { + "name": "bytes_hex", + "type": "Hex_String", + "description": "Decoded bytes as Hex", + "value": "48656c6c6f2c207468697320697320612062617365363420656e636f64656420737472696e6720666f722074657374696e67206465636f64652e" + } + ], + "init": { + "inputs": { + "data": "SGVsbG8sIHRoaXMgaXMgYSBiYXNlNjQgZW5jb2RlZCBzdHJpbmcgZm9yIHRlc3RpbmcgZGVjb2RlLg==" + }, + "outputs": {} + }, + "narrative": "The Signal Interceptor, a basic antenna rig used to catch raw data broadcasts around the precinct." + }, + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "85739284756102938475629" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "182920339117968677302289381062489571672149318360" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "init": { + "inputs": { + "a": "85739284756102938475629" + }, + "outputs": {} + }, + "narrative": "This is the Signal Synchronizer. It requires input from the Signal Amplifier to process the audio tracks." + }, + { + "id": "calc_bigmul_3271", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "948572618394857261738495" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "192837465019283746501928" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "182920339117968677302289381062489571672149318360" + } + ], + "init": { + "inputs": { + "a": "948572618394857261738495", + "b": "192837465019283746501928" + }, + "outputs": {} + }, + "narrative": "The Signal Amplifier, an analog device used to boost faint audio recordings from wiretaps." + } + ], + "edges": [ + { + "source_id": "container_3", + "target_id": "item_14", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "item_8", + "target_id": "container_3", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "item_8_2d97", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "graph_shortest_path", + "target_id": "container_3", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "fingerprint_input" + }, + { + "source_id": "code_py_exec", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "stdout", + "target_port": "dst" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "terminal_2", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "password" + }, + { + "source_id": "calc_bigmul", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "num1" + }, + { + "source_id": "item_8_7e11", + "target_id": "item_8_2d97", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_16", + "target_id": "code_py_exec", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "terminal_2", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "src" + }, + { + "source_id": "item_7", + "target_id": "code_py_exec", + "connection_type": "Code_Python", + "source_port": "content", + "target_port": "code" + }, + { + "source_id": "item_16_cec9", + "target_id": "item_8_7e11", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "b" + }, + { + "source_id": "container_3_700f", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "num_base_convert", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "num2" + }, + { + "source_id": "calc_inv_mod", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "a" + }, + { + "source_id": "calc_bigmul_0497", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "s" + }, + { + "source_id": "calc_bigmul", + "target_id": "calc_bigmul_0497", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "b" + }, + { + "source_id": "checksum_crc32_8c69", + "target_id": "calc_bigmul_0497", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "a" + }, + { + "source_id": "terminal_1", + "target_id": "checksum_crc32_8c69", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "trigger_item" + }, + { + "source_id": "crypto_rsa_decrypt_hex", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "slot_a" + }, + { + "source_id": "item_1", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "content", + "target_port": "slot_b" + }, + { + "source_id": "base64_decode", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Hex_String", + "source_port": "bytes_hex", + "target_port": "hex_cipher" + }, + { + "source_id": "item_1", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "content", + "target_port": "from_base" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "mod" + }, + { + "source_id": "checksum_crc32_8c69", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "calc_bigmul_3271", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "b" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-94cc40fa/solution/solve.sh b/tasks/agentescape-25-skeleton-94cc40fa/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-25-skeleton-94cc40fa/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-25-skeleton-94cc40fa/task.toml b/tasks/agentescape-25-skeleton-94cc40fa/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6ffbca9db505c8c8ebf25d8dbcbd78100f3376d8 --- /dev/null +++ b/tasks/agentescape-25-skeleton-94cc40fa/task.toml @@ -0,0 +1,38 @@ +schema_version = "1.4" +source = "https://github.com/AGI-Eval-Official/Repo-of-AgentEscapeBench" + +[[artifacts]] +source = "/evidence/final.json" +service = "puzzle" + +[[artifacts]] +source = "/evidence/trace.jsonl" +service = "puzzle" + +[task] +name = "edbeeching/agentescape-25-skeleton-94cc40fa" +version = "0.1.0" + +[metadata] +difficulty = 25 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "87d60b1ff1650b2109327645dc2117ec7d4e1c4733a27bf8da1e1621984f377f" +protocol = "harbor-cli-action-budget-v1" +max_actions = 500 + +[agent] +timeout_sec = 1200 + +[environment] +build_timeout_sec = 900 +cpus = 1 +memory_mb = 1024 + +[verifier] +environment_mode = "separate" +timeout_sec = 60 + +[[verifier.collect]] +service = "puzzle" +command = "python -I /app/export.py" +timeout_sec = 15 diff --git a/tasks/agentescape-25-skeleton-94cc40fa/tests/Dockerfile b/tasks/agentescape-25-skeleton-94cc40fa/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-25-skeleton-94cc40fa/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-25-skeleton-94cc40fa/tests/expected.json b/tasks/agentescape-25-skeleton-94cc40fa/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..c108ce36a66b8a42728f8d4bf2f96221a233d443 --- /dev/null +++ b/tasks/agentescape-25-skeleton-94cc40fa/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "87d60b1ff1650b2109327645dc2117ec7d4e1c4733a27bf8da1e1621984f377f", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-94cc40fa/tests/grade.py b/tasks/agentescape-25-skeleton-94cc40fa/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-25-skeleton-94cc40fa/tests/grade.py @@ -0,0 +1,21 @@ +"""Grade only Harbor-collected sidecar evidence in a fresh verifier container.""" + +import json +from pathlib import Path + +expected = json.loads(Path("/tests/expected.json").read_text()) +state = json.loads(Path("/evidence/final.json").read_text()) +assert state["collected_from_live_service"] is True, "Missing trusted service export" +assert state["scenario_sha256"] == expected["scenario_sha256"], ( + "Wrong scenario evidence" +) +assert state["max_actions"] == expected["max_actions"], "Wrong budget" +assert type(state["won"]) is bool +assert 0 <= state["action_count"] <= state["max_actions"] +assert state["termination_reason"] != "infrastructure_error", ( + "Infrastructure failure is not a puzzle failure" +) +assert not state["won"] or state["termination_reason"] == "success" +Path("/logs/verifier").mkdir(parents=True, exist_ok=True) +Path("/logs/verifier/state.json").write_text(json.dumps(state, indent=2)) +Path("/logs/verifier/reward.txt").write_text("1.0\n" if state["won"] else "0.0\n") diff --git a/tasks/agentescape-25-skeleton-94cc40fa/tests/test.sh b/tasks/agentescape-25-skeleton-94cc40fa/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-25-skeleton-94cc40fa/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-25-skeleton-a8a2cf21/environment/Dockerfile b/tasks/agentescape-25-skeleton-a8a2cf21/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-25-skeleton-a8a2cf21/environment/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-25-skeleton-a8a2cf21/environment/agent/Dockerfile b/tasks/agentescape-25-skeleton-a8a2cf21/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-25-skeleton-a8a2cf21/environment/agent/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-25-skeleton-a8a2cf21/environment/agent/cli.py b/tasks/agentescape-25-skeleton-a8a2cf21/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-25-skeleton-a8a2cf21/environment/agent/cli.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Public agent client; depends only on the Python standard library.""" + +import argparse +import json +import os +import sys +import urllib.error +import urllib.request + + +def main(): + parser = argparse.ArgumentParser(description="Interact with the escape room") + parser.add_argument( + "action", + choices=[ + "observe", + "state", + "investigate", + "tool-call", + "use-item", + "submit-answer", + ], + ) + parser.add_argument("value", nargs="?") + parser.add_argument("--arguments-json", default="{}") + args = parser.parse_args() + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000").rstrip("/") + if args.action in ("observe", "state"): + request = urllib.request.Request( + base + ("/observation" if args.action == "observe" else "/state") + ) + else: + if args.value is None: + parser.error("node ID or answer is required") + payload = {"action": args.action.replace("-", "_")} + if args.action == "submit-answer": + payload["answer"] = args.value + else: + payload["node_id"] = args.value + if args.action in ("tool-call", "use-item"): + payload["arguments"] = json.loads(args.arguments_json) + request = urllib.request.Request( + base + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=30) as response: + print(json.dumps(json.load(response), ensure_ascii=False)) + except (urllib.error.URLError, ValueError) as exc: + print(json.dumps({"ok": False, "error": str(exc)})) + sys.exit(2) + + +if __name__ == "__main__": + main() diff --git a/tasks/agentescape-25-skeleton-a8a2cf21/environment/docker-compose.yaml b/tasks/agentescape-25-skeleton-a8a2cf21/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3e7f6270d55cad40aedba9ec9d988cb13775fb41 --- /dev/null +++ b/tasks/agentescape-25-skeleton-a8a2cf21/environment/docker-compose.yaml @@ -0,0 +1,50 @@ +services: + main: + image: agentescapebench-agent:aab05a0a9ddb + build: + context: ./agent + networks: [default, puzzle] + security_opt: [no-new-privileges:true] + depends_on: + puzzle: + condition: service_healthy + puzzle: + image: agentescapebench-puzzle:agentescape-25-skeleton-a8a2cf21-aab05a0a9ddb + build: + context: ./puzzle + networks: [puzzle, execution] + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 512m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"] + interval: 1s + timeout: 3s + retries: 30 + depends_on: + worker: + condition: service_healthy + worker: + image: agentescapebench-worker:aab05a0a9ddb + build: + context: ./puzzle + dockerfile: worker.Dockerfile + networks: [execution] + read_only: true + tmpfs: ["/tmp:size=64m,mode=1777"] + cap_drop: [ALL] + cap_add: [SETUID, SETGID, KILL, CHOWN, DAC_OVERRIDE] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 384m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8001/health')"] + interval: 1s + timeout: 3s + retries: 30 +networks: + puzzle: + internal: true + execution: + internal: true diff --git a/tasks/agentescape-25-skeleton-a8a2cf21/environment/puzzle/Dockerfile b/tasks/agentescape-25-skeleton-a8a2cf21/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-25-skeleton-a8a2cf21/environment/puzzle/Dockerfile @@ -0,0 +1,9 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY upstream /app/upstream +COPY service.py export.py /app/ +COPY scenario.json /private/scenario.json +ENV SCENARIO_PATH=/private/scenario.json EVIDENCE_DIR=/evidence WORKER_URL=http://worker:8001 MAX_ACTIONS=500 +CMD ["uvicorn", "service:create_app", "--factory", "--host", "0.0.0.0", "--port", "8000", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-25-skeleton-a8a2cf21/environment/puzzle/child.py b/tasks/agentescape-25-skeleton-a8a2cf21/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-25-skeleton-a8a2cf21/environment/puzzle/child.py @@ -0,0 +1,59 @@ +"""Run the original Python tool after reducing privileges and blocking networking.""" + +import ctypes +import errno +import json +import resource +import sys + +resource.setrlimit(resource.RLIMIT_CPU, (3, 3)) +resource.setrlimit(resource.RLIMIT_AS, (256 * 1024 * 1024, 256 * 1024 * 1024)) +resource.setrlimit(resource.RLIMIT_FSIZE, (65536, 65536)) +resource.setrlimit(resource.RLIMIT_NOFILE, (32, 32)) +resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + +# Filters survive fork/exec. Fail closed if seccomp cannot be loaded. +lib = ctypes.CDLL("libseccomp.so.2", use_errno=True) +lib.seccomp_init.argtypes = [ctypes.c_uint32] +lib.seccomp_init.restype = ctypes.c_void_p +lib.seccomp_rule_add.argtypes = [ + ctypes.c_void_p, + ctypes.c_uint32, + ctypes.c_int, + ctypes.c_uint, +] +lib.seccomp_syscall_resolve_name.argtypes = [ctypes.c_char_p] +lib.seccomp_load.argtypes = [ctypes.c_void_p] +lib.seccomp_release.argtypes = [ctypes.c_void_p] +ctx = lib.seccomp_init(0x7FFF0000) # SCMP_ACT_ALLOW +if not ctx: + raise RuntimeError("Cannot initialize execution isolation") +try: + for name in ( + "socket", + "socketpair", + "connect", + "ptrace", + "process_vm_readv", + "process_vm_writev", + "mount", + "unshare", + "setns", + "bpf", + ): + number = lib.seccomp_syscall_resolve_name(name.encode()) + if ( + number >= 0 + and lib.seccomp_rule_add(ctx, 0x00050000 | errno.EPERM, number, 0) != 0 + ): + raise RuntimeError("Cannot install execution isolation rule") + if lib.seccomp_load(ctx) != 0: + raise RuntimeError("Cannot activate execution isolation") +finally: + lib.seccomp_release(ctx) + +sys.path.insert(0, "/app") +from simulator import ToolSimulator # noqa: E402 + +request = json.load(sys.stdin) +json.dump(ToolSimulator().code_py_exec(request), sys.stdout) diff --git a/tasks/agentescape-25-skeleton-a8a2cf21/environment/puzzle/export.py b/tasks/agentescape-25-skeleton-a8a2cf21/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-25-skeleton-a8a2cf21/environment/puzzle/export.py @@ -0,0 +1,13 @@ +"""Harbor invokes this inside the puzzle service after stopping the agent.""" + +import json +import pathlib +import urllib.request + +with urllib.request.urlopen("http://127.0.0.1:8000/state", timeout=10) as response: + state = json.load(response) +state["collected_from_live_service"] = True +target = pathlib.Path("/evidence/final.json") +temp = target.with_suffix(".tmp") +temp.write_text(json.dumps(state)) +temp.replace(target) diff --git a/tasks/agentescape-25-skeleton-a8a2cf21/environment/puzzle/requirements.txt b/tasks/agentescape-25-skeleton-a8a2cf21/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-25-skeleton-a8a2cf21/environment/puzzle/requirements.txt @@ -0,0 +1,57 @@ +annotated-doc==0.0.5 + # via fastapi +annotated-types==0.8.0 + # via pydantic +anyio==4.16.0 + # via starlette +certifi==2026.10.23 + # via requests +cffi==2.1.1 ; platform_python_implementation != 'PyPy' + # via cryptography +charset-normalizer==3.5.2 + # via requests +click==8.5.0 + # via uvicorn +cryptography==50.0.2 + # via agentescapebench-harbor +fastapi==0.162.0 + # via agentescapebench-harbor +h11==0.16.0 + # via uvicorn +idna==3.20 + # via + # anyio + # requests +opentelemetry-api==1.45.2 + # via fastapi +pycparser==3.12 ; implementation_name != 'PyPy' and platform_python_implementation != 'PyPy' + # via cffi +pydantic==2.14.2 + # via + # agentescapebench-harbor + # fastapi +pydantic-core==2.50.2 + # via pydantic +pytz==2025.2 + # via agentescapebench-harbor +requests==2.34.2 + # via agentescapebench-harbor +starlette==1.10.0 + # via fastapi +typing-extensions==4.16.0 + # via + # anyio + # fastapi + # opentelemetry-api + # pydantic + # pydantic-core + # starlette + # typing-inspection +typing-inspection==0.4.4 + # via + # fastapi + # pydantic +urllib3==2.8.0 + # via requests +uvicorn==0.54.0 + # via agentescapebench-harbor diff --git a/tasks/agentescape-25-skeleton-a8a2cf21/environment/puzzle/scenario.json b/tasks/agentescape-25-skeleton-a8a2cf21/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..541fb46924888a1a4bc2baaea00bc25aa3bb711d --- /dev/null +++ b/tasks/agentescape-25-skeleton-a8a2cf21/environment/puzzle/scenario.json @@ -0,0 +1,1401 @@ +{ + "metadata": { + "total_nodes": 25, + "total_edges": 28, + "win_node_id": "item_7", + "win_condition": { + "type": "item_content", + "node_id": "item_7", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_7", + "terminal_2", + "graph_shortest_path", + "json_get", + "zip_unzip_file", + "calc_inv_mod", + "graph_shortest_path_fc39", + "crypto_rsa_decrypt_hex", + "time_convert", + "calc_bigmul", + "zip_unzip_item", + "item_9", + "item_3" + ], + "by_node": { + "item_7": { + "node_name": "", + "node_type": "Item", + "template_id": "item_7", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Code_Python", + "description": "The integer" + } + } + }, + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": { + "num2": { + "type": "Big_Int", + "description": "Second Number" + } + }, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + } + } + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": {}, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "json_get": { + "node_name": "JSON Getter", + "node_type": "Tool", + "template_id": "json_get", + "init_inputs": {}, + "init_outputs": { + "values": { + "type": "Text_Generic", + "description": "Extracted values" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "calc_inv_mod": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "Integer a" + } + }, + "init_outputs": {} + }, + "graph_shortest_path_fc39": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "Graph JSON file ID" + }, + "src": { + "type": "Text_Generic", + "description": "Source node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "crypto_rsa_decrypt_hex": { + "node_name": "RSA Decrypt", + "node_type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "init_inputs": { + "hex_cipher": { + "type": "Hex_String", + "description": "Ciphertext (Hex)" + }, + "n": { + "type": "Big_Int", + "description": "Modulus n" + }, + "d": { + "type": "Big_Int", + "description": "Private exponent d" + } + }, + "init_outputs": {} + }, + "time_convert": { + "node_name": "Timezone Converter", + "node_type": "Tool", + "template_id": "time_convert", + "init_inputs": { + "iso": { + "type": "Text_Generic", + "description": "ISO Timestamp" + }, + "from_tz": { + "type": "Text_Generic", + "description": "From Timezone" + }, + "to_tz": { + "type": "Text_Generic", + "description": "To Timezone" + } + }, + "init_outputs": {} + }, + "calc_bigmul": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First large integer" + }, + "b": { + "type": "Big_Int", + "description": "Second large integer" + } + }, + "init_outputs": {} + }, + "zip_unzip_item": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_item", + "init_inputs": { + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": {} + }, + "item_9": { + "node_name": "", + "node_type": "Item", + "template_id": "item_9", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "File_Id", + "description": "JSON file path" + } + } + }, + "item_3": { + "node_name": "", + "node_type": "Item", + "template_id": "item_3", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Hex_String", + "description": "The hex code" + } + } + } + } + }, + "initial_values": { + "item_7": { + "init_inputs": {}, + "init_outputs": { + "content": "def get_integer():\n return 42\n" + } + }, + "terminal_2": { + "init_inputs": { + "num2": "8394827163849502938475" + }, + "init_outputs": { + "text_result": "Partial output evaluated successfully.", + "hex_result": "deadbeef1234567890abcdef" + } + }, + "graph_shortest_path": { + "init_inputs": {}, + "init_outputs": { + "path": "[\"NodeA\", \"NodeD\", \"NodeF\", \"NodeK\", \"NodeZ\"]", + "cost": "482910" + } + }, + "json_get": { + "init_inputs": {}, + "init_outputs": { + "values": "[\"value_1\", \"value_2\", \"value_3\", \"value_4\", \"value_5\"]" + } + }, + "zip_unzip_file": { + "init_inputs": { + "zip_id": "archive_data_738.zip" + }, + "init_outputs": { + "files": "extracted_documents_92.json" + } + }, + "calc_inv_mod": { + "init_inputs": { + "a": "5948372610594837261948" + }, + "init_outputs": {} + }, + "graph_shortest_path_fc39": { + "init_inputs": { + "file_id": "network_topology_map.json", + "src": "EntryPoint_Alpha" + }, + "init_outputs": { + "path": "[\"Start\", \"Router1\", \"SwitchA\", \"Gateway\", \"TargetNode\"]", + "cost": "738291" + } + }, + "crypto_rsa_decrypt_hex": { + "init_inputs": { + "hex_cipher": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d", + "n": "987654321098765432109876543210", + "d": "123456789012345678901234567890" + }, + "init_outputs": {} + }, + "time_convert": { + "init_inputs": { + "iso": "2023-10-15T14:30:00Z", + "from_tz": "UTC", + "to_tz": "America/New_York" + }, + "init_outputs": {} + }, + "calc_bigmul": { + "init_inputs": { + "a": "4445556667778889990001", + "b": "1112223334445556667778" + }, + "init_outputs": {} + }, + "zip_unzip_item": { + "init_inputs": { + "password": "SecurePass2024!" + }, + "init_outputs": {} + }, + "item_9": { + "init_inputs": {}, + "init_outputs": { + "content": "configuration_settings.json" + } + }, + "item_3": { + "init_inputs": {}, + "init_outputs": { + "content": "badc0ffee0ddf00d" + } + } + }, + "intro_narrative": "Welcome, traveler, to the forgotten Sanctuary of the Archmage. Here, magic and arcane machinery intertwine, guarding secrets long thought lost to the ages. The Archmage sealed his ultimate treasure, The Royal Seal, deep within this sanctum before his sudden disappearance. You stand in the grand antechamber, surrounded by cryptic artifacts, silent constructs, and enchanted stones. Your objective is clear: navigate this labyrinth of arcane logic, harness the powers of ancient relics, and retrieve the Seal. But beware, the path is fraught with interwoven wards and dependencies. You must decipher the flows of magical energy and figure out which artifacts awaken each other. Trust your intuition and intellect to conquer the sanctuary's trials and prove your worth.", + "narrative_style": "fantasy" + }, + "nodes": [ + { + "id": "item_7", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_7", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Code_Python", + "description": "The integer", + "value": "def get_integer():\n return 42\n" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "def get_integer():\n return 42\n" + } + }, + "narrative": "The Royal Seal, the ultimate symbol of the lost kingdom's authority, resting upon a velvet cushion." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A glowing Moonstone Artifact, pulsating with gentle lunar energy." + }, + { + "id": "container_3", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_3", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Big_Int", + "description": "Fingerprint Hash", + "value": "482910" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is The Silver Chest, bound by magical wards. It requires input from The Leyline Navigator to unlock." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A translucent Ethereal Gem that seems to float effortlessly in your hand." + }, + { + "id": "item_16_33d4", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A radiant Sunstone Artifact, warm to the touch and blazing with inner light." + }, + { + "id": "terminal_2", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "738291" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "8394827163849502938475" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Partial output evaluated successfully." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "deadbeef1234567890abcdef" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": { + "num2": "8394827163849502938475" + }, + "outputs": { + "text_result": "Partial output evaluated successfully.", + "hex_result": "deadbeef1234567890abcdef" + } + }, + "narrative": "This is The Oracle's Altar. It requires input from The Alchemist's Crucible to speak the ancient prophecies." + }, + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "extracted_documents_92.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "[\"value_1\", \"value_2\", \"value_3\", \"value_4\", \"value_5\"]" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Partial output evaluated successfully." + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"NodeA\", \"NodeD\", \"NodeF\", \"NodeK\", \"NodeZ\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "482910" + } + ], + "init": { + "inputs": {}, + "outputs": { + "path": "[\"NodeA\", \"NodeD\", \"NodeF\", \"NodeK\", \"NodeZ\"]", + "cost": "482910" + } + }, + "narrative": "This is The Leyline Navigator. It requires inputs from The Oracle's Altar, The Spirit Reader, and The Spell Unbinder to chart the magical currents." + }, + { + "id": "json_get", + "name": "JSON Getter", + "description": "Extract values by simple JSONPath.", + "type": "Tool", + "template_id": "json_get", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "JSON file ID", + "value": "extracted_documents_92.json" + }, + { + "name": "jsonpath", + "type": "Text_Generic", + "description": "JSONPath expression", + "value": "\u0001oG~\tqwu" + } + ], + "outputs": [ + { + "name": "values", + "type": "Text_Generic", + "description": "Extracted values", + "value": "[\"value_1\", \"value_2\", \"value_3\", \"value_4\", \"value_5\"]" + } + ], + "init": { + "inputs": {}, + "outputs": { + "values": "[\"value_1\", \"value_2\", \"value_3\", \"value_4\", \"value_5\"]" + } + }, + "narrative": "This is The Spirit Reader. It requires inputs from The Spell Unbinder and The Rune Decipherer to channel the spirits." + }, + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "archive_data_738.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Partial output evaluated successfully." + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_documents_92.json" + } + ], + "init": { + "inputs": { + "zip_id": "archive_data_738.zip" + }, + "outputs": { + "files": "extracted_documents_92.json" + } + }, + "narrative": "This is The Spell Unbinder. It requires input from The Oracle's Altar to break the protective wards." + }, + { + "id": "num_base_convert", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "738291" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "5948372610594837261948" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "4944451860503714814811970487770485298887778" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "738291" + } + ], + "narrative": "This is The Alchemist's Crucible. It requires inputs from The Astral Reverser, The Starpath Navigator, and The Mana Multiplier to transmute the elements." + }, + { + "id": "calc_inv_mod", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "5948372610594837261948" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": 1896241797 + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "5948372610594837261948" + } + ], + "init": { + "inputs": { + "a": "5948372610594837261948" + }, + "outputs": {} + }, + "narrative": "This is The Astral Reverser, a device that inverts magical flows. It requires input from The Essence Purifier." + }, + { + "id": "container_3_eeca", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_3", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Big_Int", + "description": "Fingerprint Hash", + "value": "738291" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is The Golden Chest, sealed with celestial magic. It requires input from The Starpath Navigator to open." + }, + { + "id": "graph_shortest_path_fc39", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "network_topology_map.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "EntryPoint_Alpha" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "2023-10-15T10:30:00-04:00" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Start\", \"Router1\", \"SwitchA\", \"Gateway\", \"TargetNode\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "738291" + } + ], + "init": { + "inputs": { + "file_id": "network_topology_map.json", + "src": "EntryPoint_Alpha" + }, + "outputs": { + "path": "[\"Start\", \"Router1\", \"SwitchA\", \"Gateway\", \"TargetNode\"]", + "cost": "738291" + } + }, + "narrative": "This is The Starpath Navigator. It requires input from The Chronos Pendulum to plot the celestial coordinates." + }, + { + "id": "item_8_8f97", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A deep black Void Crystal, seemingly absorbing all surrounding light into its core." + }, + { + "id": "crypto_rsa_decrypt_hex", + "name": "RSA Decrypt", + "description": "RSA decrypt (hex cipher) with n,d (decimal).", + "type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex_cipher", + "type": "Hex_String", + "description": "Ciphertext (Hex)", + "value": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Modulus n", + "value": "987654321098765432109876543210" + }, + { + "name": "d", + "type": "Big_Int", + "description": "Private exponent d", + "value": "123456789012345678901234567890" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decrypted text", + "value": "\u0001oG~\tqwu" + } + ], + "init": { + "inputs": { + "hex_cipher": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d", + "n": "987654321098765432109876543210", + "d": "123456789012345678901234567890" + }, + "outputs": {} + }, + "narrative": "The Rune Decipherer, a stone tablet covered in translating runes that hum softly." + }, + { + "id": "time_convert", + "name": "Timezone Converter", + "description": "Convert ISO time between timezones.", + "type": "Tool", + "template_id": "time_convert", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "iso", + "type": "Text_Generic", + "description": "ISO Timestamp", + "value": "2023-10-15T14:30:00Z" + }, + { + "name": "from_tz", + "type": "Text_Generic", + "description": "From Timezone", + "value": "UTC" + }, + { + "name": "to_tz", + "type": "Text_Generic", + "description": "To Timezone", + "value": "America/New_York" + } + ], + "outputs": [ + { + "name": "iso", + "type": "Text_Generic", + "description": "Converted ISO Timestamp", + "value": "2023-10-15T10:30:00-04:00" + } + ], + "init": { + "inputs": { + "iso": "2023-10-15T14:30:00Z", + "from_tz": "UTC", + "to_tz": "America/New_York" + }, + "outputs": {} + }, + "narrative": "The Chronos Pendulum, a magical artifact that sways continuously regardless of gravity." + }, + { + "id": "item_8_ed94", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A cold Shadow Tear, whispering forgotten secrets into the mind of its holder." + }, + { + "id": "calc_bigmul", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "4445556667778889990001" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "1112223334445556667778" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "4944451860503714814811970487770485298887778" + } + ], + "init": { + "inputs": { + "a": "4445556667778889990001", + "b": "1112223334445556667778" + }, + "outputs": {} + }, + "narrative": "The Mana Multiplier, an intricate brass astrolabe crackling with chaotic energy." + }, + { + "id": "checksum_crc32", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "badc0ffee0ddf00d" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "71065a85" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 1896241797 + } + ], + "narrative": "This is The Essence Purifier, an enchanted basin. It requires input from The Dragon Scale to work." + }, + { + "id": "item_8_448d", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A dark Blood Opal, swirling with crimson shadows and pulsing like a heartbeat." + }, + { + "id": "zip_unzip_item", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_item", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "configuration_settings.json" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "SecurePass2024!" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip" + } + ], + "init": { + "inputs": { + "password": "SecurePass2024!" + }, + "outputs": {} + }, + "narrative": "This is The Curse Breaker. It requires input from The Ancient Scroll to lift the complex hex." + }, + { + "id": "item_9", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_9", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "File_Id", + "description": "JSON file path", + "value": "configuration_settings.json" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "configuration_settings.json" + } + }, + "narrative": "A fragile Ancient Scroll bound with a dusty ribbon, smelling of old parchment." + }, + { + "id": "item_8_cc60", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A piece of Forest Amber containing a trapped, glowing fairy frozen in time." + }, + { + "id": "item_3", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_3", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hex_String", + "description": "The hex code", + "value": "badc0ffee0ddf00d" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "badc0ffee0ddf00d" + } + }, + "narrative": "A shimmering Dragon Scale, hard as diamond and inscribed with powerful runes." + }, + { + "id": "item_8_f6e6", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A brilliant Frost Diamond that never melts, radiating a freezing aura." + } + ], + "edges": [ + { + "source_id": "item_16", + "target_id": "item_7", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "container_3", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "item_8", + "target_id": "container_3", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "item_16_33d4", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "terminal_2", + "target_id": "item_16_33d4", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "source_tool" + }, + { + "source_id": "graph_shortest_path", + "target_id": "container_3", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "fingerprint_input" + }, + { + "source_id": "terminal_2", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "dst" + }, + { + "source_id": "json_get", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "values", + "target_port": "src" + }, + { + "source_id": "zip_unzip_file", + "target_id": "json_get", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "terminal_2", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "password" + }, + { + "source_id": "num_base_convert", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "num1" + }, + { + "source_id": "calc_inv_mod", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "from_base" + }, + { + "source_id": "container_3_eeca", + "target_id": "calc_inv_mod", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "graph_shortest_path_fc39", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "s" + }, + { + "source_id": "item_8_8f97", + "target_id": "container_3_eeca", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "graph_shortest_path_fc39", + "target_id": "container_3_eeca", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "fingerprint_input" + }, + { + "source_id": "crypto_rsa_decrypt_hex", + "target_id": "json_get", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "jsonpath" + }, + { + "source_id": "time_convert", + "target_id": "graph_shortest_path_fc39", + "connection_type": "Text_Generic", + "source_port": "iso", + "target_port": "dst" + }, + { + "source_id": "item_8_ed94", + "target_id": "item_8_8f97", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "calc_bigmul", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "to_base" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "mod" + }, + { + "source_id": "item_8_448d", + "target_id": "item_8_ed94", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "zip_unzip_item", + "target_id": "time_convert", + "connection_type": "Item", + "source_port": "item", + "target_port": "trigger_item" + }, + { + "source_id": "item_9", + "target_id": "zip_unzip_item", + "connection_type": "File_Id", + "source_port": "content", + "target_port": "zip_id" + }, + { + "source_id": "item_8_cc60", + "target_id": "item_8_448d", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_3", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "content", + "target_port": "hex" + }, + { + "source_id": "item_8_f6e6", + "target_id": "item_3", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-a8a2cf21/environment/puzzle/service.py b/tasks/agentescape-25-skeleton-a8a2cf21/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-25-skeleton-a8a2cf21/environment/puzzle/service.py @@ -0,0 +1,212 @@ +"""Restricted facade over the unchanged, pinned upstream puzzle handlers.""" + +import hashlib +import json +import logging +import os +import sys +import threading +import urllib.request +import uuid +from pathlib import Path + +from fastapi import FastAPI, HTTPException +from fastapi.responses import JSONResponse +from pydantic import BaseModel, ConfigDict + +sys.path.insert(0, str(Path(__file__).parent / "upstream")) +import server as upstream # noqa: E402 + +log = logging.getLogger(__name__) + + +def public(value): + """Keep upstream agent-internal template hints out of the public response.""" + if isinstance(value, dict): + return {k: public(v) for k, v in value.items() if not k.startswith("_")} + if isinstance(value, list): + return [public(v) for v in value] + return value + + +class Action(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + action: str + node_id: str | None = None + arguments: dict | None = None + answer: str | None = None + + +class Episode: + def __init__( + self, scenario_path, max_actions=500, evidence_dir=None, worker_url=None + ): + if max_actions < 1: + raise ValueError("max_actions must be positive") + self.lock = threading.Lock() + self.max_actions = max_actions + self.count = 0 + self.won = False + self.reason = None + self.evidence_dir = Path(evidence_dir) if evidence_dir else None + self.scenario_hash = hashlib.sha256( + Path(scenario_path).read_bytes() + ).hexdigest() + self.initial = upstream.reset_case( + case_file_path=str(scenario_path), session_id=uuid.uuid4().hex + ) + self.case_id = self.initial["case_id"] + # Hide source file paths; no upstream reset/stats/routes are mounted. + self.initial.pop("message", None) + simulator = upstream.SIMULATORS[self.case_id] + if worker_url is None: + + def no_worker(_inputs): + self.reason = "infrastructure_error" + raise RuntimeError("isolated Python worker is not configured") + + simulator.tool_map["code_py_exec"] = no_worker + else: + + def execute_python(inputs): + request = urllib.request.Request( + worker_url + "/execute", + data=json.dumps({"code": inputs.get("code", "")}).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=12) as response: + result = json.load(response) + if not isinstance(result.get("stdout"), str): + raise RuntimeError("Invalid Python worker response") + return result + except Exception: + self.reason = "infrastructure_error" + raise + + simulator.tool_map["code_py_exec"] = execute_python + self.save() + if self.evidence_dir is not None: + (self.evidence_dir / "trace.jsonl").touch() + + def state(self): + return { + "scenario_sha256": self.scenario_hash, + "action_count": self.count, + "max_actions": self.max_actions, + "won": self.won, + "termination_reason": self.reason, + } + + def save(self, action=None, result=None): + if self.evidence_dir is None: + return + self.evidence_dir.mkdir(parents=True, exist_ok=True) + target = self.evidence_dir / "outcome.json" + temp = target.with_suffix(".tmp") + temp.write_text(json.dumps(self.state())) + temp.replace(target) + if action is not None: + with (self.evidence_dir / "trace.jsonl").open("a") as handle: + handle.write( + json.dumps( + {"index": self.count, "action": action, "result": result} + ) + + "\n" + ) + + def dispatch(self, payload): + with self.lock: + if self.reason is not None: + return { + "ok": False, + "error": "Episode has ended", + "episode": self.state(), + } + self.count += 1 + try: + action = Action.model_validate(payload) + if action.action == "submit_answer" and action.answer is not None: + result = upstream.submit_answer( + self.case_id, upstream.SubmitAnswerRequest(answer=action.answer) + ) + if result.get("is_win"): + self.won = True + self.reason = "success" + elif action.action == "investigate" and action.node_id is not None: + result = upstream.investigate( + self.case_id, + upstream.InvestigateRequest(node_id=action.node_id), + ) + elif ( + action.action in ("tool_call", "use_item") + and action.node_id is not None + ): + request_type, handler = ( + (upstream.ToolCallRequest, upstream.tool_call) + if action.action == "tool_call" + else (upstream.UseItemRequest, upstream.use_item) + ) + result = handler( + self.case_id, + request_type( + node_id=action.node_id, arguments=action.arguments or {} + ), + ) + else: + result = { + "ok": False, + "error": "Unknown action or missing action parameter", + } + except HTTPException as exc: + result = {"ok": False, "error": exc.detail} + except ValueError: + result = {"ok": False, "error": "Malformed action"} + except Exception: + log.exception("Puzzle service failure") + self.reason = "infrastructure_error" + self.save() + raise + if self.reason is None and self.count >= self.max_actions: + self.reason = "action_budget_exhausted" + result = public(result) + result["episode"] = self.state() + self.save(payload, result) + return result + + +def create_app( + scenario_path=None, max_actions=None, evidence_dir=None, worker_url=None +): + episode = Episode( + scenario_path or os.environ["SCENARIO_PATH"], + max_actions or int(os.environ.get("MAX_ACTIONS", "500")), + evidence_dir if evidence_dir is not None else os.environ.get("EVIDENCE_DIR"), + worker_url if worker_url is not None else os.environ.get("WORKER_URL"), + ) + app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) + app.state.episode = episode + + @app.get("/health") + def health(): + return {"ok": True} + + @app.get("/observation") + def observation(): + return {**public(episode.initial), "episode": episode.state()} + + @app.get("/state") + def state(): + return episode.state() + + @app.post("/action") + def action(payload: dict): + try: + return episode.dispatch(payload) + except Exception: + return JSONResponse( + status_code=503, + content={"ok": False, "error": "Puzzle infrastructure failure"}, + ) + + return app diff --git a/tasks/agentescape-25-skeleton-a8a2cf21/environment/puzzle/upstream/models.py b/tasks/agentescape-25-skeleton-a8a2cf21/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-25-skeleton-a8a2cf21/environment/puzzle/upstream/models.py @@ -0,0 +1,108 @@ +from enum import Enum +from typing import List, Dict, Any, Optional +from pydantic import BaseModel, Field + +# 1. 细粒度接口类型定义 +class InterfaceType(str, Enum): + ''' + BIG_INT + TEXT_GENERIC + HEX_STRING + FILE_ID + HEX_STRING_KEY_AES + HEX_STRING_IV_AES + CODE_PYTHON + HIDDEN_ITEM + ITEM + ''' + # --- 基础类型 --- + TEXT_GENERIC = "Text_Generic" + BIG_INT = "Big_Int" + + # --- 编码/格式化字符串 --- + HEX_STRING = "Hex_String" # 通用 Hex + + # --- 特定用途的 Hex 字符串 (用于精确匹配) --- + HEX_STRING_KEY_AES = "Hex_String_Key_AES" + HEX_STRING_IV_AES = "Hex_String_IV_AES" + + # --- 文件类型 --- + FILE_ID = "File_Id" + + # --- 代码/脚本 --- + CODE_PYTHON = "Code_Python" + + # --- 实体交互类型 (严格命名) --- + ITEM = "Item" # 主动掉落接口 (Tool -> Item) + HIDDEN_ITEM = "Hidden_Item" # 被动掉落接口 (Item -> Item) + +# 3. 端口定义 +class Port(BaseModel): + name: str + type: InterfaceType + description: str + +# 4. 统一节点定义 (融合工具和物品) +class Node(BaseModel): + id: str + name: str + description: str + type: str # "Tool" or "Item" + + # 接口定义 + inputs: List[Port] = [] + outputs: List[Port] = [] + + # 状态字段 + content: Optional[Any] = None # 物品有内容,工具为None + if_success: Optional[bool] = None # 工具初始为False,物品为None + initial_visible: bool = False + + # 运行时状态 (Server维护) + is_revealed: bool = False + + # 标记该 Tool 节点是否有待触发的 HIDDEN_ITEM 掉落 + # 当 Tool 按照 golden_input 正确执行且有 HIDDEN_ITEM 输出边时设为 True + # 在 investigate 该 Tool 时触发掉落并重置为 False + has_hidden_item_ready: bool = False + + # 初始输入值 (metadata.initial_values.init_inputs,用于渐进式暴露判断) + init_input_values: Dict[str, Any] = {} + + # Golden 输入值 (nodes[].inputs[].value,用于评测验证) + golden_input_values: Dict[str, Any] = {} + + # Golden 输出值 (nodes[].outputs[].value,用于评测验证和 Item 节点的 content) + golden_output_values: Dict[str, Any] = {} + + # 实际获得的输出值历史 (工具每次执行后实际返回的输出列表,用于渐进式暴露判断) + # 格式: List[Dict[str, Any]],每个元素是一次执行的输出字典 + actual_outputs_history: List[Dict[str, Any]] = [] + + # 逻辑规则 (用于终端机等复杂物品) + logic_rules: Optional[Dict[str, Any]] = None + + def copy(self, **kwargs): + """Helper to create a copy with updated fields.""" + data = self.dict() + data.update(kwargs) + return Node(**data) + +# 5. 边定义 (拓扑结构) +class Edge(BaseModel): + source_id: str + target_id: str + connection_type: InterfaceType # 直接使用 InterfaceType + # 如果是 Data_Flow,指定端口对应关系 + source_port: Optional[str] = None + target_port: Optional[str] = None + +# 6. 完整图定义 +class GraphScenario(BaseModel): + case_id: str + title: str + intro_narrative: str + nodes: Dict[str, Node] + edges: List[Edge] + difficulty: int + win_node_id: str # 标记哪个节点是最终目标(通常是一个提交工具或最终物品) diff --git a/tasks/agentescape-25-skeleton-a8a2cf21/environment/puzzle/upstream/server.py b/tasks/agentescape-25-skeleton-a8a2cf21/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-25-skeleton-a8a2cf21/environment/puzzle/upstream/server.py @@ -0,0 +1,1490 @@ +import json +import os +import time +import logging +import random +from pathlib import Path +from typing import Dict, Any, List, Optional +from datetime import datetime +from collections import defaultdict +from fastapi import FastAPI, HTTPException, Request +from fastapi.responses import JSONResponse +from fastapi.middleware.cors import CORSMiddleware +from pydantic import BaseModel, Field + +from models import GraphScenario, Node, InterfaceType +# from generator import ScenarioGenerator +from simulator import ToolSimulator +import uvicorn + +# 配置日志 +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler('server.log'), + logging.StreamHandler() + ] +) +logger = logging.getLogger(__name__) + +app = FastAPI( + title="AgentEscapeBench Universal Server", + version="1.0.0", + description="Industrial-grade evaluation server for escape room AI agents" +) + +# 添加 CORS 支持 +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# In-memory State +SCENARIOS: Dict[str, GraphScenario] = {} +SIMULATORS: Dict[str, ToolSimulator] = {} # case_id -> ToolSimulator +RAW_NODES_DATA: Dict[str, Dict[str, Any]] = {} # case_id -> node_id -> raw node data (for template_id) +FILE_METADATA: Dict[str, Dict[str, Any]] = {} # case_id -> metadata (for initial_values access) + +# Performance monitoring +STATS: Dict[str, Any] = { + "total_requests": 0, + "successful_requests": 0, + "failed_requests": 0, + "tool_calls": defaultdict(int), + "investigates": defaultdict(int), + "use_items": defaultdict(int), + "case_loads": 0, + "start_time": datetime.now() +} + +# Request timing middleware +@app.middleware("http") +async def add_process_time_header(request: Request, call_next): + start_time = time.time() + STATS["total_requests"] += 1 + + try: + response = await call_next(request) + STATS["successful_requests"] += 1 + process_time = time.time() - start_time + response.headers["X-Process-Time"] = str(process_time) + logger.info(f"{request.method} {request.url.path} - {response.status_code} - {process_time:.3f}s") + return response + except Exception as e: + STATS["failed_requests"] += 1 + logger.error(f"{request.method} {request.url.path} - Error: {str(e)}") + raise + +# Exception handler +@app.exception_handler(Exception) +async def global_exception_handler(request: Request, exc: Exception): + logger.error(f"Unhandled exception: {exc}", exc_info=True) + return JSONResponse( + status_code=500, + content={ + "ok": False, + "error": "Internal server error", + "detail": str(exc) if os.getenv("DEBUG") else "An error occurred" + } + ) + +# Health check endpoint +@app.get("/health") +def health_check(): + """健康检查端点""" + uptime = (datetime.now() - STATS["start_time"]).total_seconds() + return { + "status": "healthy", + "version": "1.0.0", + "uptime_seconds": uptime, + "loaded_cases": len(SCENARIOS), + "stats": { + "total_requests": STATS["total_requests"], + "successful_requests": STATS["successful_requests"], + "failed_requests": STATS["failed_requests"], + "success_rate": STATS["successful_requests"] / max(STATS["total_requests"], 1) + } + } + +# Statistics endpoint +@app.get("/stats") +def get_stats(): + """获取详细统计信息""" + return { + "stats": STATS, + "loaded_cases": list(SCENARIOS.keys()), + "uptime": str(datetime.now() - STATS["start_time"]) + } + +def _apply_progressive_reveal_at_init(scenario: GraphScenario): + """ + 在初始化时应用渐进式暴露机制(基于ITEM/HIDDEN_ITEM边) + + 新逻辑: + - 如果一个节点没有 ITEM/HIDDEN_ITEM 类型的入边,它就是初始可见的 + - 如果一个节点有 ITEM/HIDDEN_ITEM 类型的入边,它初始不可见,需要等待上游触发 + + Args: + scenario: 场景对象 + """ + # 收集所有有 ITEM/HIDDEN_ITEM 入边的节点 + nodes_with_item_edges = set() + for edge in scenario.edges: + if edge.connection_type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + nodes_with_item_edges.add(edge.target_id) + + logger.info(f"Nodes with ITEM/HIDDEN_ITEM incoming edges: {nodes_with_item_edges}") + + # 设置初始可见性:没有 ITEM/HIDDEN_ITEM 入边的节点初始可见 + initially_visible_count = 0 + for node_id, node in scenario.nodes.items(): + if node_id not in nodes_with_item_edges: + node.is_revealed = True + initially_visible_count += 1 + logger.info(f"Initial visible (no ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + else: + node.is_revealed = False + logger.debug(f"Initial hidden (has ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + + logger.info(f"Progressive reveal initialized: {initially_visible_count}/{len(scenario.nodes)} nodes initially visible") + + +def _check_inputs_match_golden(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> bool: + """ + 检查实际输入参数是否与 golden inputs 完全匹配 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + True 表示所有 golden inputs 都存在且值匹配 + """ + if not golden_inputs: + return True # 如果没有 golden inputs,认为匹配 + + for key, expected_value in golden_inputs.items(): + actual_value = arguments.get(key) + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) != str(expected_value): + logger.debug(f"Input mismatch for '{key}': expected '{expected_value}', got '{actual_value}'") + return False + + return True + + +def _get_parameter_validation_feedback(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> Dict[str, Any]: + """ + 对源头节点的参数进行详细验证,返回验证反馈 + + 注意:不返回期望值(expected),避免泄漏答案 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + 包含验证结果的字典: + - all_correct: bool - 所有参数是否正确 + - correct_params: List[str] - 正确的参数名列表 + - incorrect_params: List[str] - 错误的参数名列表(不包含期望值) + """ + if not golden_inputs: + return { + "all_correct": True, + "correct_params": [], + "incorrect_params": [] + } + + correct_params = [] + incorrect_params = [] + + for key, actual_value in arguments.items(): + # 只对用户实际提交的参数给反馈,未提交的参数不评价 + if key not in golden_inputs: + continue # 该参数不在 golden 中,跳过(如 _golden_inputs 等内部参数) + expected_value = golden_inputs[key] + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) == str(expected_value): + correct_params.append(key) + else: + # 只记录参数名,不包含期望值,避免泄漏答案 + incorrect_params.append(key) + + # all_correct:用户提交的所有参数都正确,且覆盖了全部 golden 参数 + all_provided_correct = len(incorrect_params) == 0 + all_golden_covered = all(k in arguments for k in golden_inputs) + return { + "all_correct": all_provided_correct and all_golden_covered, + "correct_params": correct_params, + "incorrect_params": incorrect_params + } + + +def _is_source_node(node_id: str, scenario: GraphScenario) -> bool: + """ + 判断节点是否是源头节点(完全没有任何入边的节点) + + 源头节点定义: + - 没有任何类型的入边(包括 DATA、ITEM、HIDDEN_ITEM) + - 即没有任何上游节点 + + Args: + node_id: 节点ID + scenario: 场景对象 + + Returns: + True 表示是源头节点 + """ + for edge in scenario.edges: + if edge.target_id == node_id: + # 只要有任何入边,就不是源头节点 + return False + + return True + + +def _check_and_reveal_ready_nodes(scenario: GraphScenario, recent_outputs: Dict[str, Any], source_node_id: str) -> List[Dict[str, Any]]: + """ + 检查并释放参数齐全的隐藏节点(渐进式暴露机制) + + 核心逻辑: + 1. 维护"可见值集合":包含所有被测模型当前可以看到的值 + - init_inputs 的值(初始可见) + - 工具执行后的实际输出值(运行时获得) + - 可见 Item 的输出值 + 2. 检查隐藏节点:该节点的所有 golden_input 值是否都在可见值集合中 + 3. 如果是,则释放该节点 + + Args: + scenario: 场景对象 + recent_outputs: 最近执行的工具的输出 + source_node_id: 刚执行的工具节点ID + + Returns: + 新释放的节点列表 + """ + newly_revealed = [] + + # 构建"可见值集合"(Set of visible values) + # 存储格式:set of values (转为字符串) + visible_values = set() + + # 1. 添加有意义的 init_inputs 值到可见值集合 + # Item 的 init_inputs 不应该加入,因为它们在密室中完全用不到 + for node_id, node in scenario.nodes.items(): + # 跳过源头 Item 节点(没有入边的 Item) + if node.type == "Item": + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,跳过其 init_inputs + continue + + # 添加其他节点的 init_inputs + for port_name, init_value in node.init_input_values.items(): + if init_value: + visible_values.add(str(init_value)) + + # 2. 添加已执行工具的所有历史输出值 + for node_id, node in scenario.nodes.items(): + if node.type == "Tool" and node.if_success and node.actual_outputs_history: + # 遍历所有历史执行记录 + for output_dict in node.actual_outputs_history: + for output_port_name, output_value in output_dict.items(): + if output_value: + visible_values.add(str(output_value)) + + # 3. 添加已被 investigate 的 Item 的 golden 输出值 + # 注意:Item 可见不等于其输出值可见,需要 investigate 后才能获得 + # 这里我们使用 actual_outputs_history 来标记 Item 是否已被 investigate + for node_id, node in scenario.nodes.items(): + if node.type == "Item" and node.is_revealed and node.actual_outputs_history: + # Item 通常只会被 investigate 一次,但为了一致性也使用历史列表 + for output_dict in node.actual_outputs_history: + for port_name, port_value in output_dict.items(): + if port_value: + visible_values.add(str(port_value)) + + # 遍历所有隐藏的节点,检查其 golden_input 是否都在可见值集合中 + for node_id, node in scenario.nodes.items(): + # 跳过已可见的节点 + if node.is_revealed: + continue + + # 只检查工具节点(物品节点由 ITEM 输出触发) + if node.type != "Tool": + continue + + # 检查该节点的所有 golden_input 值是否都在可见值集合中 + all_inputs_ready = True + missing_values = [] + + for input_port_name, golden_input_value in node.golden_input_values.items(): + # 检查这个 golden 值是否在可见值集合中 + if str(golden_input_value) not in visible_values: + all_inputs_ready = False + missing_values.append(f"{input_port_name}={golden_input_value}") + + # 如果所有 golden_input 值都在可见值集合中,释放该节点 + if all_inputs_ready and len(node.golden_input_values) > 0: + logger.info(f"All golden inputs ready for {node_id}: {list(node.golden_input_values.values())}") + + # 如果所有输入都齐全,释放该节点 + if all_inputs_ready: + node.is_revealed = True + + # 构建节点信息返回给模型 + node_info = { + "id": node.id, + "type": node.type, + "can_investigate": True, + "hint": "This tool's input parameters are now complete, you can use investigate to view detailed information" + } + + # if node.name: + # node_info["name"] = node.name + if node.description: + node_info["description"] = node.description + + newly_revealed.append(node_info) + logger.info(f"Progressive reveal: {node_id} is now ready (all inputs satisfied)") + + return newly_revealed + + +def _initialize_node_values(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]): + """ + Initialize node state and load values from port value fields. + 应用渐进式暴露机制:初始时只显示参数齐全的节点(源头节点) + + 重要区分: + 1. input_values: 只加载 metadata.initial_values 中的 init_inputs(真正的初始值) + 2. output_values: 加载 nodes[].outputs[].value(golden 输出,用于验证) + """ + # 第一步:加载所有节点的值,并将所有节点初始设为隐藏 + initial_values = metadata.get('initial_values', {}) + + for node_id, node in scenario.nodes.items(): + # 忽略 initial_visible 字段,初始全部隐藏 + # 由渐进式暴露机制根据参数齐全情况决定是否显示 + node.is_revealed = False + + if node.type == "Tool": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + elif node.type == "Item": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + + # 从 JSON 加载值 + if node_id in raw_nodes_data: + node_data = raw_nodes_data[node_id] # node_data是json文件中nodes中的字典 + + # 【重要】只加载 metadata.initial_values 中的初始输入值 + if node_id in initial_values: + init_data = initial_values[node_id] + # 加载初始输入值(用于渐进式暴露判断) + for port_name, port_value in init_data.get('init_inputs', {}).items(): + node.init_input_values[port_name] = port_value + + # 【评测用】加载 golden 输入值(用于验证模型传入的参数是否正确) + for input_port_data in node_data.get('inputs', []): + if 'value' in input_port_data: + node.golden_input_values[input_port_data['name']] = input_port_data['value'] + + # 【评测用】加载 golden 输出值(用于验证工具调用是否正确,以及 Item 节点的 content) + for output_port_data in node_data.get('outputs', []): + if 'value' in output_port_data: + node.golden_output_values[output_port_data['name']] = output_port_data['value'] + + # For Items, set content from golden_output_values + if node.type == "Item" and node.golden_output_values: + # Item 的 content 是其第一个 golden 输出值 + node.content = list(node.golden_output_values.values())[0] + + # 第二步:应用渐进式暴露机制 + # 检查所有节点,根据参数齐全情况释放源头节点(工具 + Item) + _apply_progressive_reveal_at_init(scenario) + +def _build_node_info(node: Node, raw_nodes_data: Dict[str, Any]) -> Dict[str, Any]: + """ + 构建节点信息(工具或物品) + + Args: + node: 节点对象 + raw_nodes_data: 原始节点数据(用于获取 template_id 等) + + Returns: + 节点信息字典 + """ + if node.type == "Tool": + # 过滤掉输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口) + # 这些端口仅用于控制掉落机制,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + tool_info = { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Tool", + "inputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.inputs if p.type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]], + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id(工具的标准名称) + if node.id in raw_nodes_data: + node_data = raw_nodes_data[node.id] + template_id = node_data.get('template_id') + if template_id: + tool_info['template_id'] = template_id + + return tool_info + + elif node.type == "Item": + return { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Item" + } + + else: + return { + "id": node.id, + # "name": node.name, + "type": node.type + } + +def _get_initial_observation(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]) -> Dict[str, Any]: + """ + Generate initial observation for the agent (what they see when entering the room). + + 策略: + - Tools: 只显示名称和描述,不显示接口定义。需要 investigate 才能获得详细接口信息。 + - Items: 只显示存在,不显示内容。需要 investigate 才能获得内容值。 + - init_inputs: 作为"可用信息"告诉模型,这些是可以用作工具参数的初始值。 + - init_outputs: 不告诉模型(这些是答案,需要模型通过调用工具获得)。 + """ + available_entities = [] # 统一的实体列表(Tools 和 Items) + available_information = [] # 可用的初始信息(来自 init_inputs) + + # 从 metadata.initial_values 提取 init_inputs 作为可用信息 + # 只提供值本身,不透露这些值对应哪个节点的哪个参数,让模型自己推理 + # 注意:跳过源头 Item(没有入边的 Item)的 init_inputs,因为它们在密室中完全用不到 + initial_values = metadata.get('initial_values', {}) + # initial_values字段的格式 + # "initial_values": { + # "terminal_1": { + # "init_inputs": {}, + # "init_outputs": { + # "text_output": "System initialization complete.", + # "hex_output": "48656c6c6f20576f726c64", + # "item_dispenser": "掉落了一张纸条,上面写着“请勿随意触摸终端”" + # } + # } + # } + for node_id, init_data in initial_values.items(): + # 获取节点信息,判断是否为源头 Item + node = scenario.nodes.get(node_id) + if node and node.type == "Item": + # 检查是否为源头 Item(没有入边) + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,检查是否有 init_inputs + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 有 init_inputs,需要暴露这些参数 + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + # 处理完后跳过后续的通用逻辑 + continue + + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 为每个 init_input 值创建一个信息条目(不包含 source_node 和 parameter 信息) + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + + for node in scenario.nodes.values(): + if node.is_revealed: + # Tools: 只显示基本信息,提示可以 investigate 查看详细接口 + if node.type == "Tool": + tool_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Tool", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the tool's detailed interface information for calling" + } + # 只在 name 非空时添加 + # if node.name: + # tool_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_info["description"] = node.description + + available_entities.append(tool_info) + + # Items: 只显示基本信息,提示可以 investigate 查看内容 + elif node.type == "Item": + item_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Item", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the item's content" + } + # 只在 name 非空时添加 + # if node.name: + # item_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + item_info["description"] = node.description + + available_entities.append(item_info) + + return { + "narrative": scenario.intro_narrative, + "available_entities": available_entities, # 使用统一的实体列表 + "available_information": available_information, # 可用的初始信息(只包含 init_inputs) + "win_node_id": scenario.win_node_id # 胜利节点ID,让模型知道需要关注哪个节点 + } + +@app.post("/env/reset") +def reset_case(case_id: str = None, case_file_path: str = None, session_id: str = None): + """Loads a specific case from file and resets it. + + Args: + case_id: Optional case ID for resetting an existing case + case_file_path: Path to case file for loading a new case + session_id: Optional session ID to ensure isolation between concurrent evaluations + """ + logger.info(f"Reset request - case_id: {case_id}, case_file_path: {case_file_path}, session_id: {session_id}") + STATS["case_loads"] += 1 + + if case_file_path: + if not os.path.exists(case_file_path): + logger.error(f"Case file not found: {case_file_path}") + raise HTTPException(status_code=404, detail=f"File not found: {case_file_path}") + try: + with open(case_file_path, "r", encoding="utf-8") as f: + file_data = json.load(f) + + # 转换格式:从 DAG executor 生成的格式转换为 GraphScenario 格式 + # 1. 提取 metadata + metadata = file_data.get('metadata', {}) + + # 2. 生成 case_id, title, intro_narrative + # 【修复】为每个评测会话生成唯一的 case_id,防止并发评测时状态污染 + base_name = os.path.basename(case_file_path).replace('.json', '').replace('_full', '').replace('_full2', '') + + if session_id: + # 如果提供了 session_id,使用它来确保唯一性 + case_id = f"{base_name}_{session_id}" + else: + # 否则使用时间戳和随机数确保唯一性 + unique_suffix = f"{int(time.time() * 1000)}_{random.randint(1000, 9999)}" + case_id = f"{base_name}_{unique_suffix}" + + file_data['case_id'] = case_id + logger.info(f"Generated unique case_id: {case_id} (base: {base_name}, session: {session_id})") + + if 'title' not in file_data: + file_data['title'] = f"Escape Room: {file_data['case_id']}" + + if 'intro_narrative' not in file_data: # 目前的json文件中已经有了intro_narrative字段,不会使用下面一行的内容,而是使用每个评测问题的json文件中的对应字段 + 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]".' + + # 3. 转换 nodes 列表为字典(DAG executor 生成的文件中 nodes 是列表格式) + nodes_dict = {} + for node_data in file_data['nodes']: + nodes_dict[node_data['id']] = node_data # 这里的id是template_id之后可能添加一个后缀 + file_data['nodes'] = nodes_dict # 把列表转成一个字典 + + # 4. 添加缺失的字段 + if 'difficulty' not in file_data: + file_data['difficulty'] = metadata.get('total_nodes', 5) + + if 'win_node_id' not in file_data: + file_data['win_node_id'] = metadata.get('win_node_id', '') + + scenario = GraphScenario(**file_data) + + # Extract raw nodes data for template_id access + # nodes 已经在上面转换为字典格式 + raw_nodes_data = file_data.get('nodes', {}) + RAW_NODES_DATA[scenario.case_id] = raw_nodes_data + + # Store metadata for initial values access + FILE_METADATA[scenario.case_id] = metadata + + logger.info(f"Successfully parsed case file: {scenario.case_id}, nodes: {len(scenario.nodes)}, edges: {len(scenario.edges)}") + except Exception as e: + logger.error(f"Failed to load case file: {str(e)}", exc_info=True) + raise HTTPException(status_code=500, detail=f"Failed to load case file: {str(e)}") + + # Initialize node state and load values + _initialize_node_values(scenario, raw_nodes_data, metadata) + + SCENARIOS[scenario.case_id] = scenario + simulator = ToolSimulator() + SIMULATORS[scenario.case_id] = simulator + + 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'])}") + + # 生成初始观察信息(进入密室后看到的环境) + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + ''' + initial_observation的格式: + { + "narrative": scenario.intro_narrative, + "available_entities": available_entities # 使用统一的实体列表 + "available_information": available_information # 可用的初始信息(只包含 init_inputs) + } + ''' + + return { + "ok": True, + "message": f"Case loaded from {case_file_path}", + "case_id": scenario.case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果没有提供 case_file_path,但提供了 case_id,则尝试从内存重置 + if case_id and case_id in SCENARIOS: + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + metadata = FILE_METADATA.get(case_id, {}) + + # Reset dynamic fields and re-apply progressive reveal + # 重新初始化节点状态(包括渐进式暴露) + _initialize_node_values(scenario, raw_nodes_data, metadata) + + 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'])}") + + # 生成初始观察信息 + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + + return { + "ok": True, + "message": f"Case {case_id} reset.", + "case_id": case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果既没有 case_file_path,也没有在内存中找到,返回错误 + raise HTTPException( + status_code=400, + detail="Must provide case_file_path to load a new case, or use case_id to reset an existing case." + ) + +class InvestigateRequest(BaseModel): + node_id: str + +@app.post("/env/{case_id}/investigate") +def investigate(case_id: str, req: InvestigateRequest): + """ + Investigates a Tool or Item to reveal detailed information. + + - For Tools: Returns detailed interface information (inputs/outputs) needed to call the tool + - For Items: Returns content value and triggers hidden item drops + """ + logger.info(f"Investigate request - case_id: {case_id}, node_id: {req.node_id}") + STATS["investigates"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + node = scenario.nodes[req.node_id] + + if not node.is_revealed: + logger.warning(f"Attempt to investigate hidden node: {req.node_id}") + return {"ok": False, "error": "Node is not visible yet."} + + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + newly_revealed = [] + + # 处理 Tool 的 investigate + if node.type == "Tool": + logger.info(f"Investigating tool: {req.node_id}") + + # 返回工具的详细接口信息 + # id 字段使用 node.id(节点唯一标识),agent 用这个字段识别和调用具体的节点 + # template_id 是工具类型标识符,Agent 内部用于判断工具特性(如 terminal 类工具参数可选) + # 注意:只过滤输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口),这些端口仅用于控制掉落,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + # 【端口上游依赖提示 & 初始值直接给出】 + # 针对参数语义模糊(全为数字类型)的工具,在 investigate 返回信息中标注 + # 哪个输入端口来自哪个上游节点(upstream_from)。 + # 对于所有工具:若该节点不是纯源头节点(有任意数据流入边), + # 且某个端口没有上游入边(值来自初始可见参数),则直接给出该端口的 golden input 值。 + AMBIGUOUS_TOOLS = { + "num_base_convert", "calc_modexp", "calc_modexp_int", + "calc_inv_mod", "calc_inv_mod_int", "crypto_rsa_decrypt_hex", "geo_haversine" + } + # Terminal 类工具自带参数对错反馈机制,玩家/模型可自行试错, + # 无需在 investigate 时直接暴露 init_value + SELF_FEEDBACK_TOOLS = { + "terminal_1", "terminal_2", + "Logic Terminal", "Math Terminal", "Encryption Terminal", "Sequence Terminal" + } + _template_id_for_hint = raw_nodes_data.get(node.id, {}).get("template_id", "") + # 构建数据流入边映射(对所有工具):{target_port -> (source_node_id, source_port)} + _upstream_map = {} + for _edge in scenario.edges: + if (_edge.target_id == node.id + and _edge.connection_type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM] + and _edge.target_port is not None): + _upstream_map[_edge.target_port] = (_edge.source_id, _edge.source_port) + # 判断该节点是否有任意数据流入边(即不是纯源头节点) + _has_any_upstream = len(_upstream_map) > 0 + # 判断该节点是否有任意入边(包括 ITEM/HIDDEN_ITEM 掉落边) + # 有任意入边(含掉落边)但无数据流入边的节点,其输入来自初始可见参数,应直接给出 + _has_any_edge = any(_edge.target_id == node.id for _edge in scenario.edges) + # 构建 inputs 列表 + _inputs_list = [] + for p in node.inputs: + if p.type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + continue + port_dict = {"name": p.name, "type": p.type, "description": p.description} + if p.name in _upstream_map: + # 该端口有上游数据流依赖,且属于语义模糊工具 → 标注来源 + if _template_id_for_hint in AMBIGUOUS_TOOLS: + src_node_id, src_port = _upstream_map[p.name] + port_dict["upstream_from"] = f"{src_node_id}.{src_port}" if src_port else src_node_id + elif _has_any_edge and _template_id_for_hint not in SELF_FEEDBACK_TOOLS: + # 该节点有任意入边,但此端口没有数据流入边 → 值来自初始可见参数,直接给出 + # 排除自带反馈机制的 terminal 类工具(它们通过执行结果反馈对错,无需提前暴露参数值) + golden_val = node.golden_input_values.get(p.name) + if golden_val is not None: + port_dict["init_value"] = golden_val + _inputs_list.append(port_dict) + + tool_details = { + "id": node.id, # 节点 ID,用于唯一标识和调用这个具体节点 + "type": "Tool", + "inputs": _inputs_list, + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id 用于 Agent 内部判断工具类型(不会展示给被测模型) + if node.id in raw_nodes_data: + template_id = raw_nodes_data[node.id].get('template_id') + if template_id: + tool_details["_template_id"] = template_id # 使用下划线前缀标记为内部字段 + + # 只在 name 非空时添加 + # if node.name: + # tool_details["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_details["description"] = node.description + + # 添加 narrative 字段(如果存在) + if node.id in raw_nodes_data: + narrative = raw_nodes_data[node.id].get('narrative') + if narrative: + tool_details['narrative'] = narrative + + # 不再返回 init_values,避免泄漏答案 + # investigate 只应该返回工具的接口定义,不应该暴露初始值 + + # 【新增】检查该 Tool 是否有待触发的 HIDDEN_ITEM 掉落 + # 如果该工具已按照 golden_input 正确执行,且有 HIDDEN_ITEM 输出边,则触发掉落 + if node.has_hidden_item_ready: + logger.info(f"Tool has HIDDEN_ITEM ready - triggering passive drop for: {req.node_id}") + + # 遍历该工具的所有 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + # 重置标志,已经触发过了,避免重复 + node.has_hidden_item_ready = False + + logger.info(f"Tool investigation successful - node: {req.node_id}, revealed: {len(newly_revealed)}") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Tool", + "details": tool_details + } + + # 如果有新掉落的节点,添加到响应中 + if newly_revealed: + result["newly_revealed"] = newly_revealed + + return result + + # 处理 Item 的 investigate + elif node.type == "Item": + logger.info(f"Investigating item: {req.node_id}") + + # 【第一步】检查该 Item 是否有需要参数的输入端口 + # 如果有,且尚未通过 use_item 验证,则不返回内容,只返回参数要求 + required_inputs = [] + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + inputs_info = raw_node.get('inputs', []) + required_inputs = [ + { + "name": inp.get("name"), + "type": inp.get("type"), + "description": inp.get("description", "") + } + for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + # 如果有 required_inputs 且尚未通过 use_item 验证(if_success == False) + # 则不返回内容,只返回参数要求提示 + if required_inputs and not node.if_success: + logger.info(f"Item has required inputs and not yet unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "required_inputs": required_inputs + } + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + param_names = ', '.join([inp['name'] for inp in required_inputs]) + 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}" + + return result + + # 【新增】如果有 required_inputs 且已经通过 use_item 验证(if_success == True) + # 则返回提示:该节点已经被成功解决 + if required_inputs and node.if_success: + logger.info(f"Item has required inputs and already unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "message": "This item has already been successfully unlocked by you." + } + return result + + # 【第二步】该 Item 没有 required_inputs 或已通过验证,返回内容 + # 1. 返回 Item 的 golden_output_values(即 Item 的内容) + # 注意:某些 Item 仅用于触发 HIDDEN_ITEM 掉落,没有实际内容 + has_actual_content = bool(node.golden_output_values) or node.content is not None + content = node.golden_output_values if node.golden_output_values else node.content + + # 【关键】将 golden_output_values 追加到 actual_outputs_history,标记该 Item 已被 investigate + # 这样在渐进式暴露时,这些值才会被加入可见值集合 + # 即使是空字典(仅触发 HIDDEN_ITEM 的 Item),也要记录,以便渐进式暴露逻辑知道该 Item 已被调查 + if node.golden_output_values is not None: + node.actual_outputs_history.append(dict(node.golden_output_values)) + + # 2. Trigger Hidden Item Drops (Passive Drop) + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + logger.info(f"Item investigation successful - node: {req.node_id}, has_content: {has_actual_content}, revealed: {len(newly_revealed)}") + + # 【渐进式暴露】旧机制(基于 golden_input)已禁用 + # 现在完全由 ITEM/HIDDEN_ITEM 边触发控制节点可见性 + # 上面的 HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, node.golden_output_values or {}, node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # logger.info(f"Progressive reveal after Item investigate: {len(progressive_revealed)} nodes now ready") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Item" + } + + # 只在有实际内容时才添加 content 字段 + # 对于仅触发 HIDDEN_ITEM 掉落的 Item,不返回 content 字段,避免返回 None 或空字典让模型困惑 + if has_actual_content: + result["content"] = content + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型通过 investigate 获得内容后,需要自己识别这是否是胜利字符串 + + return result + + else: + logger.warning(f"Attempt to investigate unknown node type: {req.node_id} (type: {node.type})") + return {"ok": False, "error": f"Cannot investigate node type: {node.type}"} + +class ToolCallRequest(BaseModel): + node_id: str # 使用 node_id 精确指定要调用的节点 + arguments: Dict[str, Any] + +@app.post("/env/{case_id}/tool_call") +def tool_call(case_id: str, req: ToolCallRequest): + """Executes a tool and triggers item drops.""" + logger.info(f"Tool call request - case_id: {case_id}, node_id: {req.node_id}, args: {list(req.arguments.keys())}") + STATS["tool_calls"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + + # 通过 node_id 精确查找节点 + node_id = req.node_id + if node_id not in scenario.nodes: + logger.error(f"Node not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + tool_node = scenario.nodes[node_id] + + if not tool_node: + logger.error(f"Tool not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Tool not found") + + if not tool_node.is_revealed: + logger.warning(f"Attempt to call hidden tool: {node_id}") + return {"ok": False, "error": "Tool is not visible yet."} + + if tool_node.type != "Tool": + logger.warning(f"Attempt to call non-tool node: {node_id} (type: {tool_node.type})") + return {"ok": False, "error": "Only tools can be called."} + + # 1. Execute Tool (Real Execution via Simulator) + simulator = SIMULATORS[case_id] + + # Get tool name from template_id if available, otherwise use node name + tool_name = tool_node.name + if case_id in RAW_NODES_DATA and node_id in RAW_NODES_DATA[case_id]: + template_id = RAW_NODES_DATA[case_id][node_id].get('template_id') + if template_id: + tool_name = template_id + + # 文件处理工具和 Terminal 需要验证输入并返回预先计算的输出 + # 传递节点的实际输入输出值(从 DAG 执行后填充的数据) + tool_arguments = dict(req.arguments) # Make a copy + + # 传递节点的 golden values(从 JSON 的 inputs[].value 和 outputs[].value 加载) + # 用于在评测阶段验证被测模型传入的参数是否正确 + if tool_node.golden_input_values: + tool_arguments['_golden_inputs'] = tool_node.golden_input_values + if tool_node.golden_output_values: + tool_arguments['_golden_outputs'] = tool_node.golden_output_values + + logger.debug(f"Executing tool {tool_name} (node: {tool_node.name}) with args {tool_arguments}") + + try: + output_values = simulator.execute(tool_name, tool_arguments) + logger.info(f"Tool invoked - {tool_name}: {list(output_values.keys())}") + except Exception as e: + logger.error(f"Tool execution failed - {tool_name}: {str(e)}", exc_info=True) + return {"ok": False, "error": f"Tool execution failed: {str(e)}"} + + # 检查验证结果(精细化错误反馈) + validation = output_values.pop("_validation", {"valid": True}) + + if not validation["valid"]: + # 根据错误类型构造友好的错误消息 + error_type = validation.get("error_type") + + if error_type == "missing_required": + missing = validation.get("missing_params", []) + error_msg = f"Error: Missing required parameters {', '.join(missing)}" + + elif error_type == "type_error": + param = validation.get("param_name") + message = validation.get("message", "Parameter type error") + error_msg = f"Error: {message}" + + elif error_type == "incomplete_optional": + provided = validation.get("provided_params", []) + missing = validation.get("missing_params", []) + error_msg = ( + f"Hint: You provided some parameters ({', '.join(provided)}), " + f"but may also need: {', '.join(missing)}.\n" + f"Trying to provide these parameters together might yield better results." + ) + + elif error_type == "value_mismatch": + param = validation.get("param_name") + hint = validation.get("hint", "Parameter value may be incorrect") + error_msg = f"Hint: {hint}.\nPlease check if this parameter value meets the requirements." + + else: + error_msg = validation.get("hint") or validation.get("message", "Parameter validation failed") + + logger.info(f"Tool validation failed - {tool_name}: {error_type}") + return { + "ok": False, + "error": error_msg, + "error_type": error_type + } + + # Simulate success + tool_node.if_success = True + + # 【关键】将本次执行的输出值追加到历史列表(用于渐进式暴露判断) + # 每次调用都会记录,不会覆盖之前的执行结果 + tool_node.actual_outputs_history.append(dict(output_values)) + + # 2. 检查是否应该触发掉落(只有输入参数正确时才掉落) + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, tool_node.golden_input_values) + + newly_revealed = [] + investigate_hints = [] # 提示模型哪些节点可以 investigate 来发现隐藏内容 + + if inputs_match_golden: + logger.info(f"✓ Tool inputs match golden - node: {node_id}, triggering drops") + + # 检查该工具是否有 ITEM 或 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == tool_node.id: + target_node = scenario.nodes[edge.target_id] + + # ITEM 边:立即掉落(主动掉落) + if edge.connection_type == InterfaceType.ITEM: + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from {node_id})") + + # HIDDEN_ITEM 边:不立即掉落,标记并提示(被动掉落) + elif edge.connection_type == InterfaceType.HIDDEN_ITEM: + # 标记该工具有待触发的 HIDDEN_ITEM 掉落 + tool_node.has_hidden_item_ready = True + + # 提示模型可以 investigate 这个工具来发现隐藏内容 + hint_info = { + "tool_id": tool_node.id, + "hint": f"Tool '{tool_node.id}' seems to hide something, try investigating it to discover more information" + } + # if tool_node.name: + # hint_info["tool_name"] = tool_node.name + + investigate_hints.append(hint_info) + logger.info(f"HIDDEN_ITEM ready: {tool_node.id} -> {target_node.id} (will drop on investigate)") + else: + logger.info(f"✗ Tool inputs do NOT match golden - node: {node_id}, no drops triggered") + + response = { + "ok": True, + "message": "Tool invoked", + "output_values": output_values # Return raw outputs to Agent + } + + # 【新增】对源头节点进行参数验证反馈 + # 源头节点:没有数据流入边的节点,这些节点的参数需要模型自己推理 + # 验证模型使用的参数是否正确,并提供明确的反馈 + if _is_source_node(node_id, scenario) and tool_node.golden_input_values: + validation_feedback = _get_parameter_validation_feedback(req.arguments, tool_node.golden_input_values) + + if validation_feedback["all_correct"]: + # 用户提交了全部 golden 参数且全部正确 + response["parameter_feedback"] = { + "status": "correct", + "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." + } + logger.info(f"✓ Source node parameters all correct - node: {node_id}") + elif validation_feedback["incorrect_params"]: + # 有提交了但值错误的参数,只对这些参数给出反馈 + incorrect_list = [] + for param_name in validation_feedback["incorrect_params"]: + incorrect_list.append(f" - Parameter '{param_name}' is incorrect") + + correct_info = "" + if validation_feedback["correct_params"]: + correct_info = f"\n✓ Correct parameters: {', '.join(validation_feedback['correct_params'])}" + + response["parameter_feedback"] = { + "status": "incorrect", + "message": ( + f"⚠️ Some parameters are incorrect:\n" + + "\n".join(incorrect_list) + + correct_info + + 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." + ), + "incorrect_params": validation_feedback["incorrect_params"], + "correct_params": validation_feedback["correct_params"] + } + logger.info(f"✗ Source node parameters incorrect - node: {node_id}, incorrect: {validation_feedback['incorrect_params']}") + # else: 部分提交且全部正确 → 不给任何 parameter_feedback,避免对未提交的参数发表意见 + + # 检查工具调用是否完全正确(输出与 golden outputs 匹配) + # 用于给模型正向反馈,让它知道这个工具已经正确调用过,避免重复调用 + # 注意:只有当输出完全匹配时才标记为 correct,不会在错误时提供具体错误信息 + # if tool_node.golden_output_values and output_values: + # is_correct = True + # for port_name, expected_value in tool_node.golden_output_values.items(): + # actual_value = output_values.get(port_name) + # if str(actual_value) != str(expected_value): + # is_correct = False + # break + + # if is_correct: + # response["tool_call_correct"] = True + # logger.info(f"✓ Tool called with correct result - node: {node_id}") + + # 只在有新内容掉落时才返回 newly_revealed + if newly_revealed: + response["newly_revealed"] = newly_revealed + + # 添加 investigate 提示(对于有待触发 HIDDEN_ITEM 掉落的工具) + if investigate_hints: + response["investigate_hints"] = investigate_hints + + # 3. 渐进式暴露机制 - 现在完全由 ITEM/HIDDEN_ITEM 边控制 + # 旧机制(基于 golden_input 检查)已被禁用 + # 新机制中,节点的可见性只由 ITEM/HIDDEN_ITEM 边触发决定 + # 上面的 ITEM/HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, output_values, tool_node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # response["newly_revealed"] = newly_revealed + # logger.info(f"Progressive reveal: {len(progressive_revealed)} nodes now ready") + + # Check if this is the win node + if node_id == scenario.win_node_id: + # 验证输出值是否等于预期的胜利值 + # 从节点的 golden_output_values 中获取预期值(在 _initialize_node_values 时从 JSON 加载) + expected_outputs = tool_node.golden_output_values + + # 检查实际输出是否与预期输出匹配 + is_correct = False + victory_string = None + mismatch_info = [] + + if expected_outputs and output_values: + # 检查每个预期输出端口的值是否匹配 + is_correct = True + for port_name, expected_value in expected_outputs.items(): + actual_value = output_values.get(port_name) + if actual_value != expected_value: + is_correct = False + mismatch_info.append(f"Port '{port_name}': expected '{expected_value}', actual '{actual_value}'") + logger.warning(f"Win node output mismatch - port: {port_name}, expected: {expected_value}, actual: {actual_value}") + + # 如果所有输出都匹配,使用第一个输出作为胜利字符串 + if is_correct and output_values: + victory_string = list(output_values.values())[0] + else: + logger.warning(f"Win node called but missing output values - expected: {expected_outputs}, actual: {output_values}") + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型调用工具获得输出后,需要自己识别这是否是胜利字符串并提交 + if is_correct: + logger.info(f"🎯 Win node called with correct output - case: {case_id}, node: {node_id}, victory: {victory_string}") + else: + logger.info(f"❌ Win node called with incorrect output - case: {case_id}, node: {node_id}") + + return response + +class UseItemRequest(BaseModel): + node_id: str = Field(..., description="The ID of the Item node to use (must be Item type)") + arguments: Dict[str, Any] = Field(default_factory=dict, description="Input arguments to provide to the item") + +@app.post("/env/{case_id}/use_item") +def use_item(case_id: str, req: UseItemRequest): + """ + Use an Item node by providing input arguments. + + This is specifically for Item nodes that require parameters to be "unlocked" or "activated", + such as containers that need a password/fingerprint. + + - Validates that the node is of type Item + - Checks if provided arguments match the item's golden_input_values + - If match: triggers ITEM-type edge drops and returns the item's content + - If not match: returns error message + """ + logger.info(f"Use item request - case_id: {case_id}, node_id: {req.node_id}, args: {req.arguments}") + STATS["use_items"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + item_node = scenario.nodes[req.node_id] + + if not item_node.is_revealed: + logger.warning(f"Attempt to use hidden item: {req.node_id}") + return {"ok": False, "error": "Item is not visible yet."} + + if item_node.type != "Item": + logger.warning(f"Attempt to use non-item node: {req.node_id} (type: {item_node.type})") + return {"ok": False, "error": "Only Item nodes can be used with use_item. Tools should be called with tool_call."} + + # 【新增】检查该 Item 是否已经被成功解锁 + # 如果已经被正确使用过,直接返回成功提示 + if item_node.if_success: + logger.info(f"Item already unlocked, returning success message: {req.node_id}") + return { + "ok": True, + "message": "This item has already been successfully unlocked by you." + } + + # 检查该 Item 是否真的需要通过 use_item 提供参数 + # 只有当 Item 有非 Item/Hidden_Item 类型的输入时,才应该使用 use_item + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + non_hidden_inputs = [ + inp for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + if not non_hidden_inputs: + # 该 Item 不需要参数,应该只使用 investigate + logger.warning(f"Attempt to use_item on a node that doesn't require parameters: {req.node_id}") + return { + "ok": False, + "error": "This item does not require parameters. Please use investigate to examine the item directly." + } + + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, item_node.golden_input_values) + + if not inputs_match_golden: + logger.info(f"✗ Item inputs do NOT match golden - node: {req.node_id}") + # 提供更详细的错误信息,帮助 Agent 理解问题 + # 只显示非 Item/Hidden_Item 类型的参数(Hidden_Item 由系统自动处理) + expected_params = [] + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + expected_params = [ + inp.get("name") for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + provided_params = list(req.arguments.keys()) if req.arguments else [] + + # 检查参数名是否匹配 + if set(expected_params) == set(provided_params): + # 参数名正确但值不匹配 - 不泄漏正确的值 + error_msg = f"Parameter names are correct, but the parameter values are incorrect. Please try using different parameter values." + else: + error_msg = f"Parameter names do not match. Expected parameter names: {expected_params}, you provided: {provided_params}." + + return { + "ok": False, + "error": error_msg + } + + logger.info(f"✓ Item inputs match golden - node: {req.node_id}, activating item") + + # 标记该 Item 已被正确使用 + item_node.if_success = True + + # 将 golden_output_values 追加到 actual_outputs_history + if item_node.golden_output_values: + item_node.actual_outputs_history.append(dict(item_node.golden_output_values)) + + # 触发 ITEM 类型边的掉落 + newly_revealed = [] + for edge in scenario.edges: + if edge.source_id == item_node.id and edge.connection_type == InterfaceType.ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from use_item on {req.node_id})") + + # 检查是否为 Win Node + win_node_id = scenario.win_node_id + is_win_node = (req.node_id == win_node_id) + + # 构建返回结果 + result = { + "ok": True, + "message": "Item used successfully.", + "content": item_node.golden_output_values if item_node.golden_output_values else None + } + + # 获取 narrative(如果存在) + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + narrative = raw_nodes_data[req.node_id].get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 如果是 Win Node,只记录日志 + if is_win_node: + logger.info(f"Win node (Item) unlocked via use_item - case: {case_id}, node: {req.node_id}") + + return result + + +class SubmitAnswerRequest(BaseModel): + answer: str = Field(..., description="The victory string to submit") + +@app.post("/env/{case_id}/submit_answer") +def submit_answer(case_id: str, req: SubmitAnswerRequest): + """ + 提交答案接口 + 被测模型在获得胜利字符串提示后,需要调用此接口提交答案 + """ + logger.info(f"Submit answer request - case_id: {case_id}, answer: {req.answer}") + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + + # 获取 win_node 的 golden_output_values + if not scenario.win_node_id: + logger.error(f"No win node defined for case: {case_id}") + return { + "ok": False, + "error": "This case has no victory node defined" + } + + win_node = scenario.nodes.get(scenario.win_node_id) + if not win_node: + logger.error(f"Win node not found: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node does not exist" + } + + # 获取正确的胜利字符串(取第一个 golden_output_value) + if win_node.golden_output_values: + correct_answer = list(win_node.golden_output_values.values())[0] + else: + logger.error(f"Win node has no golden_output_values: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node has no correct answer" + } + + # 验证提交的答案 + if req.answer == correct_answer: + logger.info(f"🎉 CORRECT ANSWER SUBMITTED - case: {case_id}, answer: {req.answer}") + return { + "ok": True, + "is_win": True, + "victory_message": f"🎉 Congratulations on successfully escaping the room! Your answer is correct: {req.answer}" + } + else: + logger.info(f"❌ INCORRECT ANSWER SUBMITTED - case: {case_id}, submitted: {req.answer}, correct: {correct_answer}") + return { + "ok": True, + "is_win": False, + "error": f"The submitted answer is incorrect. You submitted: {req.answer}" + } + +if __name__ == "__main__": + + uvicorn.run(app, host="0.0.0.0", port=8000) \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-a8a2cf21/environment/puzzle/upstream/simulator.py b/tasks/agentescape-25-skeleton-a8a2cf21/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-25-skeleton-a8a2cf21/environment/puzzle/upstream/simulator.py @@ -0,0 +1,2911 @@ +import hashlib +import hmac +import base64 +import binascii +import zlib +import json +import uuid +import math +import re +from typing import Dict, Any, List + +class ToolSimulator: + def __init__(self): + """工具模拟器 + + 文件处理工具(zip_unzip, zip_unzip_file, zip_unzip_item, json_get, csv_query, + regex_search, graph_shortest_path)不需要真实文件系统。 + 这些工具只验证输入参数,然后返回预先初始化好的 golden_outputs。 + """ + self.tool_map = { + # 数论 + "calc_bigmul": self.calc_bigmul, + "calc_modexp": self.calc_modexp, + "calc_modexp_int": self.calc_modexp_int, + "calc_gcd": self.calc_gcd, + "calc_gcd_int": self.calc_gcd_int, + "calc_inv_mod": self.calc_inv_mod, + "calc_inv_mod_int": self.calc_inv_mod_int, + + # 哈希 + "hash_sha256": self.hash_sha256, + "hash_md5": self.hash_md5, + "hmac_sha256": self.hmac_sha256, + + # 编码 + "base64_decode": self.base64_decode, + "base64_encode": self.base64_encode, + "hex_decode": self.hex_decode, + "hex_encode": self.hex_encode, + "zlib_inflate": self.zlib_inflate, + "zlib_deflate": self.zlib_deflate, + + # 文件 + "zip_unzip": self.zip_unzip, + "zip_unzip_file": self.zip_unzip_file, + "zip_unzip_item": self.zip_unzip_item, + "regex_search": self.regex_search, + "json_get": self.json_get, + "csv_query": self.csv_query, + "code_py_exec": self.code_py_exec, + + # 图 + "graph_shortest_path": self.graph_shortest_path, + + # 加解密 (简化模拟) + "crypto_aes_cbc_decrypt": self.crypto_aes_cbc_decrypt, + "crypto_rsa_decrypt_hex": self.crypto_rsa_decrypt_hex, + + # 其他 + "num_base_convert": self.num_base_convert, + "time_convert": self.time_convert, + "checksum_crc32": self.checksum_crc32, + "geo_haversine": self.geo_haversine, + "otp_totp_generate": self.otp_totp_generate, + "unicode_norm": self.unicode_norm, + "text_bidi_sanitize": self.text_bidi_sanitize, + "text_xor_hex": self.text_xor_hex, + "text_rotN": self.text_rotN, + "luhn_check": self.luhn_check, + "iban_validate": self.iban_validate, + + # 物理 + "matter_synthesizer": self.matter_synthesizer, + + # 终端机 + "terminal_1": self.terminal_1, + "terminal_2": self.terminal_2, + "Logic Terminal": self.logic_terminal, + "Math Terminal": self.math_terminal, + "Encryption Terminal": self.crypt_terminal, + "Sequence Terminal": self.sequence_terminal + } + + def execute(self, tool_name: str, inputs: Dict[str, Any]) -> Dict[str, Any]: + if tool_name not in self.tool_map: + # Fallback for unknown tools: return dummy outputs based on expected output types + # This should ideally not happen if all tools are implemented + return {} + + try: + return self.tool_map[tool_name](inputs) + except Exception as e: + print(f"Error executing {tool_name}: {e}") + # Return empty or error indication? For generation, we might want to fail hard or return dummy. + # For now, return dummy to keep flow going, but log error. + return {} + + # --- Implementations --- + + def calc_bigmul(self, inputs): + # Check if required parameters are present + if "a" not in inputs or "b" not in inputs: + raise ValueError("Missing required parameters 'a' and/or 'b'") + + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + return {"product": str(a * b)} + except (ValueError, TypeError) as e: + raise ValueError(f"Failed to convert parameters to integers: {str(e)}") + + def calc_modexp(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + try: + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if isinstance(base, str): + base = int(base) + elif not isinstance(base, int): + raise ValueError("Parameter 'base' must be a string or integer") + + if isinstance(exp, str): + exp = int(exp) + elif not isinstance(exp, int): + raise ValueError("Parameter 'exp' must be a string or integer") + + if isinstance(mod, str): + mod = int(mod) + elif not isinstance(mod, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": str(pow(base, exp, mod))} + + def calc_modexp_int(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["base"], int): + raise ValueError("Parameter 'base' must be an integer") + if not isinstance(inputs["exp"], int): + raise ValueError("Parameter 'exp' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": pow(base, exp, mod)} + + def calc_gcd(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + # 计算 GCD 并返回字符串格式(符合 Big_Int 输出类型) + result = math.gcd(a, b) + return {"gcd": str(result)} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def calc_gcd_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["b"], int): + raise ValueError("Parameter 'b' must be an integer") + + # 获取参数 + a = inputs["a"] + b = inputs["b"] + + return {"gcd": math.gcd(a, b)} + + def calc_inv_mod(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + m = inputs["mod"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(m, str): + m = int(m) + elif not isinstance(m, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": str(pow(a, -1, m))} + except ValueError as e: + # 模逆不存在时,返回一个特殊值(用于数据传递) + # 在 DAG 生成阶段,这允许数据流继续 + return {"inv": str(a)} + + def calc_inv_mod_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + a = inputs["a"] + m = inputs["mod"] + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": pow(a, -1, m)} + except ValueError as e: + raise ValueError(f"Modular inverse does not exist: {str(e)}") + + def hash_sha256(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.sha256(text.encode()).hexdigest()} + + def hash_md5(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.md5(text.encode()).hexdigest()} + + def hmac_sha256(self, inputs): + # 参数检查 + if "hex_key" not in inputs: + raise ValueError("Missing required parameter: hex_key") + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["hex_key"], str): + raise ValueError("Parameter 'hex_key' must be a string") + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + try: + key = bytes.fromhex(inputs["hex_key"]) + text = inputs["text"].encode() + return {"hex": hmac.new(key, text, hashlib.sha256).hexdigest()} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def base64_decode(self, inputs): + # 参数检查 + if "data" not in inputs: + raise ValueError("Missing required parameter: data") + + # 类型检查 + if not isinstance(inputs["data"], str): + raise ValueError("Parameter 'data' must be a string") + + data = inputs["data"] + try: + return {"bytes_hex": binascii.hexlify(base64.b64decode(data)).decode()} + except Exception as e: + raise ValueError(f"Base64 decode error: {str(e)}") + + def base64_encode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"b64": base64.b64encode(bytes.fromhex(hex_data)).decode()} + except Exception as e: + raise ValueError(f"Base64 encode error: {str(e)}") + + def hex_decode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"text": bytes.fromhex(hex_data).decode('utf-8', errors='ignore')} + except Exception as e: + raise ValueError(f"Hex decode error: {str(e)}") + + def hex_encode(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + try: + return {"hex": text.encode().hex()} + except Exception as e: + raise ValueError(f"Hex encode error: {str(e)}") + + + # 到此处实现已经更新 + + def zlib_inflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("Parameter 'hex' must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("Missing required parameter: hex") + + try: + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空字符串 + if not hex_data: + raise ValueError("Empty hex string provided") + + # 检查十六进制字符串的有效性 + if len(hex_data) % 2 != 0: + raise ValueError("Hex string must have even length") + + # 检查是否只包含有效的十六进制字符 + if not all(c in '0123456789abcdefABCDEF' for c in hex_data): + raise ValueError("Invalid hex string provided") + + # 尝试解压缩 + return {"text": zlib.decompress(bytes.fromhex(hex_data)).decode('utf-8')} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hex string provided") from e + raise ValueError(f"Invalid zlib data: {e}") from e + except Exception as e: + raise RuntimeError(f"Failed to inflate data: {e}") from e + + def zlib_deflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("Parameter 'text' must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("Missing required parameter: text") + + try: + # 压缩文本 + return {"hex": zlib.compress(text.encode('utf-8')).hex()} + except Exception as e: + raise RuntimeError(f"Failed to deflate data: {e}") from e + + # --- File Operations --- + + def zip_unzip(self, inputs): + """ZIP 解压工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"files": golden_outputs.get("files", "")} + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return {"files": golden_outputs.get("files", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "files" in golden_outputs: + # 验证必需参数 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 检查类型 + if has_zip_id and not isinstance(zip_id, str): + return {"error": "Parameter 'zip_id' must be a string type"} + if has_password and not isinstance(password, str): + return {"error": "Parameter 'password' must be a string type"} + + # 验证输入是否与预期匹配 + if golden_inputs: + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return {"files": golden_outputs["files"]} + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + # 没有golden_inputs但有golden_outputs,直接返回输出 + return {"files": golden_outputs["files"]} + + # 如果没有预期输出,返回空结果 + return {"files": ""} + + def regex_search(self, inputs): + """正则搜索工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"matches": golden_outputs.get("matches", "[]")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "matches" in golden_outputs: + # 提取实际参数 + pattern = inputs.get("pattern") + file_id = inputs.get("file_id") + text = inputs.get("text") + + # 1. 检查必需参数 + if pattern is None: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["pattern"], + "message": "Missing required parameter 'pattern'" + } + } + + # 类型检查 + if not isinstance(pattern, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "pattern", + "message": "Parameter 'pattern' must be a string type" + } + } + if file_id is not None and not isinstance(file_id, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if text is not None and not isinstance(text, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "text", + "message": "Parameter 'text' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合 + provided_params = {} + if pattern is not None: + provided_params["pattern"] = pattern + if file_id is not None: + provided_params["file_id"] = file_id + if text is not None: + provided_params["text"] = text + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数(关键改进) + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_pattern = golden_inputs.get("pattern") + expected_file_id = golden_inputs.get("file_id") + expected_text = golden_inputs.get("text") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_pattern is not None: + if str(pattern) != str(expected_pattern): + incorrect_params.append("pattern") + else: + correct_params.append("pattern") + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_text is not None: + if str(text) != str(expected_text): + incorrect_params.append("text") + else: + correct_params.append("text") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "matches": "[]", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "matches": golden_outputs["matches"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空列表 + return {"matches": "[]"} + + def json_get(self, inputs): + """JSON 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"values": golden_outputs.get("values", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "values" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + jsonpath = inputs.get("jsonpath", "") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if jsonpath is not None and not isinstance(jsonpath, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "jsonpath", + "message": "Parameter 'jsonpath' must be a string type" + } + } + + # 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:jsonpath有默认值"") + provided_params = {} + if file_id is not None: + provided_params["file_id"] = file_id + if jsonpath != "": + provided_params["jsonpath"] = jsonpath + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_jsonpath = golden_inputs.get("jsonpath") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_jsonpath is not None: + if str(jsonpath) != str(expected_jsonpath): + incorrect_params.append("jsonpath") + else: + correct_params.append("jsonpath") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "values": "", + "_validation": validation_info + } + + # 所有验证通过,返回正确输出 + return { + "values": golden_outputs["values"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"values": ""} + + def csv_query(self, inputs): + """CSV 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"rows": golden_outputs.get("rows", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "rows" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + select_columns = inputs.get("select", "") + where_clause = inputs.get("where", "") + + # 1. 检查必需参数 + if file_id is None: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["file_id"], + "message": "Missing required parameter 'file_id'" + } + } + + # 类型检查 + if not isinstance(file_id, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if not isinstance(select_columns, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "select", + "message": "Parameter 'select' must be a string type" + } + } + if not isinstance(where_clause, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "where", + "message": "Parameter 'where' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:select和where有默认值"") + provided_params = {"file_id": file_id} + if select_columns != "": + provided_params["select"] = select_columns + if where_clause != "": + provided_params["where"] = where_clause + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_select = golden_inputs.get("select") + expected_where = golden_inputs.get("where") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_select is not None: + if str(select_columns) != str(expected_select): + incorrect_params.append("select") + else: + correct_params.append("select") + + if expected_where is not None: + if str(where_clause) != str(expected_where): + incorrect_params.append("where") + else: + correct_params.append("where") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "rows": "", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "rows": golden_outputs["rows"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"rows": ""} + + def graph_shortest_path(self, inputs): + """图最短路径工具 + + 如果有 _golden_outputs 或 _init_outputs,验证输入并返回预设输出。 + 否则执行真实的 Dijkstra 算法。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 检查是否在预设模式中(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + if golden_outputs and "path" in golden_outputs: + # 评测阶段但没有 golden_inputs,直接返回 outputs + if not golden_inputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 评测模式:验证输入参数是否匹配 golden 值 + src = inputs.get("src") + dst = inputs.get("dst") + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + + has_src = src is not None and src != "" + has_dst = dst is not None and dst != "" + + # 验证必需参数 + if not has_src or not has_dst: + missing = [] + if not has_src: + missing.append("src") + if not has_dst: + missing.append("dst") + return {"error": "Missing required parameters: " + ", ".join(missing)} + + # 类型检查 + if not isinstance(src, str): + return {"error": "Parameter 'src' must be a string"} + if not isinstance(dst, str): + return {"error": "Parameter 'dst' must be a string"} + + # 验证输入是否匹配期望值 + if golden_inputs: + expected_src = golden_inputs.get("src") + expected_dst = golden_inputs.get("dst") + expected_file_id = golden_inputs.get("file_id") + expected_graph_data = golden_inputs.get("graph_data") + + # 收集验证结果 + incorrect_params = [] + correct_params = [] + + # 检查必需参数是否匹配 + if expected_src is not None: + if str(src) != str(expected_src): + incorrect_params.append("src") + else: + correct_params.append("src") + + if expected_dst is not None: + if str(dst) != str(expected_dst): + incorrect_params.append("dst") + else: + correct_params.append("dst") + + # 检查可选参数(如果在 expected_inputs 中定义了) + if expected_file_id is not None: + if file_id != expected_file_id: + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_graph_data is not None: + if graph_data != expected_graph_data: + incorrect_params.append("graph_data") + else: + correct_params.append("graph_data") + + # 如果有参数不正确,返回详细的反馈 + if incorrect_params: + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 验证通过,返回预设的输出 + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 获取参数(真实执行路径) + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + # Support both src/dst (interface definition) and start/end (original implementation) + start = inputs.get("src") + end = inputs.get("dst") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + raise TypeError("file_id must be a string") + + if graph_data is not None and not isinstance(graph_data, str): + raise TypeError("graph_data must be a string") + + if start is not None and not isinstance(start, str): + raise TypeError("src/start must be a string") + + if end is not None and not isinstance(end, str): + raise TypeError("dst/end must be a string") + + # 检查必需参数 + if file_id is None and graph_data is None: + raise ValueError("Either file_id or graph_data must be provided") + + if start is None: + raise ValueError("src/start parameter is required") + + if end is None: + raise ValueError("dst/end parameter is required") + + # Get graph content + content = None + if file_id is not None: + # 尝试从 VFS 获取(如果存在) + if hasattr(self, 'vfs') and file_id in self.vfs: + content = self.vfs[file_id] + else: + # VFS 不存在或文件不在 VFS 中 + # 返回一个默认的空图结果,或者抛出错误提示需要 init_outputs + raise ValueError( + f"File '{file_id}' not found. For tools that require files, " + f"please provide init_outputs in the initial_values." + ) + elif graph_data is not None: + content = graph_data + + if content is None: + content = "{}" + + try: + # Parse graph data + graph = json.loads(content) + + # 类型检查 + if not isinstance(graph, dict): + raise TypeError("Graph data must be a dictionary") + + # If graph is not in the expected format, try to extract adjacency list + if "nodes" in graph and "edges" in graph: + # 验证nodes和edges的类型 + if not isinstance(graph["nodes"], list): + raise TypeError("Nodes must be a list") + + if not isinstance(graph["edges"], list): + raise TypeError("Edges must be a list") + + # Convert from nodes/edges format to adjacency list + adjacency_list = {} + for node in graph["nodes"]: + # 验证node类型 + if not isinstance(node, dict): + raise TypeError("Each node must be a dictionary") + + # Use node ID as key, not the entire node dictionary + node_id = node.get("id", "") + if node_id: + adjacency_list[node_id] = {} + + for edge in graph["edges"]: + # 验证edge类型 + if not isinstance(edge, dict): + raise TypeError("Each edge must be a dictionary") + + u = edge["from"] + v = edge["to"] + weight = edge.get("weight", 1) # Default to unweighted + + # 类型检查 + if not isinstance(u, str): + raise TypeError("Edge 'from' must be a string") + + if not isinstance(v, str): + raise TypeError("Edge 'to' must be a string") + + if not isinstance(weight, (int, float)): + raise TypeError("Edge weight must be a number") + + if u not in adjacency_list: + adjacency_list[u] = {} + if v not in adjacency_list: + adjacency_list[v] = {} + + adjacency_list[u][v] = weight + # If undirected, add reverse edge + if not edge.get("directed", False): + adjacency_list[v][u] = weight + elif isinstance(graph, dict): + # Already in adjacency list format + adjacency_list = graph + + # 验证邻接表结构 + for node, neighbors in adjacency_list.items(): + if not isinstance(neighbors, dict): + raise TypeError("Adjacency list must be a dictionary of dictionaries") + + for neighbor, weight in neighbors.items(): + if not isinstance(weight, (int, float)): + raise TypeError("Edge weights must be numbers") + else: + raise TypeError("Graph data must be a dictionary") + + # 检查起点和终点是否为空 + if not start: + raise ValueError("Start node cannot be empty") + + if not end: + raise ValueError("End node cannot be empty") + + # 检查起点和终点是否在图中 + if start not in adjacency_list: + raise ValueError(f"Start node '{start}' not found in graph") + + if end not in adjacency_list: + raise ValueError(f"End node '{end}' not found in graph") + + # Dijkstra's algorithm implementation + import heapq + + # Initialize distances and previous nodes + distances = {node: float('infinity') for node in adjacency_list} + previous = {node: None for node in adjacency_list} + distances[start] = 0 + + # Priority queue + pq = [(0, start)] + heapq.heapify(pq) + + while pq: + current_dist, current_node = heapq.heappop(pq) + + # If we've reached the end node, we can break early + if current_node == end: + break + + # Nodes can be added multiple times to the priority queue, but we only process them once + if current_dist > distances[current_node]: + continue + + # Explore neighbors + for neighbor, weight in adjacency_list[current_node].items(): + distance = current_dist + weight + + # If a shorter path is found + if distance < distances[neighbor]: + distances[neighbor] = distance + previous[neighbor] = current_node + heapq.heappush(pq, (distance, neighbor)) + + # Reconstruct the shortest path + path = [] + current = end + while current is not None: + path.append(current) + current = previous[current] + path.reverse() # Reverse to get from start to end + + # Check if path exists + if not path or path[0] != start: + return {"path": "[]", "cost": 0} + + return { + "path": json.dumps(path), + "cost": distances[end] + } + except json.JSONDecodeError as e: + raise ValueError(f"Invalid JSON in graph data: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in graph_shortest_path: {str(e)}") + + # --- Crypto (Simplified) --- + def crypto_aes_cbc_decrypt(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 (使用模板中定义的参数名) + hex_cipher = inputs.get("hex_cipher") + hex_key = inputs.get("hex_key") + hex_iv = inputs.get("hex_iv") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + + if hex_key is not None and not isinstance(hex_key, str): + raise TypeError("hex_key must be a string") + + if hex_iv is not None and not isinstance(hex_iv, str): + raise TypeError("hex_iv must be a string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + + if hex_key is None: + raise ValueError("hex_key parameter is required") + + if hex_iv is None: + raise ValueError("hex_iv parameter is required") + + from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes + from cryptography.hazmat.backends import default_backend + from cryptography.hazmat.primitives import padding + + try: + # Convert hex strings to bytes + ciphertext = bytes.fromhex(hex_cipher) + key = bytes.fromhex(hex_key) + iv = bytes.fromhex(hex_iv) + + # Validate key length (AES-128, AES-192, AES-256) + if len(key) not in [16, 24, 32]: + raise ValueError("Invalid key length. Must be 16, 24, or 32 bytes.") + + if len(iv) != 16: + raise ValueError("Invalid IV length. Must be 16 bytes.") + + # Create cipher object + cipher = Cipher( + algorithms.AES(key), + modes.CBC(iv), + backend=default_backend() + ) + + decryptor = cipher.decryptor() + + # Decrypt the ciphertext + padded_plaintext = decryptor.update(ciphertext) + decryptor.finalize() + + # Remove PKCS7 padding + unpadder = padding.PKCS7(128).unpadder() + plaintext = unpadder.update(padded_plaintext) + unpadder.finalize() + + # Return decrypted text + return {"text": plaintext.decode('utf-8', errors='ignore')} + except ValueError as e: + if "non-hexadecimal number found in fromhex()" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher, hex_key, or hex_iv") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in crypto_aes_cbc_decrypt: {str(e)}") + + def crypto_rsa_decrypt_hex(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_cipher = inputs.get("hex_cipher") + n = inputs.get("n") + d = inputs.get("d") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + if n is not None and not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + if d is not None and not isinstance(d, (int, str)): + raise TypeError("d must be an integer or string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + if n is None: + raise ValueError("n parameter is required") + if d is None: + raise ValueError("d parameter is required") + + try: + # Convert parameters to appropriate types + cipher_int = int(hex_cipher, 16) + n_int = int(n) if isinstance(n, str) else n + d_int = int(d) if isinstance(d, str) else d + + # RSA decryption: plaintext = ciphertext^d mod n + plaintext_int = pow(cipher_int, d_int, n_int) + + # Convert result to hex and then to text + plaintext_hex = hex(plaintext_int)[2:] + + # Pad with leading zero if odd length + if len(plaintext_hex) % 2 != 0: + plaintext_hex = '0' + plaintext_hex + + # Convert hex to bytes and then to text + try: + plaintext_bytes = bytes.fromhex(plaintext_hex) + plaintext_text = plaintext_bytes.decode('utf-8', errors='ignore') + except: + # If decoding fails, return hex representation + plaintext_text = plaintext_hex + + return {"text": plaintext_text} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in crypto_rsa_decrypt_hex: {str(e)}") + + # --- Others --- + def num_base_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + s = inputs.get("s") + from_base = inputs.get("from_base") + to_base = inputs.get("to_base") + + # 类型检查 - 接受 str 或 int + if s is not None and not isinstance(s, (str, int)): + raise TypeError("s must be a string or integer") + + if from_base is not None and not isinstance(from_base, (int, str)): + raise TypeError("from_base must be an integer") + + if to_base is not None and not isinstance(to_base, (int, str)): + raise TypeError("to_base must be an integer") + + # 检查必需参数 + if s is None: + raise ValueError("s parameter is required") + + if from_base is None: + raise ValueError("from_base parameter is required") + + if to_base is None: + raise ValueError("to_base parameter is required") + + try: + # Convert to int if needed + from_base = int(from_base) if isinstance(from_base, str) else from_base + to_base = int(to_base) if isinstance(to_base, str) else to_base + s_str = str(s) + + # 验证基数范围 + if from_base < 2 or from_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + if to_base < 2 or to_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + # Convert from source base to decimal + val = int(s_str, from_base) + + # Convert from decimal to target base + if to_base == 10: + result = str(val) + elif to_base == 16: + result = hex(val)[2:] + elif to_base == 8: + result = oct(val)[2:] + elif to_base == 2: + result = bin(val)[2:] + else: + # Generic base conversion for other bases + if val == 0: + result = "0" + else: + digits = "0123456789abcdefghijklmnopqrstuvwxyz" + result = "" + n = abs(val) + while n: + result = digits[n % to_base] + result + n //= to_base + if val < 0: + result = "-" + result + + return {"str": result} + except ValueError as e: + raise ValueError(f"Invalid number format: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in num_base_convert: {str(e)}") + + def time_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iso = inputs.get("iso") + timestamp = inputs.get("timestamp") + datetime_str = inputs.get("datetime") + from_tz = inputs.get("from_tz") + to_tz = inputs.get("to_tz") + format_str = inputs.get("format") + + # 类型检查 + if iso is not None and not isinstance(iso, str): + raise TypeError("iso must be a string") + + if timestamp is not None and not isinstance(timestamp, (str, int, float)): + raise TypeError("timestamp must be a string, integer, or float") + + if datetime_str is not None and not isinstance(datetime_str, str): + raise TypeError("datetime must be a string") + + if from_tz is not None and not isinstance(from_tz, str): + raise TypeError("from_tz must be a string") + + if to_tz is not None and not isinstance(to_tz, str): + raise TypeError("to_tz must be a string") + + if format_str is not None and not isinstance(format_str, str): + raise TypeError("format must be a string") + + # 设置默认值 + if from_tz is None: + from_tz = "UTC" + + if to_tz is None: + to_tz = "UTC" + + import datetime + import pytz + + # 验证时区参数 + try: + if from_tz: + pytz.timezone(from_tz) + if to_tz: + pytz.timezone(to_tz) + except Exception: + raise ValueError("Invalid timezone provided") + + try: + # Parse input time + dt = None + + if iso is not None: + # Parse ISO 8601 format + dt = datetime.datetime.fromisoformat(iso.replace('Z', '+00:00')) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=pytz.UTC) + elif timestamp is not None: + # Parse Unix timestamp + timestamp = float(timestamp) + dt = datetime.datetime.fromtimestamp(timestamp, pytz.UTC) + elif datetime_str is not None: + # Parse datetime string + # Try common formats + formats_to_try = [ + "%Y-%m-%d %H:%M:%S", + "%Y-%m-%d %H:%M:%S.%f", + "%Y-%m-%d", + "%m/%d/%Y %H:%M:%S", + "%m/%d/%Y" + ] + + parse_success = False + for fmt in formats_to_try: + try: + dt = datetime.datetime.strptime(datetime_str, fmt) + dt = pytz.timezone(from_tz).localize(dt) + parse_success = True + break + except ValueError: + continue + + if not parse_success: + raise ValueError("Unable to parse datetime string with common formats") + else: + # 如果没有提供任何时间参数,则使用当前时间 + dt = datetime.datetime.now(pytz.UTC) + except ValueError as e: + raise ValueError(f"Error parsing time input: {str(e)}") + except Exception as e: + raise RuntimeError(f"Unexpected error parsing time input: {str(e)}") + + try: + # Convert timezone + if from_tz != to_tz: + dt = dt.astimezone(pytz.timezone(to_tz)) + + # Format outputs + result = { + "iso": dt.isoformat(), + "timestamp": str(dt.timestamp()), + "datetime": dt.strftime("%Y-%m-%d %H:%M:%S"), + "date": dt.strftime("%Y-%m-%d"), + "time": dt.strftime("%H:%M:%S"), + "timezone": to_tz + } + + # Add custom format if requested + if format_str: + try: + result["formatted"] = dt.strftime(format_str) + except ValueError as e: + raise ValueError(f"Invalid format string: {str(e)}") + + return result + except Exception as e: + raise RuntimeError(f"Error in time_convert: {str(e)}") + + def checksum_crc32(self, inputs): + import zlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("hex must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("hex parameter is required") + + try: + # 验证十六进制字符串 + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空 + if not hex_data: + raise ValueError("hex data cannot be empty") + + # 检查是否为有效的十六进制字符串 + if not all(c in "0123456789abcdefABCDEF" for c in hex_data): + raise ValueError("hex must be a valid hexadecimal string") + + # 检查长度是否为偶数 + if len(hex_data) % 2 != 0: + raise ValueError("hex must have even number of characters") + + val = zlib.crc32(bytes.fromhex(hex_data)) + # 确保 hex 输出是 8 位,前导补 0 + return {"hex": f"{val:08x}", "int": val} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in checksum_crc32: {str(e)}") + + def geo_haversine(self, inputs): + import math + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + lat1 = inputs.get("lat1") + lon1 = inputs.get("lon1") + lat2 = inputs.get("lat2") + lon2 = inputs.get("lon2") + + # 类型检查 + if lat1 is not None and not isinstance(lat1, (int, float, str)): + raise TypeError("lat1 must be a number or string") + if lon1 is not None and not isinstance(lon1, (int, float, str)): + raise TypeError("lon1 must be a number or string") + if lat2 is not None and not isinstance(lat2, (int, float, str)): + raise TypeError("lat2 must be a number or string") + if lon2 is not None and not isinstance(lon2, (int, float, str)): + raise TypeError("lon2 must be a number or string") + + # 检查必需参数 + if lat1 is None: + raise ValueError("lat1 parameter is required") + if lon1 is None: + raise ValueError("lon1 parameter is required") + if lat2 is None: + raise ValueError("lat2 parameter is required") + if lon2 is None: + raise ValueError("lon2 parameter is required") + + try: + # 转换为浮点数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(lat1, str): + lat1 = float(lat1) + elif not isinstance(lat1, (int, float)): + raise TypeError("lat1 must be a number or string") + else: + lat1 = float(lat1) + + if isinstance(lon1, str): + lon1 = float(lon1) + elif not isinstance(lon1, (int, float)): + raise TypeError("lon1 must be a number or string") + else: + lon1 = float(lon1) + + if isinstance(lat2, str): + lat2 = float(lat2) + elif not isinstance(lat2, (int, float)): + raise TypeError("lat2 must be a number or string") + else: + lat2 = float(lat2) + + if isinstance(lon2, str): + lon2 = float(lon2) + elif not isinstance(lon2, (int, float)): + raise TypeError("lon2 must be a number or string") + else: + lon2 = float(lon2) + + # Validate coordinates (approximate range check) + if not (-90 <= lat1 <= 90): + raise ValueError("lat1 must be between -90 and 90") + if not (-90 <= lat2 <= 90): + raise ValueError("lat2 must be between -90 and 90") + if not (-180 <= lon1 <= 180): + raise ValueError("lon1 must be between -180 and 180") + if not (-180 <= lon2 <= 180): + raise ValueError("lon2 must be between -180 and 180") + + # Earth radius in meters + R = 6371000 # Approximate radius of Earth + + # Convert degrees to radians + lat1_rad = math.radians(lat1) + lon1_rad = math.radians(lon1) + lat2_rad = math.radians(lat2) + lon2_rad = math.radians(lon2) + + # Calculate differences + delta_lat = lat2_rad - lat1_rad + delta_lon = lon2_rad - lon1_rad + + # Haversine formula + a = math.sin(delta_lat / 2) ** 2 + \ + math.cos(lat1_rad) * math.cos(lat2_rad) * \ + math.sin(delta_lon / 2) ** 2 + c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) + distance_m = R * c + + # Return distance in meters + return {"meters": round(distance_m, 2)} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in geo_haversine: {str(e)}") + + def otp_totp_generate(self, inputs): + import hmac + import hashlib + import base64 + import time + import struct + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + base32_secret = inputs.get("base32_secret") + step = inputs.get("step", 30) # Default to 30 seconds + digits = inputs.get("digits", 6) # Default to 6 digits + timestamp_iso = inputs.get("timestamp_iso", "") + algo = inputs.get("algo", "sha1") # Default to sha1 as current implementation only supports this + + # 类型检查 + if base32_secret is not None and not isinstance(base32_secret, str): + raise TypeError("base32_secret must be a string") + if not isinstance(step, (int, str)): + raise TypeError("step must be an integer or string") + if not isinstance(digits, (int, str)): + raise TypeError("digits must be an integer or string") + if not isinstance(timestamp_iso, str): + raise TypeError("timestamp_iso must be a string") + if not isinstance(algo, str): + raise TypeError("algo must be a string") + + # 检查必需参数 + if base32_secret is None: + raise ValueError("base32_secret parameter is required") + + try: + # Convert step and digits to appropriate types + step = int(step) + digits = int(digits) + if digits < 6 or digits > 8: + raise ValueError("Digits must be between 6 and 8") + + # Convert timestamp_iso to integer timestamp + if timestamp_iso: + import datetime + dt = datetime.datetime.fromisoformat(timestamp_iso.replace('Z', '+00:00')) + timestamp = int(dt.timestamp()) + else: + timestamp = int(time.time()) + + # Calculate counter value (T = floor(timestamp / step)) + counter = timestamp // step + + # Decode the base32 secret + # Add padding if necessary (base64 requires padding to be multiple of 8) + base32_secret = base32_secret.upper().replace(' ', '') + if len(base32_secret) % 8 != 0: + base32_secret += '=' * (8 - (len(base32_secret) % 8)) + key = base64.b32decode(base32_secret, casefold=True) + + # Calculate HMAC-SHA1 + counter_bytes = struct.pack('>Q', counter) # Big-endian 8-byte integer + hmac_hash = hmac.new(key, counter_bytes, hashlib.sha1).digest() + + # Dynamic truncation + offset = hmac_hash[-1] & 0xF + code = struct.unpack('>I', hmac_hash[offset:offset+4])[0] & 0x7FFFFFFF + + # Generate the OTP + otp = str(code % (10 ** digits)).zfill(digits) + + # Calculate remaining time until next OTP change + remaining_time = step - (timestamp % step) + + return {"totp": otp, "remaining_time": remaining_time, "time_step": step} + except ValueError as e: + if "invalid literal for int()" in str(e): + raise ValueError("step and digits must be valid integers") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in otp_totp_generate: {str(e)}") + + def unicode_norm(self, inputs): + import unicodedata + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + form = inputs.get("form", "NFC") # Default to NFC + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if form is not None and not isinstance(form, str): + raise TypeError("form must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Normalize form (NFC, NFD, NFKC, NFKD) + form = form.upper().strip() + + if form not in ['NFC', 'NFD', 'NFKC', 'NFKD']: + raise ValueError(f"Invalid normalization form: {form}. Must be one of: NFC, NFD, NFKC, NFKD") + + # Apply Unicode normalization + normalized_text = unicodedata.normalize(form, text) + + return {"text": normalized_text} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in unicode_norm: {str(e)}") + + def text_bidi_sanitize(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Bidi control characters to remove + bidi_controls = [ + '\u200E', # LEFT-TO-RIGHT MARK + '\u200F', # RIGHT-TO-LEFT MARK + '\u202A', # LEFT-TO-RIGHT EMBEDDING + '\u202B', # RIGHT-TO-LEFT EMBEDDING + '\u202C', # POP DIRECTIONAL FORMATTING + '\u202D', # LEFT-TO-RIGHT OVERRIDE + '\u202E', # RIGHT-TO-LEFT OVERRIDE + '\u2066', # LEFT-TO-RIGHT ISOLATE + '\u2067', # RIGHT-TO-LEFT ISOLATE + '\u2068', # FIRST STRONG ISOLATE + '\u2069', # POP DIRECTIONAL ISOLATE + ] + + # Remove all Bidi control characters + sanitized_text = text + for control_char in bidi_controls: + sanitized_text = sanitized_text.replace(control_char, '') + + return {"text": sanitized_text} + except Exception as e: + raise RuntimeError(f"Error in text_bidi_sanitize: {str(e)}") + + def text_xor_hex(self, inputs): + import binascii + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_a = inputs.get("hex_a") + hex_b = inputs.get("hex_b") + + # 类型检查 + if hex_a is not None and not isinstance(hex_a, str): + raise TypeError("hex_a must be a string") + if hex_b is not None and not isinstance(hex_b, str): + raise TypeError("hex_b must be a string") + + # 检查必需参数 + if hex_a is None: + raise ValueError("hex_a parameter is required") + if hex_b is None: + raise ValueError("hex_b parameter is required") + + try: + # Remove any whitespace + hex_a = hex_a.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + hex_b = hex_b.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + + # Validate hex strings + if not (all(c in "0123456789abcdefABCDEF" for c in hex_a) and len(hex_a) % 2 == 0): + raise ValueError("hex_a must be a valid hexadecimal string with even length") + if not (all(c in "0123456789abcdefABCDEF" for c in hex_b) and len(hex_b) % 2 == 0): + raise ValueError("hex_b must be a valid hexadecimal string with even length") + + # Convert hex strings to bytes + bytes_a = binascii.unhexlify(hex_a) + bytes_b = binascii.unhexlify(hex_b) + + # Make the byte arrays the same length by padding the shorter one with zeros + max_len = max(len(bytes_a), len(bytes_b)) + bytes_a = bytes_a.ljust(max_len, b'\x00') + bytes_b = bytes_b.ljust(max_len, b'\x00') + + # Perform XOR operation + result_bytes = bytes(a ^ b for a, b in zip(bytes_a, bytes_b)) + + # Convert result back to hex + result_hex = binascii.hexlify(result_bytes).decode('utf-8') + + return {"hex": result_hex} + except ValueError as e: + if "Non-hexadecimal digit found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in text_xor_hex: {str(e)}") + + def text_rotN(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + n = inputs.get("n", 0) + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + n = int(n) + except ValueError: + raise ValueError("n must be a valid integer") + + result = [] + for char in text: + if char.isupper(): + # Rotate uppercase letters + result_char = chr((ord(char) - ord('A') + n) % 26 + ord('A')) + result.append(result_char) + elif char.islower(): + # Rotate lowercase letters + result_char = chr((ord(char) - ord('a') + n) % 26 + ord('a')) + result.append(result_char) + else: + # Keep non-alphabetic characters unchanged + result.append(char) + + return {"text": ''.join(result)} + + def luhn_check(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数(支持 card_number 和 number 两个参数名) + card_number = inputs.get("number") or inputs.get("card_number") + + # 类型检查 + if card_number is not None and not isinstance(card_number, str): + raise TypeError("number must be a string") + + # 检查必需参数 + if card_number is None: + raise ValueError("number parameter is required") + + try: + # 如果输入是JSON数组或其他非数字字符串,返回该字符串本身(用于数据传递) + # 这种情况发生在DAG设计中类型不匹配时 + if card_number.startswith('[') or card_number.startswith('{'): + # 输入是JSON,直接返回原值(用于传递) + return {"valid": card_number} + + # Remove whitespace from card number + card_number = card_number.replace(" ", "").replace("-", "") + + # Check if card number is all digits + if not card_number.isdigit() or len(card_number) < 13: + return {"valid": "false"} + + # Implement Luhn algorithm + total = 0 + reverse_digits = card_number[::-1] # Reverse the number for easier processing + + for i, digit in enumerate(reverse_digits): + num = int(digit) + if i % 2 == 1: # Every second digit starting from the right (which is first in reversed string) + num *= 2 + if num > 9: + num -= 9 # Equivalent to sum of digits for 2-digit numbers + total += num + + # Check if total is divisible by 10 + is_valid = total % 10 == 0 + return {"valid": "true" if is_valid else "false"} + except Exception as e: + raise RuntimeError(f"Error in luhn_check: {str(e)}") + + def iban_validate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iban = inputs.get("iban") + + # 类型检查 + if iban is not None and not isinstance(iban, str): + raise TypeError("iban must be a string") + + # 检查必需参数 + if iban is None: + raise ValueError("iban parameter is required") + + try: + # Remove whitespace from IBAN + iban = iban.replace(" ", "") + + # Basic length and format check + if not (len(iban) >= 15 and len(iban) <= 34): + return {"valid": "False"} + + if not (iban[:2].isalpha() and iban[2:].isdigit()): + return {"valid": "False"} + + # Move first four characters to the end + rearranged = iban[4:] + iban[:4] + + # Replace letters with numbers (A=10, B=11, ..., Z=35) + numeric_iban = '' + for char in rearranged: + if char.isdigit(): + numeric_iban += char + else: + numeric_iban += str(ord(char.upper()) - ord('A') + 10) + + # Perform modulo 97 check + # Use step-by-step approach for very large numbers + remainder = 0 + for char in numeric_iban: + remainder = (remainder * 10 + int(char)) % 97 + + is_valid = remainder == 1 + return {"valid": "True" if is_valid else "False"} + except Exception as e: + raise RuntimeError(f"Error in iban_validate: {str(e)}") + + def matter_synthesizer(self, inputs): + import hashlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + blueprint = inputs.get("blueprint") + + # 类型检查 + if blueprint is not None and not isinstance(blueprint, str): + raise TypeError("blueprint must be a string") + + try: + # Get blueprint parameter as defined in interface + if blueprint is None: + blueprint = "" + + # Generate a unique item ID based on the blueprint + # This ensures the same blueprint always produces the same item + blueprint_hash = hashlib.sha256(blueprint.encode()).hexdigest()[:16] + + # Create a synthesized item with a deterministic ID based on blueprint + synthesized_item = f"synthesized_item_{blueprint_hash}" + + return {"output_slot": synthesized_item} + except Exception as e: + raise RuntimeError(f"Error in matter_synthesizer: {str(e)}") + + # --- Terminal Implementations --- + def terminal_1(self, inputs): + """ + terminal_1: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 只返回 text_output + - 只输入正确的 slot_b → 只返回 hex_output + - 同时输入正确的 slot_a 和 slot_b → 返回 item_dispenser(物品掉落) + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + # 检查哪些输入被提供了 + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值是否正确(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + expected_a = golden_inputs["slot_a"] + a_valid = str(slot_a) == str(expected_a) + + if has_b and "slot_b" in golden_inputs: + expected_b = golden_inputs["slot_b"] + b_valid = str(slot_b) == str(expected_b) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 item_dispenser + if has_a and has_b: + if a_valid and b_valid: + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 text_output + if has_a and not has_b: + if a_valid: + if "text_output" in golden_outputs: + result["text_output"] = golden_outputs["text_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 hex_output + if has_b and not has_a: + if b_valid: + if "hex_output" in golden_outputs: + result["hex_output"] = golden_outputs["hex_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def terminal_2(self, inputs): + """ + terminal_2: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 text_result + - 同时输入正确的 num1 和 num2 → 返回 hex_result 和 math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + # 检查哪些输入被提供了 + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值是否正确(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + expected_num1 = golden_inputs["num1"] + num1_valid = str(num1) == str(expected_num1) + + if has_num2 and "num2" in golden_inputs: + expected_num2 = golden_inputs["num2"] + num2_valid = str(num2) == str(expected_num2) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 hex_result 和 math_token + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 text_result + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "text_result" in golden_outputs: + result["text_result"] = golden_outputs["text_result"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def logic_terminal(self, inputs): + """ + Logic Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 返回 screen(部分输出) + - 只输入正确的 slot_b → 返回 screen 和 secondary_output + - 同时输入正确的 slot_a 和 slot_b → 返回 screen, secondary_output, item_dispenser + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + a_valid = str(slot_a) == str(golden_inputs["slot_a"]) + + if has_b and "slot_b" in golden_inputs: + b_valid = str(slot_b) == str(golden_inputs["slot_b"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出(包括 item_dispenser) + if has_a and has_b: + if a_valid and b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 screen(部分输出) + if has_a and not has_b: + if a_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 screen 和 secondary_output + if has_b and not has_a: + if b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def math_terminal(self, inputs): + """ + Math Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 result_display + - 同时输入正确的 num1 和 num2 → 返回 result_display, hex_result, math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + num1_valid = str(num1) == str(golden_inputs["num1"]) + + if has_num2 and "num2" in golden_inputs: + num2_valid = str(num2) == str(golden_inputs["num2"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 result_display + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def crypt_terminal(self, inputs): + """ + Encryption Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 plaintext → 返回 status(部分输出) + - 同时输入正确的 plaintext 和 key → 返回 status, encrypted_hex, encryption_chip + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + plaintext = inputs.get("plaintext") + key = inputs.get("key") + + has_plaintext = plaintext is not None and plaintext != "" + has_key = key is not None and key != "" + + # 验证输入值(与 golden values 比较) + plaintext_valid = False + key_valid = False + + if has_plaintext and "plaintext" in golden_inputs: + plaintext_valid = str(plaintext) == str(golden_inputs["plaintext"]) + + if has_key and "key" in golden_inputs: + key_valid = str(key) == str(golden_inputs["key"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_plaintext and has_key: + if plaintext_valid and key_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + if "encrypted_hex" in golden_outputs: + result["encrypted_hex"] = golden_outputs["encrypted_hex"] + if "encryption_chip" in golden_outputs: + result["encryption_chip"] = golden_outputs["encryption_chip"] + return result + else: + incorrect_params = [] + correct_params = [] + if not plaintext_valid: + incorrect_params.append("plaintext") + else: + correct_params.append("plaintext") + if not key_valid: + incorrect_params.append("key") + else: + correct_params.append("key") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 plaintext 且正确 → 返回 status(部分输出) + if has_plaintext and not has_key: + if plaintext_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: plaintext"} + + # 只提供 key 但没有 plaintext + if has_key and not has_plaintext: + return {"error": "plaintext required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + def sequence_terminal(self, inputs): + """ + Sequence Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 sequence → 返回 verification(部分输出) + - 同时输入正确的 sequence 和 checksum → 返回 verification, auth_code, access_card + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + sequence = inputs.get("sequence") + checksum = inputs.get("checksum") + + has_sequence = sequence is not None and sequence != "" + has_checksum = checksum is not None and checksum != "" + + # 验证输入值(与 golden values 比较) + sequence_valid = False + checksum_valid = False + + if has_sequence and "sequence" in golden_inputs: + sequence_valid = str(sequence) == str(golden_inputs["sequence"]) + + if has_checksum and "checksum" in golden_inputs: + checksum_valid = str(checksum) == str(golden_inputs["checksum"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_sequence and has_checksum: + if sequence_valid and checksum_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + if "auth_code" in golden_outputs: + result["auth_code"] = golden_outputs["auth_code"] + if "access_card" in golden_outputs: + result["access_card"] = golden_outputs["access_card"] + return result + else: + incorrect_params = [] + correct_params = [] + if not sequence_valid: + incorrect_params.append("sequence") + else: + correct_params.append("sequence") + if not checksum_valid: + incorrect_params.append("checksum") + else: + correct_params.append("checksum") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 sequence 且正确 → 返回 verification(部分输出) + if has_sequence and not has_checksum: + if sequence_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: sequence"} + + # 只提供 checksum 但没有 sequence + if has_checksum and not has_sequence: + return {"error": "sequence required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + # --- Additional File Tools --- + + def zip_unzip_file(self, inputs): + """ZIP 解压文件工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def zip_unzip_item(self, inputs): + """ZIP 解压道具工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def code_py_exec(self, inputs): + """Python 代码执行工具 + + 这是一个真实执行的工具,在 DAG 生成阶段和运行时评测阶段都会执行代码。 + 输入: code (Python 代码字符串) + 输出: stdout (标准输出,包含执行结果和错误信息) + + 特殊行为: + - 如果代码定义了 main() 函数,会自动调用它 + - 如果执行出错,错误信息会包含在 stdout 中 + """ + code = inputs.get("code", "") + + if not code: + return {"stdout": "Error: No code provided"} + + try: + # 创建一个受限的执行环境 + import io + import sys + + # 捕获标准输出和标准错误 + old_stdout = sys.stdout + old_stderr = sys.stderr + sys.stdout = io.StringIO() + sys.stderr = io.StringIO() + + # 执行代码 + exec_globals = {"__builtins__": __builtins__} + exec_locals = {} + exec(code, exec_globals, exec_locals) + + # 如果定义了 main() 函数,自动调用它 + if 'main' in exec_locals and callable(exec_locals['main']): + exec_locals['main']() + + # 获取输出 + stdout_value = sys.stdout.getvalue() + stderr_value = sys.stderr.getvalue() + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 合并 stdout 和 stderr + output = stdout_value + if stderr_value: + output += ("\n" if output else "") + f"[stderr] {stderr_value}" + + # 如果没有任何输出,尝试返回 result 变量的值 + if not output: + result = exec_locals.get("_result") or exec_locals.get("result") + if result is not None: + output = str(result) + + return {"stdout": output if output else "(no output)"} + + except Exception as e: + # 恢复标准输出和错误输出 + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 返回错误信息 + return {"stdout": f"Error: {type(e).__name__}: {str(e)}"} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-a8a2cf21/environment/puzzle/worker.Dockerfile b/tasks/agentescape-25-skeleton-a8a2cf21/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-25-skeleton-a8a2cf21/environment/puzzle/worker.Dockerfile @@ -0,0 +1,8 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends libseccomp2 && rm -rf /var/lib/apt/lists/* +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY worker.py child.py /app/ +COPY upstream/simulator.py /app/simulator.py +CMD ["uvicorn", "worker:app", "--host", "0.0.0.0", "--port", "8001", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-25-skeleton-a8a2cf21/environment/puzzle/worker.py b/tasks/agentescape-25-skeleton-a8a2cf21/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-25-skeleton-a8a2cf21/environment/puzzle/worker.py @@ -0,0 +1,73 @@ +"""Stateless Python tool worker. Never receives a scenario or reference values.""" + +import json +import os +import signal +import subprocess +import sys +import tempfile +import threading + +from fastapi import FastAPI +from pydantic import BaseModel, ConfigDict + +app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) +lock = threading.Lock() + + +class Execution(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + code: str + + +@app.get("/health") +def health(): + return {"ok": True} + + +@app.post("/execute") +def execute(request: Execution): + if len(request.code.encode()) > 65536: + return {"stdout": "Error: code exceeds 64 KiB limit"} + with lock, tempfile.TemporaryDirectory(prefix="escape-code-") as directory: + os.chown(directory, 65534, 65534) + with tempfile.TemporaryFile() as output: + process = subprocess.Popen( + [sys.executable, "-I", "/app/child.py"], + stdin=subprocess.PIPE, + stdout=output, + stderr=subprocess.DEVNULL, + cwd=directory, + user=65534, + group=65534, + extra_groups=[], + start_new_session=True, + env={"PATH": "/usr/local/bin:/usr/bin:/bin"}, + ) + try: + process.communicate( + json.dumps({"code": request.code}).encode(), timeout=5 + ) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + return {"stdout": "Error: Python execution timed out"} + finally: + # Also remove children still in the process group after normal exit. + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + output.seek(0) + value = output.read(65537) + if len(value) > 65536 or process.returncode != 0: + return { + "stdout": "Error: Python execution exceeded a resource limit or failed" + } + try: + result = json.loads(value) + if not isinstance(result.get("stdout"), str): + raise ValueError("Invalid worker response") + return result + except (ValueError, AttributeError): + return {"stdout": "Error: Python execution returned invalid output"} diff --git a/tasks/agentescape-25-skeleton-a8a2cf21/instruction.md b/tasks/agentescape-25-skeleton-a8a2cf21/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-25-skeleton-a8a2cf21/instruction.md @@ -0,0 +1,18 @@ +# Escape the room + +Discover the victory string and submit it with `escape submit-answer`. +Start with `escape observe`. This returns the room, available information, visible entities, and victory node ID. + +Use these commands (JSON responses): + +```sh +escape investigate NODE_ID +escape tool-call NODE_ID --arguments-json '{"parameter": "value"}' +escape use-item NODE_ID --arguments-json '{"parameter": "value"}' +escape submit-answer 'exact victory string' +escape state +``` + +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. + +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. diff --git a/tasks/agentescape-25-skeleton-a8a2cf21/solution/oracle.py b/tasks/agentescape-25-skeleton-a8a2cf21/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-25-skeleton-a8a2cf21/solution/oracle.py @@ -0,0 +1,133 @@ +"""Reference solver: use trusted inputs, but obtain the answer through public actions.""" + +import json +import urllib.request +from pathlib import Path + + +def http_action(base_url, payload): + request = urllib.request.Request( + base_url + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(request, timeout=30) as response: + return json.load(response) + + +def solve(scenario, act, observe): + nodes = {node["id"]: node for node in scenario["nodes"]} + visible = {entity["id"] for entity in observe["available_entities"]} + solved = set() + seen_outputs = {} + action_count = 0 + + def call(payload): + nonlocal action_count + action_count += 1 + response = act(payload) + visible.update(entity["id"] for entity in response.get("newly_revealed", [])) + if ( + response.get("episode", {}).get("termination_reason") + == "infrastructure_error" + ): + raise RuntimeError("Infrastructure failure") + return response + + for _round in range(len(nodes) + 2): + progress = False + for node_id, node in nodes.items(): + if node_id not in visible or node_id in solved: + continue + # Preserve graph order for data inputs; trigger/drop edges express visibility. + predecessors = [ + edge["source_id"] + for edge in scenario["edges"] + if edge["target_id"] == node_id + and edge["connection_type"] not in ("Item", "Hidden_Item") + ] + if any(pred not in solved for pred in predecessors): + continue + info = call({"action": "investigate", "node_id": node_id}) + if not info.get("ok"): + raise RuntimeError(f"Investigation failed: {node_id}: {info}") + inputs = { + port["name"]: port["value"] + for port in node.get("inputs", []) + if "value" in port + } + if node["type"] == "Tool": + result = call( + {"action": "tool_call", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok") or result.get("output_values", {}).get("error"): + raise RuntimeError(f"Tool failed: {node_id}: {result}") + output = result.get("output_values", {}) + if node.get("template_id") in ("terminal_1", "terminal_2"): + slots = { + port["name"]: inputs[port["name"]] + for port in node["inputs"] + if port["type"] not in ("Item", "Hidden_Item") + and port["name"] in inputs + } + triggers = { + key: value for key, value in inputs.items() if key not in slots + } + for key, value in slots.items(): + partial = call( + { + "action": "tool_call", + "node_id": node_id, + "arguments": {**triggers, key: value}, + } + ) + if partial.get("ok"): + output.update(partial.get("output_values", {})) + # HIDDEN_ITEM tool drops only occur on subsequent investigation. + call({"action": "investigate", "node_id": node_id}) + elif info.get("required_inputs"): + result = call( + {"action": "use_item", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok"): + raise RuntimeError(f"Item failed: {node_id}: {result}") + output = result.get("content") + else: + output = info.get("content") + seen_outputs[node_id] = output + solved.add(node_id) + progress = True + win_id = scenario["metadata"]["win_node_id"] + if win_id in solved and (len(solved) == len(nodes) or not progress): + outputs = seen_outputs[win_id] + if not outputs: + raise RuntimeError(f"Victory node returned no output: {win_id}") + # Upstream grades its first stored output port, independent of response order. + victory_port = next( + port["name"] for port in nodes[win_id]["outputs"] if "value" in port + ) + answer = outputs[victory_port] if isinstance(outputs, dict) else outputs + result = call({"action": "submit_answer", "answer": answer}) + if not result.get("is_win"): + raise RuntimeError(f"Victory submission failed: {result}") + return {"won": True, "actions": action_count, "visited_nodes": len(solved)} + if not progress: + raise RuntimeError(f"No progress: visible={visible}, solved={solved}") + raise RuntimeError("Reference solver exceeded graph traversal limit") + + +if __name__ == "__main__": + import os + + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000") + with urllib.request.urlopen(base + "/observation", timeout=20) as response: + observation = json.load(response) + print( + json.dumps( + solve( + json.loads(Path("/solution/scenario.json").read_text()), + lambda payload: http_action(base, payload), + observation, + ) + ) + ) diff --git a/tasks/agentescape-25-skeleton-a8a2cf21/solution/scenario.json b/tasks/agentescape-25-skeleton-a8a2cf21/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..541fb46924888a1a4bc2baaea00bc25aa3bb711d --- /dev/null +++ b/tasks/agentescape-25-skeleton-a8a2cf21/solution/scenario.json @@ -0,0 +1,1401 @@ +{ + "metadata": { + "total_nodes": 25, + "total_edges": 28, + "win_node_id": "item_7", + "win_condition": { + "type": "item_content", + "node_id": "item_7", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_7", + "terminal_2", + "graph_shortest_path", + "json_get", + "zip_unzip_file", + "calc_inv_mod", + "graph_shortest_path_fc39", + "crypto_rsa_decrypt_hex", + "time_convert", + "calc_bigmul", + "zip_unzip_item", + "item_9", + "item_3" + ], + "by_node": { + "item_7": { + "node_name": "", + "node_type": "Item", + "template_id": "item_7", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Code_Python", + "description": "The integer" + } + } + }, + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": { + "num2": { + "type": "Big_Int", + "description": "Second Number" + } + }, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + } + } + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": {}, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "json_get": { + "node_name": "JSON Getter", + "node_type": "Tool", + "template_id": "json_get", + "init_inputs": {}, + "init_outputs": { + "values": { + "type": "Text_Generic", + "description": "Extracted values" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "calc_inv_mod": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "Integer a" + } + }, + "init_outputs": {} + }, + "graph_shortest_path_fc39": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "Graph JSON file ID" + }, + "src": { + "type": "Text_Generic", + "description": "Source node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "crypto_rsa_decrypt_hex": { + "node_name": "RSA Decrypt", + "node_type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "init_inputs": { + "hex_cipher": { + "type": "Hex_String", + "description": "Ciphertext (Hex)" + }, + "n": { + "type": "Big_Int", + "description": "Modulus n" + }, + "d": { + "type": "Big_Int", + "description": "Private exponent d" + } + }, + "init_outputs": {} + }, + "time_convert": { + "node_name": "Timezone Converter", + "node_type": "Tool", + "template_id": "time_convert", + "init_inputs": { + "iso": { + "type": "Text_Generic", + "description": "ISO Timestamp" + }, + "from_tz": { + "type": "Text_Generic", + "description": "From Timezone" + }, + "to_tz": { + "type": "Text_Generic", + "description": "To Timezone" + } + }, + "init_outputs": {} + }, + "calc_bigmul": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First large integer" + }, + "b": { + "type": "Big_Int", + "description": "Second large integer" + } + }, + "init_outputs": {} + }, + "zip_unzip_item": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_item", + "init_inputs": { + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": {} + }, + "item_9": { + "node_name": "", + "node_type": "Item", + "template_id": "item_9", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "File_Id", + "description": "JSON file path" + } + } + }, + "item_3": { + "node_name": "", + "node_type": "Item", + "template_id": "item_3", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Hex_String", + "description": "The hex code" + } + } + } + } + }, + "initial_values": { + "item_7": { + "init_inputs": {}, + "init_outputs": { + "content": "def get_integer():\n return 42\n" + } + }, + "terminal_2": { + "init_inputs": { + "num2": "8394827163849502938475" + }, + "init_outputs": { + "text_result": "Partial output evaluated successfully.", + "hex_result": "deadbeef1234567890abcdef" + } + }, + "graph_shortest_path": { + "init_inputs": {}, + "init_outputs": { + "path": "[\"NodeA\", \"NodeD\", \"NodeF\", \"NodeK\", \"NodeZ\"]", + "cost": "482910" + } + }, + "json_get": { + "init_inputs": {}, + "init_outputs": { + "values": "[\"value_1\", \"value_2\", \"value_3\", \"value_4\", \"value_5\"]" + } + }, + "zip_unzip_file": { + "init_inputs": { + "zip_id": "archive_data_738.zip" + }, + "init_outputs": { + "files": "extracted_documents_92.json" + } + }, + "calc_inv_mod": { + "init_inputs": { + "a": "5948372610594837261948" + }, + "init_outputs": {} + }, + "graph_shortest_path_fc39": { + "init_inputs": { + "file_id": "network_topology_map.json", + "src": "EntryPoint_Alpha" + }, + "init_outputs": { + "path": "[\"Start\", \"Router1\", \"SwitchA\", \"Gateway\", \"TargetNode\"]", + "cost": "738291" + } + }, + "crypto_rsa_decrypt_hex": { + "init_inputs": { + "hex_cipher": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d", + "n": "987654321098765432109876543210", + "d": "123456789012345678901234567890" + }, + "init_outputs": {} + }, + "time_convert": { + "init_inputs": { + "iso": "2023-10-15T14:30:00Z", + "from_tz": "UTC", + "to_tz": "America/New_York" + }, + "init_outputs": {} + }, + "calc_bigmul": { + "init_inputs": { + "a": "4445556667778889990001", + "b": "1112223334445556667778" + }, + "init_outputs": {} + }, + "zip_unzip_item": { + "init_inputs": { + "password": "SecurePass2024!" + }, + "init_outputs": {} + }, + "item_9": { + "init_inputs": {}, + "init_outputs": { + "content": "configuration_settings.json" + } + }, + "item_3": { + "init_inputs": {}, + "init_outputs": { + "content": "badc0ffee0ddf00d" + } + } + }, + "intro_narrative": "Welcome, traveler, to the forgotten Sanctuary of the Archmage. Here, magic and arcane machinery intertwine, guarding secrets long thought lost to the ages. The Archmage sealed his ultimate treasure, The Royal Seal, deep within this sanctum before his sudden disappearance. You stand in the grand antechamber, surrounded by cryptic artifacts, silent constructs, and enchanted stones. Your objective is clear: navigate this labyrinth of arcane logic, harness the powers of ancient relics, and retrieve the Seal. But beware, the path is fraught with interwoven wards and dependencies. You must decipher the flows of magical energy and figure out which artifacts awaken each other. Trust your intuition and intellect to conquer the sanctuary's trials and prove your worth.", + "narrative_style": "fantasy" + }, + "nodes": [ + { + "id": "item_7", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_7", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Code_Python", + "description": "The integer", + "value": "def get_integer():\n return 42\n" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "def get_integer():\n return 42\n" + } + }, + "narrative": "The Royal Seal, the ultimate symbol of the lost kingdom's authority, resting upon a velvet cushion." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A glowing Moonstone Artifact, pulsating with gentle lunar energy." + }, + { + "id": "container_3", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_3", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Big_Int", + "description": "Fingerprint Hash", + "value": "482910" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is The Silver Chest, bound by magical wards. It requires input from The Leyline Navigator to unlock." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A translucent Ethereal Gem that seems to float effortlessly in your hand." + }, + { + "id": "item_16_33d4", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A radiant Sunstone Artifact, warm to the touch and blazing with inner light." + }, + { + "id": "terminal_2", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "738291" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "8394827163849502938475" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Partial output evaluated successfully." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "deadbeef1234567890abcdef" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": { + "num2": "8394827163849502938475" + }, + "outputs": { + "text_result": "Partial output evaluated successfully.", + "hex_result": "deadbeef1234567890abcdef" + } + }, + "narrative": "This is The Oracle's Altar. It requires input from The Alchemist's Crucible to speak the ancient prophecies." + }, + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "extracted_documents_92.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "[\"value_1\", \"value_2\", \"value_3\", \"value_4\", \"value_5\"]" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Partial output evaluated successfully." + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"NodeA\", \"NodeD\", \"NodeF\", \"NodeK\", \"NodeZ\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "482910" + } + ], + "init": { + "inputs": {}, + "outputs": { + "path": "[\"NodeA\", \"NodeD\", \"NodeF\", \"NodeK\", \"NodeZ\"]", + "cost": "482910" + } + }, + "narrative": "This is The Leyline Navigator. It requires inputs from The Oracle's Altar, The Spirit Reader, and The Spell Unbinder to chart the magical currents." + }, + { + "id": "json_get", + "name": "JSON Getter", + "description": "Extract values by simple JSONPath.", + "type": "Tool", + "template_id": "json_get", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "JSON file ID", + "value": "extracted_documents_92.json" + }, + { + "name": "jsonpath", + "type": "Text_Generic", + "description": "JSONPath expression", + "value": "\u0001oG~\tqwu" + } + ], + "outputs": [ + { + "name": "values", + "type": "Text_Generic", + "description": "Extracted values", + "value": "[\"value_1\", \"value_2\", \"value_3\", \"value_4\", \"value_5\"]" + } + ], + "init": { + "inputs": {}, + "outputs": { + "values": "[\"value_1\", \"value_2\", \"value_3\", \"value_4\", \"value_5\"]" + } + }, + "narrative": "This is The Spirit Reader. It requires inputs from The Spell Unbinder and The Rune Decipherer to channel the spirits." + }, + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "archive_data_738.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Partial output evaluated successfully." + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_documents_92.json" + } + ], + "init": { + "inputs": { + "zip_id": "archive_data_738.zip" + }, + "outputs": { + "files": "extracted_documents_92.json" + } + }, + "narrative": "This is The Spell Unbinder. It requires input from The Oracle's Altar to break the protective wards." + }, + { + "id": "num_base_convert", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "738291" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "5948372610594837261948" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "4944451860503714814811970487770485298887778" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "738291" + } + ], + "narrative": "This is The Alchemist's Crucible. It requires inputs from The Astral Reverser, The Starpath Navigator, and The Mana Multiplier to transmute the elements." + }, + { + "id": "calc_inv_mod", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "5948372610594837261948" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": 1896241797 + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "5948372610594837261948" + } + ], + "init": { + "inputs": { + "a": "5948372610594837261948" + }, + "outputs": {} + }, + "narrative": "This is The Astral Reverser, a device that inverts magical flows. It requires input from The Essence Purifier." + }, + { + "id": "container_3_eeca", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_3", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Big_Int", + "description": "Fingerprint Hash", + "value": "738291" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is The Golden Chest, sealed with celestial magic. It requires input from The Starpath Navigator to open." + }, + { + "id": "graph_shortest_path_fc39", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "network_topology_map.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "EntryPoint_Alpha" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "2023-10-15T10:30:00-04:00" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Start\", \"Router1\", \"SwitchA\", \"Gateway\", \"TargetNode\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "738291" + } + ], + "init": { + "inputs": { + "file_id": "network_topology_map.json", + "src": "EntryPoint_Alpha" + }, + "outputs": { + "path": "[\"Start\", \"Router1\", \"SwitchA\", \"Gateway\", \"TargetNode\"]", + "cost": "738291" + } + }, + "narrative": "This is The Starpath Navigator. It requires input from The Chronos Pendulum to plot the celestial coordinates." + }, + { + "id": "item_8_8f97", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A deep black Void Crystal, seemingly absorbing all surrounding light into its core." + }, + { + "id": "crypto_rsa_decrypt_hex", + "name": "RSA Decrypt", + "description": "RSA decrypt (hex cipher) with n,d (decimal).", + "type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex_cipher", + "type": "Hex_String", + "description": "Ciphertext (Hex)", + "value": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Modulus n", + "value": "987654321098765432109876543210" + }, + { + "name": "d", + "type": "Big_Int", + "description": "Private exponent d", + "value": "123456789012345678901234567890" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decrypted text", + "value": "\u0001oG~\tqwu" + } + ], + "init": { + "inputs": { + "hex_cipher": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d", + "n": "987654321098765432109876543210", + "d": "123456789012345678901234567890" + }, + "outputs": {} + }, + "narrative": "The Rune Decipherer, a stone tablet covered in translating runes that hum softly." + }, + { + "id": "time_convert", + "name": "Timezone Converter", + "description": "Convert ISO time between timezones.", + "type": "Tool", + "template_id": "time_convert", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "iso", + "type": "Text_Generic", + "description": "ISO Timestamp", + "value": "2023-10-15T14:30:00Z" + }, + { + "name": "from_tz", + "type": "Text_Generic", + "description": "From Timezone", + "value": "UTC" + }, + { + "name": "to_tz", + "type": "Text_Generic", + "description": "To Timezone", + "value": "America/New_York" + } + ], + "outputs": [ + { + "name": "iso", + "type": "Text_Generic", + "description": "Converted ISO Timestamp", + "value": "2023-10-15T10:30:00-04:00" + } + ], + "init": { + "inputs": { + "iso": "2023-10-15T14:30:00Z", + "from_tz": "UTC", + "to_tz": "America/New_York" + }, + "outputs": {} + }, + "narrative": "The Chronos Pendulum, a magical artifact that sways continuously regardless of gravity." + }, + { + "id": "item_8_ed94", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A cold Shadow Tear, whispering forgotten secrets into the mind of its holder." + }, + { + "id": "calc_bigmul", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "4445556667778889990001" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "1112223334445556667778" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "4944451860503714814811970487770485298887778" + } + ], + "init": { + "inputs": { + "a": "4445556667778889990001", + "b": "1112223334445556667778" + }, + "outputs": {} + }, + "narrative": "The Mana Multiplier, an intricate brass astrolabe crackling with chaotic energy." + }, + { + "id": "checksum_crc32", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "badc0ffee0ddf00d" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "71065a85" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 1896241797 + } + ], + "narrative": "This is The Essence Purifier, an enchanted basin. It requires input from The Dragon Scale to work." + }, + { + "id": "item_8_448d", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A dark Blood Opal, swirling with crimson shadows and pulsing like a heartbeat." + }, + { + "id": "zip_unzip_item", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_item", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "configuration_settings.json" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "SecurePass2024!" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip" + } + ], + "init": { + "inputs": { + "password": "SecurePass2024!" + }, + "outputs": {} + }, + "narrative": "This is The Curse Breaker. It requires input from The Ancient Scroll to lift the complex hex." + }, + { + "id": "item_9", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_9", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "File_Id", + "description": "JSON file path", + "value": "configuration_settings.json" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "configuration_settings.json" + } + }, + "narrative": "A fragile Ancient Scroll bound with a dusty ribbon, smelling of old parchment." + }, + { + "id": "item_8_cc60", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A piece of Forest Amber containing a trapped, glowing fairy frozen in time." + }, + { + "id": "item_3", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_3", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hex_String", + "description": "The hex code", + "value": "badc0ffee0ddf00d" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "badc0ffee0ddf00d" + } + }, + "narrative": "A shimmering Dragon Scale, hard as diamond and inscribed with powerful runes." + }, + { + "id": "item_8_f6e6", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A brilliant Frost Diamond that never melts, radiating a freezing aura." + } + ], + "edges": [ + { + "source_id": "item_16", + "target_id": "item_7", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "container_3", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "item_8", + "target_id": "container_3", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "item_16_33d4", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "terminal_2", + "target_id": "item_16_33d4", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "source_tool" + }, + { + "source_id": "graph_shortest_path", + "target_id": "container_3", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "fingerprint_input" + }, + { + "source_id": "terminal_2", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "dst" + }, + { + "source_id": "json_get", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "values", + "target_port": "src" + }, + { + "source_id": "zip_unzip_file", + "target_id": "json_get", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "terminal_2", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "password" + }, + { + "source_id": "num_base_convert", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "num1" + }, + { + "source_id": "calc_inv_mod", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "from_base" + }, + { + "source_id": "container_3_eeca", + "target_id": "calc_inv_mod", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "graph_shortest_path_fc39", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "s" + }, + { + "source_id": "item_8_8f97", + "target_id": "container_3_eeca", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "graph_shortest_path_fc39", + "target_id": "container_3_eeca", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "fingerprint_input" + }, + { + "source_id": "crypto_rsa_decrypt_hex", + "target_id": "json_get", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "jsonpath" + }, + { + "source_id": "time_convert", + "target_id": "graph_shortest_path_fc39", + "connection_type": "Text_Generic", + "source_port": "iso", + "target_port": "dst" + }, + { + "source_id": "item_8_ed94", + "target_id": "item_8_8f97", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "calc_bigmul", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "to_base" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "mod" + }, + { + "source_id": "item_8_448d", + "target_id": "item_8_ed94", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "zip_unzip_item", + "target_id": "time_convert", + "connection_type": "Item", + "source_port": "item", + "target_port": "trigger_item" + }, + { + "source_id": "item_9", + "target_id": "zip_unzip_item", + "connection_type": "File_Id", + "source_port": "content", + "target_port": "zip_id" + }, + { + "source_id": "item_8_cc60", + "target_id": "item_8_448d", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_3", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "content", + "target_port": "hex" + }, + { + "source_id": "item_8_f6e6", + "target_id": "item_3", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-a8a2cf21/solution/solve.sh b/tasks/agentescape-25-skeleton-a8a2cf21/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-25-skeleton-a8a2cf21/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-25-skeleton-a8a2cf21/task.toml b/tasks/agentescape-25-skeleton-a8a2cf21/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1d20a2f41a28e294d79363ac003e7697467f2d2c --- /dev/null +++ b/tasks/agentescape-25-skeleton-a8a2cf21/task.toml @@ -0,0 +1,38 @@ +schema_version = "1.4" +source = "https://github.com/AGI-Eval-Official/Repo-of-AgentEscapeBench" + +[[artifacts]] +source = "/evidence/final.json" +service = "puzzle" + +[[artifacts]] +source = "/evidence/trace.jsonl" +service = "puzzle" + +[task] +name = "edbeeching/agentescape-25-skeleton-a8a2cf21" +version = "0.1.0" + +[metadata] +difficulty = 25 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "ff17a95784c70425e15b3edf0d40a6f8393251aa1a063c878d50c2bda3fc5b9b" +protocol = "harbor-cli-action-budget-v1" +max_actions = 500 + +[agent] +timeout_sec = 1200 + +[environment] +build_timeout_sec = 900 +cpus = 1 +memory_mb = 1024 + +[verifier] +environment_mode = "separate" +timeout_sec = 60 + +[[verifier.collect]] +service = "puzzle" +command = "python -I /app/export.py" +timeout_sec = 15 diff --git a/tasks/agentescape-25-skeleton-a8a2cf21/tests/Dockerfile b/tasks/agentescape-25-skeleton-a8a2cf21/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-25-skeleton-a8a2cf21/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-25-skeleton-a8a2cf21/tests/expected.json b/tasks/agentescape-25-skeleton-a8a2cf21/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..d4db9b10a1fda11db25eb09ba140a9812750439b --- /dev/null +++ b/tasks/agentescape-25-skeleton-a8a2cf21/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "ff17a95784c70425e15b3edf0d40a6f8393251aa1a063c878d50c2bda3fc5b9b", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-a8a2cf21/tests/grade.py b/tasks/agentescape-25-skeleton-a8a2cf21/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-25-skeleton-a8a2cf21/tests/grade.py @@ -0,0 +1,21 @@ +"""Grade only Harbor-collected sidecar evidence in a fresh verifier container.""" + +import json +from pathlib import Path + +expected = json.loads(Path("/tests/expected.json").read_text()) +state = json.loads(Path("/evidence/final.json").read_text()) +assert state["collected_from_live_service"] is True, "Missing trusted service export" +assert state["scenario_sha256"] == expected["scenario_sha256"], ( + "Wrong scenario evidence" +) +assert state["max_actions"] == expected["max_actions"], "Wrong budget" +assert type(state["won"]) is bool +assert 0 <= state["action_count"] <= state["max_actions"] +assert state["termination_reason"] != "infrastructure_error", ( + "Infrastructure failure is not a puzzle failure" +) +assert not state["won"] or state["termination_reason"] == "success" +Path("/logs/verifier").mkdir(parents=True, exist_ok=True) +Path("/logs/verifier/state.json").write_text(json.dumps(state, indent=2)) +Path("/logs/verifier/reward.txt").write_text("1.0\n" if state["won"] else "0.0\n") diff --git a/tasks/agentescape-25-skeleton-a8a2cf21/tests/test.sh b/tasks/agentescape-25-skeleton-a8a2cf21/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-25-skeleton-a8a2cf21/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-25-skeleton-ad399fad/environment/Dockerfile b/tasks/agentescape-25-skeleton-ad399fad/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-25-skeleton-ad399fad/environment/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-25-skeleton-ad399fad/environment/agent/Dockerfile b/tasks/agentescape-25-skeleton-ad399fad/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-25-skeleton-ad399fad/environment/agent/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-25-skeleton-ad399fad/environment/agent/cli.py b/tasks/agentescape-25-skeleton-ad399fad/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-25-skeleton-ad399fad/environment/agent/cli.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Public agent client; depends only on the Python standard library.""" + +import argparse +import json +import os +import sys +import urllib.error +import urllib.request + + +def main(): + parser = argparse.ArgumentParser(description="Interact with the escape room") + parser.add_argument( + "action", + choices=[ + "observe", + "state", + "investigate", + "tool-call", + "use-item", + "submit-answer", + ], + ) + parser.add_argument("value", nargs="?") + parser.add_argument("--arguments-json", default="{}") + args = parser.parse_args() + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000").rstrip("/") + if args.action in ("observe", "state"): + request = urllib.request.Request( + base + ("/observation" if args.action == "observe" else "/state") + ) + else: + if args.value is None: + parser.error("node ID or answer is required") + payload = {"action": args.action.replace("-", "_")} + if args.action == "submit-answer": + payload["answer"] = args.value + else: + payload["node_id"] = args.value + if args.action in ("tool-call", "use-item"): + payload["arguments"] = json.loads(args.arguments_json) + request = urllib.request.Request( + base + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=30) as response: + print(json.dumps(json.load(response), ensure_ascii=False)) + except (urllib.error.URLError, ValueError) as exc: + print(json.dumps({"ok": False, "error": str(exc)})) + sys.exit(2) + + +if __name__ == "__main__": + main() diff --git a/tasks/agentescape-25-skeleton-ad399fad/environment/docker-compose.yaml b/tasks/agentescape-25-skeleton-ad399fad/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a31f8034d3fc590937836dea9904d80bd0cb935b --- /dev/null +++ b/tasks/agentescape-25-skeleton-ad399fad/environment/docker-compose.yaml @@ -0,0 +1,50 @@ +services: + main: + image: agentescapebench-agent:aab05a0a9ddb + build: + context: ./agent + networks: [default, puzzle] + security_opt: [no-new-privileges:true] + depends_on: + puzzle: + condition: service_healthy + puzzle: + image: agentescapebench-puzzle:agentescape-25-skeleton-ad399fad-aab05a0a9ddb + build: + context: ./puzzle + networks: [puzzle, execution] + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 512m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"] + interval: 1s + timeout: 3s + retries: 30 + depends_on: + worker: + condition: service_healthy + worker: + image: agentescapebench-worker:aab05a0a9ddb + build: + context: ./puzzle + dockerfile: worker.Dockerfile + networks: [execution] + read_only: true + tmpfs: ["/tmp:size=64m,mode=1777"] + cap_drop: [ALL] + cap_add: [SETUID, SETGID, KILL, CHOWN, DAC_OVERRIDE] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 384m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8001/health')"] + interval: 1s + timeout: 3s + retries: 30 +networks: + puzzle: + internal: true + execution: + internal: true diff --git a/tasks/agentescape-25-skeleton-ad399fad/environment/puzzle/Dockerfile b/tasks/agentescape-25-skeleton-ad399fad/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-25-skeleton-ad399fad/environment/puzzle/Dockerfile @@ -0,0 +1,9 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY upstream /app/upstream +COPY service.py export.py /app/ +COPY scenario.json /private/scenario.json +ENV SCENARIO_PATH=/private/scenario.json EVIDENCE_DIR=/evidence WORKER_URL=http://worker:8001 MAX_ACTIONS=500 +CMD ["uvicorn", "service:create_app", "--factory", "--host", "0.0.0.0", "--port", "8000", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-25-skeleton-ad399fad/environment/puzzle/child.py b/tasks/agentescape-25-skeleton-ad399fad/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-25-skeleton-ad399fad/environment/puzzle/child.py @@ -0,0 +1,59 @@ +"""Run the original Python tool after reducing privileges and blocking networking.""" + +import ctypes +import errno +import json +import resource +import sys + +resource.setrlimit(resource.RLIMIT_CPU, (3, 3)) +resource.setrlimit(resource.RLIMIT_AS, (256 * 1024 * 1024, 256 * 1024 * 1024)) +resource.setrlimit(resource.RLIMIT_FSIZE, (65536, 65536)) +resource.setrlimit(resource.RLIMIT_NOFILE, (32, 32)) +resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + +# Filters survive fork/exec. Fail closed if seccomp cannot be loaded. +lib = ctypes.CDLL("libseccomp.so.2", use_errno=True) +lib.seccomp_init.argtypes = [ctypes.c_uint32] +lib.seccomp_init.restype = ctypes.c_void_p +lib.seccomp_rule_add.argtypes = [ + ctypes.c_void_p, + ctypes.c_uint32, + ctypes.c_int, + ctypes.c_uint, +] +lib.seccomp_syscall_resolve_name.argtypes = [ctypes.c_char_p] +lib.seccomp_load.argtypes = [ctypes.c_void_p] +lib.seccomp_release.argtypes = [ctypes.c_void_p] +ctx = lib.seccomp_init(0x7FFF0000) # SCMP_ACT_ALLOW +if not ctx: + raise RuntimeError("Cannot initialize execution isolation") +try: + for name in ( + "socket", + "socketpair", + "connect", + "ptrace", + "process_vm_readv", + "process_vm_writev", + "mount", + "unshare", + "setns", + "bpf", + ): + number = lib.seccomp_syscall_resolve_name(name.encode()) + if ( + number >= 0 + and lib.seccomp_rule_add(ctx, 0x00050000 | errno.EPERM, number, 0) != 0 + ): + raise RuntimeError("Cannot install execution isolation rule") + if lib.seccomp_load(ctx) != 0: + raise RuntimeError("Cannot activate execution isolation") +finally: + lib.seccomp_release(ctx) + +sys.path.insert(0, "/app") +from simulator import ToolSimulator # noqa: E402 + +request = json.load(sys.stdin) +json.dump(ToolSimulator().code_py_exec(request), sys.stdout) diff --git a/tasks/agentescape-25-skeleton-ad399fad/environment/puzzle/export.py b/tasks/agentescape-25-skeleton-ad399fad/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-25-skeleton-ad399fad/environment/puzzle/export.py @@ -0,0 +1,13 @@ +"""Harbor invokes this inside the puzzle service after stopping the agent.""" + +import json +import pathlib +import urllib.request + +with urllib.request.urlopen("http://127.0.0.1:8000/state", timeout=10) as response: + state = json.load(response) +state["collected_from_live_service"] = True +target = pathlib.Path("/evidence/final.json") +temp = target.with_suffix(".tmp") +temp.write_text(json.dumps(state)) +temp.replace(target) diff --git a/tasks/agentescape-25-skeleton-ad399fad/environment/puzzle/requirements.txt b/tasks/agentescape-25-skeleton-ad399fad/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-25-skeleton-ad399fad/environment/puzzle/requirements.txt @@ -0,0 +1,57 @@ +annotated-doc==0.0.5 + # via fastapi +annotated-types==0.8.0 + # via pydantic +anyio==4.16.0 + # via starlette +certifi==2026.10.23 + # via requests +cffi==2.1.1 ; platform_python_implementation != 'PyPy' + # via cryptography +charset-normalizer==3.5.2 + # via requests +click==8.5.0 + # via uvicorn +cryptography==50.0.2 + # via agentescapebench-harbor +fastapi==0.162.0 + # via agentescapebench-harbor +h11==0.16.0 + # via uvicorn +idna==3.20 + # via + # anyio + # requests +opentelemetry-api==1.45.2 + # via fastapi +pycparser==3.12 ; implementation_name != 'PyPy' and platform_python_implementation != 'PyPy' + # via cffi +pydantic==2.14.2 + # via + # agentescapebench-harbor + # fastapi +pydantic-core==2.50.2 + # via pydantic +pytz==2025.2 + # via agentescapebench-harbor +requests==2.34.2 + # via agentescapebench-harbor +starlette==1.10.0 + # via fastapi +typing-extensions==4.16.0 + # via + # anyio + # fastapi + # opentelemetry-api + # pydantic + # pydantic-core + # starlette + # typing-inspection +typing-inspection==0.4.4 + # via + # fastapi + # pydantic +urllib3==2.8.0 + # via requests +uvicorn==0.54.0 + # via agentescapebench-harbor diff --git a/tasks/agentescape-25-skeleton-ad399fad/environment/puzzle/scenario.json b/tasks/agentescape-25-skeleton-ad399fad/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..6d90dba3a72244d687b0e5048af2679087185c3d --- /dev/null +++ b/tasks/agentescape-25-skeleton-ad399fad/environment/puzzle/scenario.json @@ -0,0 +1,1449 @@ +{ + "metadata": { + "total_nodes": 25, + "total_edges": 37, + "win_node_id": "hex_encode", + "win_condition": { + "type": "tool_output", + "node_id": "hex_encode", + "output_port": "hex", + "output_type": "Hex_String", + "description": "Execute Text to Hex Encoder and get the output from port 'hex'" + }, + "source_init": { + "source_nodes": [ + "calc_modexp", + "graph_shortest_path", + "calc_modexp_bd8a", + "calc_bigmul", + "terminal_1", + "calc_gcd", + "calc_inv_mod_1089", + "terminal_1_b192", + "calc_inv_mod_fa78", + "item_15", + "luhn_check" + ], + "by_node": { + "calc_modexp": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "base": { + "type": "Big_Int", + "description": "Base" + } + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "Graph JSON file ID" + }, + "dst": { + "type": "Text_Generic", + "description": "Destination node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "calc_modexp_bd8a": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "calc_bigmul": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First large integer" + }, + "b": { + "type": "Big_Int", + "description": "Second large integer" + } + }, + "init_outputs": {} + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": {}, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + } + } + }, + "calc_gcd": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "b": { + "type": "Big_Int", + "description": "Second integer" + } + }, + "init_outputs": {} + }, + "calc_inv_mod_1089": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "Integer a" + }, + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "terminal_1_b192": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": {}, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + } + } + }, + "calc_inv_mod_fa78": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "Integer a" + }, + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "item_15": { + "node_name": "", + "node_type": "Item", + "template_id": "item_15", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Text_Generic", + "description": "Timezone text" + } + } + }, + "luhn_check": { + "node_name": "Luhn Checker", + "node_type": "Tool", + "template_id": "luhn_check", + "init_inputs": { + "number": { + "type": "Text_Generic", + "description": "Number string" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "calc_modexp": { + "init_inputs": { + "base": "17" + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": { + "file_id": "network_graph.json", + "dst": "target_node_88" + }, + "init_outputs": { + "path": "[\"node_1\", \"node_2\", \"node_3\", \"node_4\", \"target_node_88\"]", + "cost": "345678" + } + }, + "calc_modexp_bd8a": { + "init_inputs": { + "mod": "456787" + }, + "init_outputs": {} + }, + "calc_bigmul": { + "init_inputs": { + "a": "47382910475839201928", + "b": "58392019485739201847" + }, + "init_outputs": {} + }, + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "Data successfully processed in terminal slot A.", + "hex_output": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + } + }, + "calc_gcd": { + "init_inputs": { + "b": "38475920193847583920" + }, + "init_outputs": {} + }, + "calc_inv_mod_1089": { + "init_inputs": { + "a": "83940582918374659201", + "mod": "876541" + }, + "init_outputs": {} + }, + "terminal_1_b192": { + "init_inputs": {}, + "init_outputs": { + "text_output": "Terminal B operational state confirmed and verified.", + "hex_output": "112233445566778899aabbccddeeff00" + } + }, + "calc_inv_mod_fa78": { + "init_inputs": { + "a": "49583029182746583920", + "mod": "100003" + }, + "init_outputs": {} + }, + "item_15": { + "init_inputs": {}, + "init_outputs": { + "content": "America/Los_Angeles" + } + }, + "luhn_check": { + "init_inputs": { + "number": "45327189394028" + }, + "init_outputs": {} + } + }, + "intro_narrative": "Welcome to the lost sanctum of Archmage Vaelen. For centuries, this floating tower has been hidden by powerful enchantments. As a seeker of arcane knowledge, you have breached the outer wards, but the true prize—a legendary spell scroll—remains sealed by a complex web of magical devices. The artifacts in this room are intertwined, their energies feeding into one another. You must explore the sanctum, master these archaic tools, and trace the flow of mana to unravel the grand puzzle. Your ultimate goal is to decipher the final incantation before the sanctum crumbles into the aether.", + "narrative_style": "fantasy" + }, + "nodes": [ + { + "id": "hex_encode", + "name": "Text to Hex Encoder", + "description": "Encode UTF-8 text to hex.", + "type": "Tool", + "template_id": "hex_encode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "\u0003rH" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Encoded hex", + "value": "037248" + } + ], + "narrative": "This is The Final Translation Scroll. It requires input from The Grand Archmage's Deciphering Orb to reveal the ultimate secret." + }, + { + "id": "crypto_rsa_decrypt_hex", + "name": "RSA Decrypt", + "description": "RSA decrypt (hex cipher) with n,d (decimal).", + "type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex_cipher", + "type": "Hex_String", + "description": "Ciphertext (Hex)", + "value": "112233445566778899aabbccddeeff00" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Modulus n", + "value": "283032" + }, + { + "name": "d", + "type": "Big_Int", + "description": "Private exponent d", + "value": "283032" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decrypted text", + "value": "\u0003rH" + } + ], + "narrative": "This is The Grand Archmage's Deciphering Orb. It requires inputs from The Altar of Reversal, The Enchanted Astrolabe, and The Oracle's Basin to break the ancient ciphers." + }, + { + "id": "calc_inv_mod", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "283032" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "36963" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "283032" + } + ], + "narrative": "This is The Altar of Reversal. It requires inputs from The Elemental Transmuter and The Enchanted Astrolabe to flip the magical polarity." + }, + { + "id": "calc_modexp", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "17" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "345678" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "370159" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "283032" + } + ], + "init": { + "inputs": { + "base": "17" + }, + "outputs": {} + }, + "narrative": "This is The Enchanted Astrolabe. It requires inputs from The Map of Ley Lines and The Obsidian Focusing Crystal to align the celestial forces." + }, + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "network_graph.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "America/Los_Angeles" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "target_node_88" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"node_1\", \"node_2\", \"node_3\", \"node_4\", \"target_node_88\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "345678" + } + ], + "init": { + "inputs": { + "file_id": "network_graph.json", + "dst": "target_node_88" + }, + "outputs": { + "path": "[\"node_1\", \"node_2\", \"node_3\", \"node_4\", \"target_node_88\"]", + "cost": "345678" + } + }, + "narrative": "This is The Map of Ley Lines. It requires input from The Star Parchment to chart the magical paths across the sanctum." + }, + { + "id": "num_base_convert", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "36963" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "10059" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "370159" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "36963" + } + ], + "narrative": "This is The Elemental Transmuter. It requires inputs from The Obsidian Focusing Crystal, The Mirror of Reflection, and The Stone of Inversion to shift the arcane states." + }, + { + "id": "calc_modexp_bd8a", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "72966" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "2766783831796238835646601554020183561016" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "456787" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "370159" + } + ], + "init": { + "inputs": { + "mod": "456787" + }, + "outputs": {} + }, + "narrative": "This is The Obsidian Focusing Crystal. It requires inputs from The Loom of Multiplication and The Forge of Amplification to concentrate raw mana." + }, + { + "id": "container_3", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_3", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Big_Int", + "description": "Fingerprint Hash", + "value": "72966" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is The Silver Reliquary. It requires input from The Forge of Amplification to unlock its magical seals." + }, + { + "id": "calc_inv_mod_148f", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "36963" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "43264" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "10059" + } + ], + "narrative": "This is The Mirror of Reflection. It requires inputs from The Celestial Orrery and The Stone of Inversion to reveal hidden truths." + }, + { + "id": "calc_bigmul", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "47382910475839201928" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "58392019485739201847" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "2766783831796238835646601554020183561016" + } + ], + "init": { + "inputs": { + "a": "47382910475839201928", + "b": "58392019485739201847" + }, + "outputs": {} + }, + "narrative": "An arcane loom that weaves numbers and spells together into much larger, intricate patterns." + }, + { + "id": "calc_modexp_3695", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "2766783831796238835646601554020183561016" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "2" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "283032" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "43264" + } + ], + "narrative": "This is The Celestial Orrery. It requires inputs from The Loom of Multiplication, The Enchanted Astrolabe, and The Scale of Balance to track the cosmic movements." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A mysterious rune stone vibrating with latent, ancient energy." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "false" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "72966" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Data successfully processed in terminal slot A." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "Data successfully processed in terminal slot A.", + "hex_output": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + } + }, + "narrative": "This is The Golem Control Pedestal. It requires inputs from The Forge of Amplification and The Truth Seeker's Eye to command the sanctum's guardians." + }, + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "345678" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "38475920193847583920" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "2" + } + ], + "init": { + "inputs": { + "b": "38475920193847583920" + }, + "outputs": {} + }, + "narrative": "This is The Scale of Balance. It requires input from The Map of Ley Lines to find the harmonic resonance between magics." + }, + { + "id": "calc_bigmul_a22e", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "2" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "36483" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "72966" + } + ], + "narrative": "This is The Forge of Amplification. It requires inputs from The Scale of Balance and The Shadow Pendulum to empower the elemental energies." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A delicate, humming amulet that seems to contain the essence of fractured time." + }, + { + "id": "calc_inv_mod_1089", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "83940582918374659201" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "876541" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "36963" + } + ], + "init": { + "inputs": { + "a": "83940582918374659201", + "mod": "876541" + }, + "outputs": {} + }, + "narrative": "An ancient stone engraved with paradoxical runes that seem to contradict themselves." + }, + { + "id": "terminal_1_b192", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "[\"node_1\", \"node_2\", \"node_3\", \"node_4\", \"target_node_88\"]" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "36963" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Terminal B operational state confirmed and verified." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "112233445566778899aabbccddeeff00" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "Terminal B operational state confirmed and verified.", + "hex_output": "112233445566778899aabbccddeeff00" + } + }, + "narrative": "This is The Oracle's Basin. It requires inputs from The Map of Ley Lines and The Stone of Inversion to project visions of the past." + }, + { + "id": "calc_inv_mod_fa78", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "49583029182746583920" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "100003" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "36483" + } + ], + "init": { + "inputs": { + "a": "49583029182746583920", + "mod": "100003" + }, + "outputs": {} + }, + "narrative": "A mystical pendulum swinging in a rhythm that defies the natural laws of motion." + }, + { + "id": "container_3_d78b", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_3", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Big_Int", + "description": "Fingerprint Hash", + "value": "2766783831796238835646601554020183561016" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is The Golden Chalice. It requires input from The Loom of Multiplication to break its warding spell." + }, + { + "id": "item_8_5a2c", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A dark gem that constantly whispers forgotten names and forbidden spells." + }, + { + "id": "item_15", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_15", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Text_Generic", + "description": "Timezone text", + "value": "America/Los_Angeles" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "America/Los_Angeles" + } + }, + "narrative": "An illuminated parchment depicting the night sky as it appeared ten thousand years ago." + }, + { + "id": "luhn_check", + "name": "Luhn Checker", + "description": "Luhn validity of number string.", + "type": "Tool", + "template_id": "luhn_check", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "number", + "type": "Text_Generic", + "description": "Number string", + "value": "45327189394028" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "false" + } + ], + "init": { + "inputs": { + "number": "45327189394028" + }, + "outputs": {} + }, + "narrative": "A magical eye artifact designed to distinguish true cosmic constants from illusions and falsehoods." + }, + { + "id": "item_8_fb5f", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A permanently frozen shard of magical ice that chills the air around it." + }, + { + "id": "item_8_f626", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A burning shard of volcanic glass that emits a perpetual, warming glow." + } + ], + "edges": [ + { + "source_id": "crypto_rsa_decrypt_hex", + "target_id": "hex_encode", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "text" + }, + { + "source_id": "calc_inv_mod", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "n" + }, + { + "source_id": "calc_modexp", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "d" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "exp" + }, + { + "source_id": "num_base_convert", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "mod" + }, + { + "source_id": "calc_modexp_bd8a", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "to_base" + }, + { + "source_id": "calc_modexp", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "a" + }, + { + "source_id": "calc_modexp_bd8a", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "mod" + }, + { + "source_id": "container_3", + "target_id": "calc_inv_mod", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "calc_inv_mod_148f", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "from_base" + }, + { + "source_id": "calc_bigmul", + "target_id": "calc_modexp_bd8a", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "exp" + }, + { + "source_id": "calc_modexp_3695", + "target_id": "calc_inv_mod_148f", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "mod" + }, + { + "source_id": "item_8", + "target_id": "container_3", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "calc_bigmul", + "target_id": "calc_modexp_3695", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "base" + }, + { + "source_id": "calc_modexp", + "target_id": "calc_modexp_3695", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "mod" + }, + { + "source_id": "terminal_1", + "target_id": "calc_bigmul", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "trigger_item" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_modexp_3695", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "exp" + }, + { + "source_id": "calc_bigmul_a22e", + "target_id": "container_3", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "fingerprint_input" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "a" + }, + { + "source_id": "calc_bigmul_a22e", + "target_id": "calc_modexp_bd8a", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "base" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_bigmul_a22e", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "a" + }, + { + "source_id": "calc_bigmul_a22e", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "slot_b" + }, + { + "source_id": "item_16", + "target_id": "calc_bigmul_a22e", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "calc_inv_mod_1089", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "s" + }, + { + "source_id": "terminal_1_b192", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "source_tool" + }, + { + "source_id": "graph_shortest_path", + "target_id": "terminal_1_b192", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "slot_a" + }, + { + "source_id": "calc_inv_mod_fa78", + "target_id": "calc_bigmul_a22e", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "b" + }, + { + "source_id": "container_3_d78b", + "target_id": "calc_modexp_bd8a", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "calc_bigmul", + "target_id": "container_3_d78b", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "fingerprint_input" + }, + { + "source_id": "item_8_5a2c", + "target_id": "calc_inv_mod_fa78", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "item_15", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "content", + "target_port": "src" + }, + { + "source_id": "luhn_check", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "slot_a" + }, + { + "source_id": "calc_inv_mod_1089", + "target_id": "terminal_1_b192", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "slot_b" + }, + { + "source_id": "terminal_1_b192", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Hex_String", + "source_port": "hex_output", + "target_port": "hex_cipher" + }, + { + "source_id": "calc_inv_mod_1089", + "target_id": "calc_inv_mod_148f", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "a" + }, + { + "source_id": "item_8_fb5f", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_8_f626", + "target_id": "container_3_d78b", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-ad399fad/environment/puzzle/service.py b/tasks/agentescape-25-skeleton-ad399fad/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-25-skeleton-ad399fad/environment/puzzle/service.py @@ -0,0 +1,212 @@ +"""Restricted facade over the unchanged, pinned upstream puzzle handlers.""" + +import hashlib +import json +import logging +import os +import sys +import threading +import urllib.request +import uuid +from pathlib import Path + +from fastapi import FastAPI, HTTPException +from fastapi.responses import JSONResponse +from pydantic import BaseModel, ConfigDict + +sys.path.insert(0, str(Path(__file__).parent / "upstream")) +import server as upstream # noqa: E402 + +log = logging.getLogger(__name__) + + +def public(value): + """Keep upstream agent-internal template hints out of the public response.""" + if isinstance(value, dict): + return {k: public(v) for k, v in value.items() if not k.startswith("_")} + if isinstance(value, list): + return [public(v) for v in value] + return value + + +class Action(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + action: str + node_id: str | None = None + arguments: dict | None = None + answer: str | None = None + + +class Episode: + def __init__( + self, scenario_path, max_actions=500, evidence_dir=None, worker_url=None + ): + if max_actions < 1: + raise ValueError("max_actions must be positive") + self.lock = threading.Lock() + self.max_actions = max_actions + self.count = 0 + self.won = False + self.reason = None + self.evidence_dir = Path(evidence_dir) if evidence_dir else None + self.scenario_hash = hashlib.sha256( + Path(scenario_path).read_bytes() + ).hexdigest() + self.initial = upstream.reset_case( + case_file_path=str(scenario_path), session_id=uuid.uuid4().hex + ) + self.case_id = self.initial["case_id"] + # Hide source file paths; no upstream reset/stats/routes are mounted. + self.initial.pop("message", None) + simulator = upstream.SIMULATORS[self.case_id] + if worker_url is None: + + def no_worker(_inputs): + self.reason = "infrastructure_error" + raise RuntimeError("isolated Python worker is not configured") + + simulator.tool_map["code_py_exec"] = no_worker + else: + + def execute_python(inputs): + request = urllib.request.Request( + worker_url + "/execute", + data=json.dumps({"code": inputs.get("code", "")}).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=12) as response: + result = json.load(response) + if not isinstance(result.get("stdout"), str): + raise RuntimeError("Invalid Python worker response") + return result + except Exception: + self.reason = "infrastructure_error" + raise + + simulator.tool_map["code_py_exec"] = execute_python + self.save() + if self.evidence_dir is not None: + (self.evidence_dir / "trace.jsonl").touch() + + def state(self): + return { + "scenario_sha256": self.scenario_hash, + "action_count": self.count, + "max_actions": self.max_actions, + "won": self.won, + "termination_reason": self.reason, + } + + def save(self, action=None, result=None): + if self.evidence_dir is None: + return + self.evidence_dir.mkdir(parents=True, exist_ok=True) + target = self.evidence_dir / "outcome.json" + temp = target.with_suffix(".tmp") + temp.write_text(json.dumps(self.state())) + temp.replace(target) + if action is not None: + with (self.evidence_dir / "trace.jsonl").open("a") as handle: + handle.write( + json.dumps( + {"index": self.count, "action": action, "result": result} + ) + + "\n" + ) + + def dispatch(self, payload): + with self.lock: + if self.reason is not None: + return { + "ok": False, + "error": "Episode has ended", + "episode": self.state(), + } + self.count += 1 + try: + action = Action.model_validate(payload) + if action.action == "submit_answer" and action.answer is not None: + result = upstream.submit_answer( + self.case_id, upstream.SubmitAnswerRequest(answer=action.answer) + ) + if result.get("is_win"): + self.won = True + self.reason = "success" + elif action.action == "investigate" and action.node_id is not None: + result = upstream.investigate( + self.case_id, + upstream.InvestigateRequest(node_id=action.node_id), + ) + elif ( + action.action in ("tool_call", "use_item") + and action.node_id is not None + ): + request_type, handler = ( + (upstream.ToolCallRequest, upstream.tool_call) + if action.action == "tool_call" + else (upstream.UseItemRequest, upstream.use_item) + ) + result = handler( + self.case_id, + request_type( + node_id=action.node_id, arguments=action.arguments or {} + ), + ) + else: + result = { + "ok": False, + "error": "Unknown action or missing action parameter", + } + except HTTPException as exc: + result = {"ok": False, "error": exc.detail} + except ValueError: + result = {"ok": False, "error": "Malformed action"} + except Exception: + log.exception("Puzzle service failure") + self.reason = "infrastructure_error" + self.save() + raise + if self.reason is None and self.count >= self.max_actions: + self.reason = "action_budget_exhausted" + result = public(result) + result["episode"] = self.state() + self.save(payload, result) + return result + + +def create_app( + scenario_path=None, max_actions=None, evidence_dir=None, worker_url=None +): + episode = Episode( + scenario_path or os.environ["SCENARIO_PATH"], + max_actions or int(os.environ.get("MAX_ACTIONS", "500")), + evidence_dir if evidence_dir is not None else os.environ.get("EVIDENCE_DIR"), + worker_url if worker_url is not None else os.environ.get("WORKER_URL"), + ) + app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) + app.state.episode = episode + + @app.get("/health") + def health(): + return {"ok": True} + + @app.get("/observation") + def observation(): + return {**public(episode.initial), "episode": episode.state()} + + @app.get("/state") + def state(): + return episode.state() + + @app.post("/action") + def action(payload: dict): + try: + return episode.dispatch(payload) + except Exception: + return JSONResponse( + status_code=503, + content={"ok": False, "error": "Puzzle infrastructure failure"}, + ) + + return app diff --git a/tasks/agentescape-25-skeleton-ad399fad/environment/puzzle/upstream/models.py b/tasks/agentescape-25-skeleton-ad399fad/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-25-skeleton-ad399fad/environment/puzzle/upstream/models.py @@ -0,0 +1,108 @@ +from enum import Enum +from typing import List, Dict, Any, Optional +from pydantic import BaseModel, Field + +# 1. 细粒度接口类型定义 +class InterfaceType(str, Enum): + ''' + BIG_INT + TEXT_GENERIC + HEX_STRING + FILE_ID + HEX_STRING_KEY_AES + HEX_STRING_IV_AES + CODE_PYTHON + HIDDEN_ITEM + ITEM + ''' + # --- 基础类型 --- + TEXT_GENERIC = "Text_Generic" + BIG_INT = "Big_Int" + + # --- 编码/格式化字符串 --- + HEX_STRING = "Hex_String" # 通用 Hex + + # --- 特定用途的 Hex 字符串 (用于精确匹配) --- + HEX_STRING_KEY_AES = "Hex_String_Key_AES" + HEX_STRING_IV_AES = "Hex_String_IV_AES" + + # --- 文件类型 --- + FILE_ID = "File_Id" + + # --- 代码/脚本 --- + CODE_PYTHON = "Code_Python" + + # --- 实体交互类型 (严格命名) --- + ITEM = "Item" # 主动掉落接口 (Tool -> Item) + HIDDEN_ITEM = "Hidden_Item" # 被动掉落接口 (Item -> Item) + +# 3. 端口定义 +class Port(BaseModel): + name: str + type: InterfaceType + description: str + +# 4. 统一节点定义 (融合工具和物品) +class Node(BaseModel): + id: str + name: str + description: str + type: str # "Tool" or "Item" + + # 接口定义 + inputs: List[Port] = [] + outputs: List[Port] = [] + + # 状态字段 + content: Optional[Any] = None # 物品有内容,工具为None + if_success: Optional[bool] = None # 工具初始为False,物品为None + initial_visible: bool = False + + # 运行时状态 (Server维护) + is_revealed: bool = False + + # 标记该 Tool 节点是否有待触发的 HIDDEN_ITEM 掉落 + # 当 Tool 按照 golden_input 正确执行且有 HIDDEN_ITEM 输出边时设为 True + # 在 investigate 该 Tool 时触发掉落并重置为 False + has_hidden_item_ready: bool = False + + # 初始输入值 (metadata.initial_values.init_inputs,用于渐进式暴露判断) + init_input_values: Dict[str, Any] = {} + + # Golden 输入值 (nodes[].inputs[].value,用于评测验证) + golden_input_values: Dict[str, Any] = {} + + # Golden 输出值 (nodes[].outputs[].value,用于评测验证和 Item 节点的 content) + golden_output_values: Dict[str, Any] = {} + + # 实际获得的输出值历史 (工具每次执行后实际返回的输出列表,用于渐进式暴露判断) + # 格式: List[Dict[str, Any]],每个元素是一次执行的输出字典 + actual_outputs_history: List[Dict[str, Any]] = [] + + # 逻辑规则 (用于终端机等复杂物品) + logic_rules: Optional[Dict[str, Any]] = None + + def copy(self, **kwargs): + """Helper to create a copy with updated fields.""" + data = self.dict() + data.update(kwargs) + return Node(**data) + +# 5. 边定义 (拓扑结构) +class Edge(BaseModel): + source_id: str + target_id: str + connection_type: InterfaceType # 直接使用 InterfaceType + # 如果是 Data_Flow,指定端口对应关系 + source_port: Optional[str] = None + target_port: Optional[str] = None + +# 6. 完整图定义 +class GraphScenario(BaseModel): + case_id: str + title: str + intro_narrative: str + nodes: Dict[str, Node] + edges: List[Edge] + difficulty: int + win_node_id: str # 标记哪个节点是最终目标(通常是一个提交工具或最终物品) diff --git a/tasks/agentescape-25-skeleton-ad399fad/environment/puzzle/upstream/server.py b/tasks/agentescape-25-skeleton-ad399fad/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-25-skeleton-ad399fad/environment/puzzle/upstream/server.py @@ -0,0 +1,1490 @@ +import json +import os +import time +import logging +import random +from pathlib import Path +from typing import Dict, Any, List, Optional +from datetime import datetime +from collections import defaultdict +from fastapi import FastAPI, HTTPException, Request +from fastapi.responses import JSONResponse +from fastapi.middleware.cors import CORSMiddleware +from pydantic import BaseModel, Field + +from models import GraphScenario, Node, InterfaceType +# from generator import ScenarioGenerator +from simulator import ToolSimulator +import uvicorn + +# 配置日志 +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler('server.log'), + logging.StreamHandler() + ] +) +logger = logging.getLogger(__name__) + +app = FastAPI( + title="AgentEscapeBench Universal Server", + version="1.0.0", + description="Industrial-grade evaluation server for escape room AI agents" +) + +# 添加 CORS 支持 +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# In-memory State +SCENARIOS: Dict[str, GraphScenario] = {} +SIMULATORS: Dict[str, ToolSimulator] = {} # case_id -> ToolSimulator +RAW_NODES_DATA: Dict[str, Dict[str, Any]] = {} # case_id -> node_id -> raw node data (for template_id) +FILE_METADATA: Dict[str, Dict[str, Any]] = {} # case_id -> metadata (for initial_values access) + +# Performance monitoring +STATS: Dict[str, Any] = { + "total_requests": 0, + "successful_requests": 0, + "failed_requests": 0, + "tool_calls": defaultdict(int), + "investigates": defaultdict(int), + "use_items": defaultdict(int), + "case_loads": 0, + "start_time": datetime.now() +} + +# Request timing middleware +@app.middleware("http") +async def add_process_time_header(request: Request, call_next): + start_time = time.time() + STATS["total_requests"] += 1 + + try: + response = await call_next(request) + STATS["successful_requests"] += 1 + process_time = time.time() - start_time + response.headers["X-Process-Time"] = str(process_time) + logger.info(f"{request.method} {request.url.path} - {response.status_code} - {process_time:.3f}s") + return response + except Exception as e: + STATS["failed_requests"] += 1 + logger.error(f"{request.method} {request.url.path} - Error: {str(e)}") + raise + +# Exception handler +@app.exception_handler(Exception) +async def global_exception_handler(request: Request, exc: Exception): + logger.error(f"Unhandled exception: {exc}", exc_info=True) + return JSONResponse( + status_code=500, + content={ + "ok": False, + "error": "Internal server error", + "detail": str(exc) if os.getenv("DEBUG") else "An error occurred" + } + ) + +# Health check endpoint +@app.get("/health") +def health_check(): + """健康检查端点""" + uptime = (datetime.now() - STATS["start_time"]).total_seconds() + return { + "status": "healthy", + "version": "1.0.0", + "uptime_seconds": uptime, + "loaded_cases": len(SCENARIOS), + "stats": { + "total_requests": STATS["total_requests"], + "successful_requests": STATS["successful_requests"], + "failed_requests": STATS["failed_requests"], + "success_rate": STATS["successful_requests"] / max(STATS["total_requests"], 1) + } + } + +# Statistics endpoint +@app.get("/stats") +def get_stats(): + """获取详细统计信息""" + return { + "stats": STATS, + "loaded_cases": list(SCENARIOS.keys()), + "uptime": str(datetime.now() - STATS["start_time"]) + } + +def _apply_progressive_reveal_at_init(scenario: GraphScenario): + """ + 在初始化时应用渐进式暴露机制(基于ITEM/HIDDEN_ITEM边) + + 新逻辑: + - 如果一个节点没有 ITEM/HIDDEN_ITEM 类型的入边,它就是初始可见的 + - 如果一个节点有 ITEM/HIDDEN_ITEM 类型的入边,它初始不可见,需要等待上游触发 + + Args: + scenario: 场景对象 + """ + # 收集所有有 ITEM/HIDDEN_ITEM 入边的节点 + nodes_with_item_edges = set() + for edge in scenario.edges: + if edge.connection_type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + nodes_with_item_edges.add(edge.target_id) + + logger.info(f"Nodes with ITEM/HIDDEN_ITEM incoming edges: {nodes_with_item_edges}") + + # 设置初始可见性:没有 ITEM/HIDDEN_ITEM 入边的节点初始可见 + initially_visible_count = 0 + for node_id, node in scenario.nodes.items(): + if node_id not in nodes_with_item_edges: + node.is_revealed = True + initially_visible_count += 1 + logger.info(f"Initial visible (no ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + else: + node.is_revealed = False + logger.debug(f"Initial hidden (has ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + + logger.info(f"Progressive reveal initialized: {initially_visible_count}/{len(scenario.nodes)} nodes initially visible") + + +def _check_inputs_match_golden(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> bool: + """ + 检查实际输入参数是否与 golden inputs 完全匹配 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + True 表示所有 golden inputs 都存在且值匹配 + """ + if not golden_inputs: + return True # 如果没有 golden inputs,认为匹配 + + for key, expected_value in golden_inputs.items(): + actual_value = arguments.get(key) + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) != str(expected_value): + logger.debug(f"Input mismatch for '{key}': expected '{expected_value}', got '{actual_value}'") + return False + + return True + + +def _get_parameter_validation_feedback(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> Dict[str, Any]: + """ + 对源头节点的参数进行详细验证,返回验证反馈 + + 注意:不返回期望值(expected),避免泄漏答案 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + 包含验证结果的字典: + - all_correct: bool - 所有参数是否正确 + - correct_params: List[str] - 正确的参数名列表 + - incorrect_params: List[str] - 错误的参数名列表(不包含期望值) + """ + if not golden_inputs: + return { + "all_correct": True, + "correct_params": [], + "incorrect_params": [] + } + + correct_params = [] + incorrect_params = [] + + for key, actual_value in arguments.items(): + # 只对用户实际提交的参数给反馈,未提交的参数不评价 + if key not in golden_inputs: + continue # 该参数不在 golden 中,跳过(如 _golden_inputs 等内部参数) + expected_value = golden_inputs[key] + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) == str(expected_value): + correct_params.append(key) + else: + # 只记录参数名,不包含期望值,避免泄漏答案 + incorrect_params.append(key) + + # all_correct:用户提交的所有参数都正确,且覆盖了全部 golden 参数 + all_provided_correct = len(incorrect_params) == 0 + all_golden_covered = all(k in arguments for k in golden_inputs) + return { + "all_correct": all_provided_correct and all_golden_covered, + "correct_params": correct_params, + "incorrect_params": incorrect_params + } + + +def _is_source_node(node_id: str, scenario: GraphScenario) -> bool: + """ + 判断节点是否是源头节点(完全没有任何入边的节点) + + 源头节点定义: + - 没有任何类型的入边(包括 DATA、ITEM、HIDDEN_ITEM) + - 即没有任何上游节点 + + Args: + node_id: 节点ID + scenario: 场景对象 + + Returns: + True 表示是源头节点 + """ + for edge in scenario.edges: + if edge.target_id == node_id: + # 只要有任何入边,就不是源头节点 + return False + + return True + + +def _check_and_reveal_ready_nodes(scenario: GraphScenario, recent_outputs: Dict[str, Any], source_node_id: str) -> List[Dict[str, Any]]: + """ + 检查并释放参数齐全的隐藏节点(渐进式暴露机制) + + 核心逻辑: + 1. 维护"可见值集合":包含所有被测模型当前可以看到的值 + - init_inputs 的值(初始可见) + - 工具执行后的实际输出值(运行时获得) + - 可见 Item 的输出值 + 2. 检查隐藏节点:该节点的所有 golden_input 值是否都在可见值集合中 + 3. 如果是,则释放该节点 + + Args: + scenario: 场景对象 + recent_outputs: 最近执行的工具的输出 + source_node_id: 刚执行的工具节点ID + + Returns: + 新释放的节点列表 + """ + newly_revealed = [] + + # 构建"可见值集合"(Set of visible values) + # 存储格式:set of values (转为字符串) + visible_values = set() + + # 1. 添加有意义的 init_inputs 值到可见值集合 + # Item 的 init_inputs 不应该加入,因为它们在密室中完全用不到 + for node_id, node in scenario.nodes.items(): + # 跳过源头 Item 节点(没有入边的 Item) + if node.type == "Item": + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,跳过其 init_inputs + continue + + # 添加其他节点的 init_inputs + for port_name, init_value in node.init_input_values.items(): + if init_value: + visible_values.add(str(init_value)) + + # 2. 添加已执行工具的所有历史输出值 + for node_id, node in scenario.nodes.items(): + if node.type == "Tool" and node.if_success and node.actual_outputs_history: + # 遍历所有历史执行记录 + for output_dict in node.actual_outputs_history: + for output_port_name, output_value in output_dict.items(): + if output_value: + visible_values.add(str(output_value)) + + # 3. 添加已被 investigate 的 Item 的 golden 输出值 + # 注意:Item 可见不等于其输出值可见,需要 investigate 后才能获得 + # 这里我们使用 actual_outputs_history 来标记 Item 是否已被 investigate + for node_id, node in scenario.nodes.items(): + if node.type == "Item" and node.is_revealed and node.actual_outputs_history: + # Item 通常只会被 investigate 一次,但为了一致性也使用历史列表 + for output_dict in node.actual_outputs_history: + for port_name, port_value in output_dict.items(): + if port_value: + visible_values.add(str(port_value)) + + # 遍历所有隐藏的节点,检查其 golden_input 是否都在可见值集合中 + for node_id, node in scenario.nodes.items(): + # 跳过已可见的节点 + if node.is_revealed: + continue + + # 只检查工具节点(物品节点由 ITEM 输出触发) + if node.type != "Tool": + continue + + # 检查该节点的所有 golden_input 值是否都在可见值集合中 + all_inputs_ready = True + missing_values = [] + + for input_port_name, golden_input_value in node.golden_input_values.items(): + # 检查这个 golden 值是否在可见值集合中 + if str(golden_input_value) not in visible_values: + all_inputs_ready = False + missing_values.append(f"{input_port_name}={golden_input_value}") + + # 如果所有 golden_input 值都在可见值集合中,释放该节点 + if all_inputs_ready and len(node.golden_input_values) > 0: + logger.info(f"All golden inputs ready for {node_id}: {list(node.golden_input_values.values())}") + + # 如果所有输入都齐全,释放该节点 + if all_inputs_ready: + node.is_revealed = True + + # 构建节点信息返回给模型 + node_info = { + "id": node.id, + "type": node.type, + "can_investigate": True, + "hint": "This tool's input parameters are now complete, you can use investigate to view detailed information" + } + + # if node.name: + # node_info["name"] = node.name + if node.description: + node_info["description"] = node.description + + newly_revealed.append(node_info) + logger.info(f"Progressive reveal: {node_id} is now ready (all inputs satisfied)") + + return newly_revealed + + +def _initialize_node_values(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]): + """ + Initialize node state and load values from port value fields. + 应用渐进式暴露机制:初始时只显示参数齐全的节点(源头节点) + + 重要区分: + 1. input_values: 只加载 metadata.initial_values 中的 init_inputs(真正的初始值) + 2. output_values: 加载 nodes[].outputs[].value(golden 输出,用于验证) + """ + # 第一步:加载所有节点的值,并将所有节点初始设为隐藏 + initial_values = metadata.get('initial_values', {}) + + for node_id, node in scenario.nodes.items(): + # 忽略 initial_visible 字段,初始全部隐藏 + # 由渐进式暴露机制根据参数齐全情况决定是否显示 + node.is_revealed = False + + if node.type == "Tool": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + elif node.type == "Item": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + + # 从 JSON 加载值 + if node_id in raw_nodes_data: + node_data = raw_nodes_data[node_id] # node_data是json文件中nodes中的字典 + + # 【重要】只加载 metadata.initial_values 中的初始输入值 + if node_id in initial_values: + init_data = initial_values[node_id] + # 加载初始输入值(用于渐进式暴露判断) + for port_name, port_value in init_data.get('init_inputs', {}).items(): + node.init_input_values[port_name] = port_value + + # 【评测用】加载 golden 输入值(用于验证模型传入的参数是否正确) + for input_port_data in node_data.get('inputs', []): + if 'value' in input_port_data: + node.golden_input_values[input_port_data['name']] = input_port_data['value'] + + # 【评测用】加载 golden 输出值(用于验证工具调用是否正确,以及 Item 节点的 content) + for output_port_data in node_data.get('outputs', []): + if 'value' in output_port_data: + node.golden_output_values[output_port_data['name']] = output_port_data['value'] + + # For Items, set content from golden_output_values + if node.type == "Item" and node.golden_output_values: + # Item 的 content 是其第一个 golden 输出值 + node.content = list(node.golden_output_values.values())[0] + + # 第二步:应用渐进式暴露机制 + # 检查所有节点,根据参数齐全情况释放源头节点(工具 + Item) + _apply_progressive_reveal_at_init(scenario) + +def _build_node_info(node: Node, raw_nodes_data: Dict[str, Any]) -> Dict[str, Any]: + """ + 构建节点信息(工具或物品) + + Args: + node: 节点对象 + raw_nodes_data: 原始节点数据(用于获取 template_id 等) + + Returns: + 节点信息字典 + """ + if node.type == "Tool": + # 过滤掉输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口) + # 这些端口仅用于控制掉落机制,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + tool_info = { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Tool", + "inputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.inputs if p.type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]], + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id(工具的标准名称) + if node.id in raw_nodes_data: + node_data = raw_nodes_data[node.id] + template_id = node_data.get('template_id') + if template_id: + tool_info['template_id'] = template_id + + return tool_info + + elif node.type == "Item": + return { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Item" + } + + else: + return { + "id": node.id, + # "name": node.name, + "type": node.type + } + +def _get_initial_observation(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]) -> Dict[str, Any]: + """ + Generate initial observation for the agent (what they see when entering the room). + + 策略: + - Tools: 只显示名称和描述,不显示接口定义。需要 investigate 才能获得详细接口信息。 + - Items: 只显示存在,不显示内容。需要 investigate 才能获得内容值。 + - init_inputs: 作为"可用信息"告诉模型,这些是可以用作工具参数的初始值。 + - init_outputs: 不告诉模型(这些是答案,需要模型通过调用工具获得)。 + """ + available_entities = [] # 统一的实体列表(Tools 和 Items) + available_information = [] # 可用的初始信息(来自 init_inputs) + + # 从 metadata.initial_values 提取 init_inputs 作为可用信息 + # 只提供值本身,不透露这些值对应哪个节点的哪个参数,让模型自己推理 + # 注意:跳过源头 Item(没有入边的 Item)的 init_inputs,因为它们在密室中完全用不到 + initial_values = metadata.get('initial_values', {}) + # initial_values字段的格式 + # "initial_values": { + # "terminal_1": { + # "init_inputs": {}, + # "init_outputs": { + # "text_output": "System initialization complete.", + # "hex_output": "48656c6c6f20576f726c64", + # "item_dispenser": "掉落了一张纸条,上面写着“请勿随意触摸终端”" + # } + # } + # } + for node_id, init_data in initial_values.items(): + # 获取节点信息,判断是否为源头 Item + node = scenario.nodes.get(node_id) + if node and node.type == "Item": + # 检查是否为源头 Item(没有入边) + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,检查是否有 init_inputs + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 有 init_inputs,需要暴露这些参数 + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + # 处理完后跳过后续的通用逻辑 + continue + + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 为每个 init_input 值创建一个信息条目(不包含 source_node 和 parameter 信息) + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + + for node in scenario.nodes.values(): + if node.is_revealed: + # Tools: 只显示基本信息,提示可以 investigate 查看详细接口 + if node.type == "Tool": + tool_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Tool", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the tool's detailed interface information for calling" + } + # 只在 name 非空时添加 + # if node.name: + # tool_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_info["description"] = node.description + + available_entities.append(tool_info) + + # Items: 只显示基本信息,提示可以 investigate 查看内容 + elif node.type == "Item": + item_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Item", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the item's content" + } + # 只在 name 非空时添加 + # if node.name: + # item_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + item_info["description"] = node.description + + available_entities.append(item_info) + + return { + "narrative": scenario.intro_narrative, + "available_entities": available_entities, # 使用统一的实体列表 + "available_information": available_information, # 可用的初始信息(只包含 init_inputs) + "win_node_id": scenario.win_node_id # 胜利节点ID,让模型知道需要关注哪个节点 + } + +@app.post("/env/reset") +def reset_case(case_id: str = None, case_file_path: str = None, session_id: str = None): + """Loads a specific case from file and resets it. + + Args: + case_id: Optional case ID for resetting an existing case + case_file_path: Path to case file for loading a new case + session_id: Optional session ID to ensure isolation between concurrent evaluations + """ + logger.info(f"Reset request - case_id: {case_id}, case_file_path: {case_file_path}, session_id: {session_id}") + STATS["case_loads"] += 1 + + if case_file_path: + if not os.path.exists(case_file_path): + logger.error(f"Case file not found: {case_file_path}") + raise HTTPException(status_code=404, detail=f"File not found: {case_file_path}") + try: + with open(case_file_path, "r", encoding="utf-8") as f: + file_data = json.load(f) + + # 转换格式:从 DAG executor 生成的格式转换为 GraphScenario 格式 + # 1. 提取 metadata + metadata = file_data.get('metadata', {}) + + # 2. 生成 case_id, title, intro_narrative + # 【修复】为每个评测会话生成唯一的 case_id,防止并发评测时状态污染 + base_name = os.path.basename(case_file_path).replace('.json', '').replace('_full', '').replace('_full2', '') + + if session_id: + # 如果提供了 session_id,使用它来确保唯一性 + case_id = f"{base_name}_{session_id}" + else: + # 否则使用时间戳和随机数确保唯一性 + unique_suffix = f"{int(time.time() * 1000)}_{random.randint(1000, 9999)}" + case_id = f"{base_name}_{unique_suffix}" + + file_data['case_id'] = case_id + logger.info(f"Generated unique case_id: {case_id} (base: {base_name}, session: {session_id})") + + if 'title' not in file_data: + file_data['title'] = f"Escape Room: {file_data['case_id']}" + + if 'intro_narrative' not in file_data: # 目前的json文件中已经有了intro_narrative字段,不会使用下面一行的内容,而是使用每个评测问题的json文件中的对应字段 + 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]".' + + # 3. 转换 nodes 列表为字典(DAG executor 生成的文件中 nodes 是列表格式) + nodes_dict = {} + for node_data in file_data['nodes']: + nodes_dict[node_data['id']] = node_data # 这里的id是template_id之后可能添加一个后缀 + file_data['nodes'] = nodes_dict # 把列表转成一个字典 + + # 4. 添加缺失的字段 + if 'difficulty' not in file_data: + file_data['difficulty'] = metadata.get('total_nodes', 5) + + if 'win_node_id' not in file_data: + file_data['win_node_id'] = metadata.get('win_node_id', '') + + scenario = GraphScenario(**file_data) + + # Extract raw nodes data for template_id access + # nodes 已经在上面转换为字典格式 + raw_nodes_data = file_data.get('nodes', {}) + RAW_NODES_DATA[scenario.case_id] = raw_nodes_data + + # Store metadata for initial values access + FILE_METADATA[scenario.case_id] = metadata + + logger.info(f"Successfully parsed case file: {scenario.case_id}, nodes: {len(scenario.nodes)}, edges: {len(scenario.edges)}") + except Exception as e: + logger.error(f"Failed to load case file: {str(e)}", exc_info=True) + raise HTTPException(status_code=500, detail=f"Failed to load case file: {str(e)}") + + # Initialize node state and load values + _initialize_node_values(scenario, raw_nodes_data, metadata) + + SCENARIOS[scenario.case_id] = scenario + simulator = ToolSimulator() + SIMULATORS[scenario.case_id] = simulator + + 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'])}") + + # 生成初始观察信息(进入密室后看到的环境) + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + ''' + initial_observation的格式: + { + "narrative": scenario.intro_narrative, + "available_entities": available_entities # 使用统一的实体列表 + "available_information": available_information # 可用的初始信息(只包含 init_inputs) + } + ''' + + return { + "ok": True, + "message": f"Case loaded from {case_file_path}", + "case_id": scenario.case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果没有提供 case_file_path,但提供了 case_id,则尝试从内存重置 + if case_id and case_id in SCENARIOS: + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + metadata = FILE_METADATA.get(case_id, {}) + + # Reset dynamic fields and re-apply progressive reveal + # 重新初始化节点状态(包括渐进式暴露) + _initialize_node_values(scenario, raw_nodes_data, metadata) + + 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'])}") + + # 生成初始观察信息 + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + + return { + "ok": True, + "message": f"Case {case_id} reset.", + "case_id": case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果既没有 case_file_path,也没有在内存中找到,返回错误 + raise HTTPException( + status_code=400, + detail="Must provide case_file_path to load a new case, or use case_id to reset an existing case." + ) + +class InvestigateRequest(BaseModel): + node_id: str + +@app.post("/env/{case_id}/investigate") +def investigate(case_id: str, req: InvestigateRequest): + """ + Investigates a Tool or Item to reveal detailed information. + + - For Tools: Returns detailed interface information (inputs/outputs) needed to call the tool + - For Items: Returns content value and triggers hidden item drops + """ + logger.info(f"Investigate request - case_id: {case_id}, node_id: {req.node_id}") + STATS["investigates"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + node = scenario.nodes[req.node_id] + + if not node.is_revealed: + logger.warning(f"Attempt to investigate hidden node: {req.node_id}") + return {"ok": False, "error": "Node is not visible yet."} + + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + newly_revealed = [] + + # 处理 Tool 的 investigate + if node.type == "Tool": + logger.info(f"Investigating tool: {req.node_id}") + + # 返回工具的详细接口信息 + # id 字段使用 node.id(节点唯一标识),agent 用这个字段识别和调用具体的节点 + # template_id 是工具类型标识符,Agent 内部用于判断工具特性(如 terminal 类工具参数可选) + # 注意:只过滤输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口),这些端口仅用于控制掉落,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + # 【端口上游依赖提示 & 初始值直接给出】 + # 针对参数语义模糊(全为数字类型)的工具,在 investigate 返回信息中标注 + # 哪个输入端口来自哪个上游节点(upstream_from)。 + # 对于所有工具:若该节点不是纯源头节点(有任意数据流入边), + # 且某个端口没有上游入边(值来自初始可见参数),则直接给出该端口的 golden input 值。 + AMBIGUOUS_TOOLS = { + "num_base_convert", "calc_modexp", "calc_modexp_int", + "calc_inv_mod", "calc_inv_mod_int", "crypto_rsa_decrypt_hex", "geo_haversine" + } + # Terminal 类工具自带参数对错反馈机制,玩家/模型可自行试错, + # 无需在 investigate 时直接暴露 init_value + SELF_FEEDBACK_TOOLS = { + "terminal_1", "terminal_2", + "Logic Terminal", "Math Terminal", "Encryption Terminal", "Sequence Terminal" + } + _template_id_for_hint = raw_nodes_data.get(node.id, {}).get("template_id", "") + # 构建数据流入边映射(对所有工具):{target_port -> (source_node_id, source_port)} + _upstream_map = {} + for _edge in scenario.edges: + if (_edge.target_id == node.id + and _edge.connection_type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM] + and _edge.target_port is not None): + _upstream_map[_edge.target_port] = (_edge.source_id, _edge.source_port) + # 判断该节点是否有任意数据流入边(即不是纯源头节点) + _has_any_upstream = len(_upstream_map) > 0 + # 判断该节点是否有任意入边(包括 ITEM/HIDDEN_ITEM 掉落边) + # 有任意入边(含掉落边)但无数据流入边的节点,其输入来自初始可见参数,应直接给出 + _has_any_edge = any(_edge.target_id == node.id for _edge in scenario.edges) + # 构建 inputs 列表 + _inputs_list = [] + for p in node.inputs: + if p.type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + continue + port_dict = {"name": p.name, "type": p.type, "description": p.description} + if p.name in _upstream_map: + # 该端口有上游数据流依赖,且属于语义模糊工具 → 标注来源 + if _template_id_for_hint in AMBIGUOUS_TOOLS: + src_node_id, src_port = _upstream_map[p.name] + port_dict["upstream_from"] = f"{src_node_id}.{src_port}" if src_port else src_node_id + elif _has_any_edge and _template_id_for_hint not in SELF_FEEDBACK_TOOLS: + # 该节点有任意入边,但此端口没有数据流入边 → 值来自初始可见参数,直接给出 + # 排除自带反馈机制的 terminal 类工具(它们通过执行结果反馈对错,无需提前暴露参数值) + golden_val = node.golden_input_values.get(p.name) + if golden_val is not None: + port_dict["init_value"] = golden_val + _inputs_list.append(port_dict) + + tool_details = { + "id": node.id, # 节点 ID,用于唯一标识和调用这个具体节点 + "type": "Tool", + "inputs": _inputs_list, + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id 用于 Agent 内部判断工具类型(不会展示给被测模型) + if node.id in raw_nodes_data: + template_id = raw_nodes_data[node.id].get('template_id') + if template_id: + tool_details["_template_id"] = template_id # 使用下划线前缀标记为内部字段 + + # 只在 name 非空时添加 + # if node.name: + # tool_details["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_details["description"] = node.description + + # 添加 narrative 字段(如果存在) + if node.id in raw_nodes_data: + narrative = raw_nodes_data[node.id].get('narrative') + if narrative: + tool_details['narrative'] = narrative + + # 不再返回 init_values,避免泄漏答案 + # investigate 只应该返回工具的接口定义,不应该暴露初始值 + + # 【新增】检查该 Tool 是否有待触发的 HIDDEN_ITEM 掉落 + # 如果该工具已按照 golden_input 正确执行,且有 HIDDEN_ITEM 输出边,则触发掉落 + if node.has_hidden_item_ready: + logger.info(f"Tool has HIDDEN_ITEM ready - triggering passive drop for: {req.node_id}") + + # 遍历该工具的所有 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + # 重置标志,已经触发过了,避免重复 + node.has_hidden_item_ready = False + + logger.info(f"Tool investigation successful - node: {req.node_id}, revealed: {len(newly_revealed)}") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Tool", + "details": tool_details + } + + # 如果有新掉落的节点,添加到响应中 + if newly_revealed: + result["newly_revealed"] = newly_revealed + + return result + + # 处理 Item 的 investigate + elif node.type == "Item": + logger.info(f"Investigating item: {req.node_id}") + + # 【第一步】检查该 Item 是否有需要参数的输入端口 + # 如果有,且尚未通过 use_item 验证,则不返回内容,只返回参数要求 + required_inputs = [] + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + inputs_info = raw_node.get('inputs', []) + required_inputs = [ + { + "name": inp.get("name"), + "type": inp.get("type"), + "description": inp.get("description", "") + } + for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + # 如果有 required_inputs 且尚未通过 use_item 验证(if_success == False) + # 则不返回内容,只返回参数要求提示 + if required_inputs and not node.if_success: + logger.info(f"Item has required inputs and not yet unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "required_inputs": required_inputs + } + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + param_names = ', '.join([inp['name'] for inp in required_inputs]) + 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}" + + return result + + # 【新增】如果有 required_inputs 且已经通过 use_item 验证(if_success == True) + # 则返回提示:该节点已经被成功解决 + if required_inputs and node.if_success: + logger.info(f"Item has required inputs and already unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "message": "This item has already been successfully unlocked by you." + } + return result + + # 【第二步】该 Item 没有 required_inputs 或已通过验证,返回内容 + # 1. 返回 Item 的 golden_output_values(即 Item 的内容) + # 注意:某些 Item 仅用于触发 HIDDEN_ITEM 掉落,没有实际内容 + has_actual_content = bool(node.golden_output_values) or node.content is not None + content = node.golden_output_values if node.golden_output_values else node.content + + # 【关键】将 golden_output_values 追加到 actual_outputs_history,标记该 Item 已被 investigate + # 这样在渐进式暴露时,这些值才会被加入可见值集合 + # 即使是空字典(仅触发 HIDDEN_ITEM 的 Item),也要记录,以便渐进式暴露逻辑知道该 Item 已被调查 + if node.golden_output_values is not None: + node.actual_outputs_history.append(dict(node.golden_output_values)) + + # 2. Trigger Hidden Item Drops (Passive Drop) + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + logger.info(f"Item investigation successful - node: {req.node_id}, has_content: {has_actual_content}, revealed: {len(newly_revealed)}") + + # 【渐进式暴露】旧机制(基于 golden_input)已禁用 + # 现在完全由 ITEM/HIDDEN_ITEM 边触发控制节点可见性 + # 上面的 HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, node.golden_output_values or {}, node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # logger.info(f"Progressive reveal after Item investigate: {len(progressive_revealed)} nodes now ready") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Item" + } + + # 只在有实际内容时才添加 content 字段 + # 对于仅触发 HIDDEN_ITEM 掉落的 Item,不返回 content 字段,避免返回 None 或空字典让模型困惑 + if has_actual_content: + result["content"] = content + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型通过 investigate 获得内容后,需要自己识别这是否是胜利字符串 + + return result + + else: + logger.warning(f"Attempt to investigate unknown node type: {req.node_id} (type: {node.type})") + return {"ok": False, "error": f"Cannot investigate node type: {node.type}"} + +class ToolCallRequest(BaseModel): + node_id: str # 使用 node_id 精确指定要调用的节点 + arguments: Dict[str, Any] + +@app.post("/env/{case_id}/tool_call") +def tool_call(case_id: str, req: ToolCallRequest): + """Executes a tool and triggers item drops.""" + logger.info(f"Tool call request - case_id: {case_id}, node_id: {req.node_id}, args: {list(req.arguments.keys())}") + STATS["tool_calls"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + + # 通过 node_id 精确查找节点 + node_id = req.node_id + if node_id not in scenario.nodes: + logger.error(f"Node not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + tool_node = scenario.nodes[node_id] + + if not tool_node: + logger.error(f"Tool not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Tool not found") + + if not tool_node.is_revealed: + logger.warning(f"Attempt to call hidden tool: {node_id}") + return {"ok": False, "error": "Tool is not visible yet."} + + if tool_node.type != "Tool": + logger.warning(f"Attempt to call non-tool node: {node_id} (type: {tool_node.type})") + return {"ok": False, "error": "Only tools can be called."} + + # 1. Execute Tool (Real Execution via Simulator) + simulator = SIMULATORS[case_id] + + # Get tool name from template_id if available, otherwise use node name + tool_name = tool_node.name + if case_id in RAW_NODES_DATA and node_id in RAW_NODES_DATA[case_id]: + template_id = RAW_NODES_DATA[case_id][node_id].get('template_id') + if template_id: + tool_name = template_id + + # 文件处理工具和 Terminal 需要验证输入并返回预先计算的输出 + # 传递节点的实际输入输出值(从 DAG 执行后填充的数据) + tool_arguments = dict(req.arguments) # Make a copy + + # 传递节点的 golden values(从 JSON 的 inputs[].value 和 outputs[].value 加载) + # 用于在评测阶段验证被测模型传入的参数是否正确 + if tool_node.golden_input_values: + tool_arguments['_golden_inputs'] = tool_node.golden_input_values + if tool_node.golden_output_values: + tool_arguments['_golden_outputs'] = tool_node.golden_output_values + + logger.debug(f"Executing tool {tool_name} (node: {tool_node.name}) with args {tool_arguments}") + + try: + output_values = simulator.execute(tool_name, tool_arguments) + logger.info(f"Tool invoked - {tool_name}: {list(output_values.keys())}") + except Exception as e: + logger.error(f"Tool execution failed - {tool_name}: {str(e)}", exc_info=True) + return {"ok": False, "error": f"Tool execution failed: {str(e)}"} + + # 检查验证结果(精细化错误反馈) + validation = output_values.pop("_validation", {"valid": True}) + + if not validation["valid"]: + # 根据错误类型构造友好的错误消息 + error_type = validation.get("error_type") + + if error_type == "missing_required": + missing = validation.get("missing_params", []) + error_msg = f"Error: Missing required parameters {', '.join(missing)}" + + elif error_type == "type_error": + param = validation.get("param_name") + message = validation.get("message", "Parameter type error") + error_msg = f"Error: {message}" + + elif error_type == "incomplete_optional": + provided = validation.get("provided_params", []) + missing = validation.get("missing_params", []) + error_msg = ( + f"Hint: You provided some parameters ({', '.join(provided)}), " + f"but may also need: {', '.join(missing)}.\n" + f"Trying to provide these parameters together might yield better results." + ) + + elif error_type == "value_mismatch": + param = validation.get("param_name") + hint = validation.get("hint", "Parameter value may be incorrect") + error_msg = f"Hint: {hint}.\nPlease check if this parameter value meets the requirements." + + else: + error_msg = validation.get("hint") or validation.get("message", "Parameter validation failed") + + logger.info(f"Tool validation failed - {tool_name}: {error_type}") + return { + "ok": False, + "error": error_msg, + "error_type": error_type + } + + # Simulate success + tool_node.if_success = True + + # 【关键】将本次执行的输出值追加到历史列表(用于渐进式暴露判断) + # 每次调用都会记录,不会覆盖之前的执行结果 + tool_node.actual_outputs_history.append(dict(output_values)) + + # 2. 检查是否应该触发掉落(只有输入参数正确时才掉落) + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, tool_node.golden_input_values) + + newly_revealed = [] + investigate_hints = [] # 提示模型哪些节点可以 investigate 来发现隐藏内容 + + if inputs_match_golden: + logger.info(f"✓ Tool inputs match golden - node: {node_id}, triggering drops") + + # 检查该工具是否有 ITEM 或 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == tool_node.id: + target_node = scenario.nodes[edge.target_id] + + # ITEM 边:立即掉落(主动掉落) + if edge.connection_type == InterfaceType.ITEM: + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from {node_id})") + + # HIDDEN_ITEM 边:不立即掉落,标记并提示(被动掉落) + elif edge.connection_type == InterfaceType.HIDDEN_ITEM: + # 标记该工具有待触发的 HIDDEN_ITEM 掉落 + tool_node.has_hidden_item_ready = True + + # 提示模型可以 investigate 这个工具来发现隐藏内容 + hint_info = { + "tool_id": tool_node.id, + "hint": f"Tool '{tool_node.id}' seems to hide something, try investigating it to discover more information" + } + # if tool_node.name: + # hint_info["tool_name"] = tool_node.name + + investigate_hints.append(hint_info) + logger.info(f"HIDDEN_ITEM ready: {tool_node.id} -> {target_node.id} (will drop on investigate)") + else: + logger.info(f"✗ Tool inputs do NOT match golden - node: {node_id}, no drops triggered") + + response = { + "ok": True, + "message": "Tool invoked", + "output_values": output_values # Return raw outputs to Agent + } + + # 【新增】对源头节点进行参数验证反馈 + # 源头节点:没有数据流入边的节点,这些节点的参数需要模型自己推理 + # 验证模型使用的参数是否正确,并提供明确的反馈 + if _is_source_node(node_id, scenario) and tool_node.golden_input_values: + validation_feedback = _get_parameter_validation_feedback(req.arguments, tool_node.golden_input_values) + + if validation_feedback["all_correct"]: + # 用户提交了全部 golden 参数且全部正确 + response["parameter_feedback"] = { + "status": "correct", + "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." + } + logger.info(f"✓ Source node parameters all correct - node: {node_id}") + elif validation_feedback["incorrect_params"]: + # 有提交了但值错误的参数,只对这些参数给出反馈 + incorrect_list = [] + for param_name in validation_feedback["incorrect_params"]: + incorrect_list.append(f" - Parameter '{param_name}' is incorrect") + + correct_info = "" + if validation_feedback["correct_params"]: + correct_info = f"\n✓ Correct parameters: {', '.join(validation_feedback['correct_params'])}" + + response["parameter_feedback"] = { + "status": "incorrect", + "message": ( + f"⚠️ Some parameters are incorrect:\n" + + "\n".join(incorrect_list) + + correct_info + + 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." + ), + "incorrect_params": validation_feedback["incorrect_params"], + "correct_params": validation_feedback["correct_params"] + } + logger.info(f"✗ Source node parameters incorrect - node: {node_id}, incorrect: {validation_feedback['incorrect_params']}") + # else: 部分提交且全部正确 → 不给任何 parameter_feedback,避免对未提交的参数发表意见 + + # 检查工具调用是否完全正确(输出与 golden outputs 匹配) + # 用于给模型正向反馈,让它知道这个工具已经正确调用过,避免重复调用 + # 注意:只有当输出完全匹配时才标记为 correct,不会在错误时提供具体错误信息 + # if tool_node.golden_output_values and output_values: + # is_correct = True + # for port_name, expected_value in tool_node.golden_output_values.items(): + # actual_value = output_values.get(port_name) + # if str(actual_value) != str(expected_value): + # is_correct = False + # break + + # if is_correct: + # response["tool_call_correct"] = True + # logger.info(f"✓ Tool called with correct result - node: {node_id}") + + # 只在有新内容掉落时才返回 newly_revealed + if newly_revealed: + response["newly_revealed"] = newly_revealed + + # 添加 investigate 提示(对于有待触发 HIDDEN_ITEM 掉落的工具) + if investigate_hints: + response["investigate_hints"] = investigate_hints + + # 3. 渐进式暴露机制 - 现在完全由 ITEM/HIDDEN_ITEM 边控制 + # 旧机制(基于 golden_input 检查)已被禁用 + # 新机制中,节点的可见性只由 ITEM/HIDDEN_ITEM 边触发决定 + # 上面的 ITEM/HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, output_values, tool_node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # response["newly_revealed"] = newly_revealed + # logger.info(f"Progressive reveal: {len(progressive_revealed)} nodes now ready") + + # Check if this is the win node + if node_id == scenario.win_node_id: + # 验证输出值是否等于预期的胜利值 + # 从节点的 golden_output_values 中获取预期值(在 _initialize_node_values 时从 JSON 加载) + expected_outputs = tool_node.golden_output_values + + # 检查实际输出是否与预期输出匹配 + is_correct = False + victory_string = None + mismatch_info = [] + + if expected_outputs and output_values: + # 检查每个预期输出端口的值是否匹配 + is_correct = True + for port_name, expected_value in expected_outputs.items(): + actual_value = output_values.get(port_name) + if actual_value != expected_value: + is_correct = False + mismatch_info.append(f"Port '{port_name}': expected '{expected_value}', actual '{actual_value}'") + logger.warning(f"Win node output mismatch - port: {port_name}, expected: {expected_value}, actual: {actual_value}") + + # 如果所有输出都匹配,使用第一个输出作为胜利字符串 + if is_correct and output_values: + victory_string = list(output_values.values())[0] + else: + logger.warning(f"Win node called but missing output values - expected: {expected_outputs}, actual: {output_values}") + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型调用工具获得输出后,需要自己识别这是否是胜利字符串并提交 + if is_correct: + logger.info(f"🎯 Win node called with correct output - case: {case_id}, node: {node_id}, victory: {victory_string}") + else: + logger.info(f"❌ Win node called with incorrect output - case: {case_id}, node: {node_id}") + + return response + +class UseItemRequest(BaseModel): + node_id: str = Field(..., description="The ID of the Item node to use (must be Item type)") + arguments: Dict[str, Any] = Field(default_factory=dict, description="Input arguments to provide to the item") + +@app.post("/env/{case_id}/use_item") +def use_item(case_id: str, req: UseItemRequest): + """ + Use an Item node by providing input arguments. + + This is specifically for Item nodes that require parameters to be "unlocked" or "activated", + such as containers that need a password/fingerprint. + + - Validates that the node is of type Item + - Checks if provided arguments match the item's golden_input_values + - If match: triggers ITEM-type edge drops and returns the item's content + - If not match: returns error message + """ + logger.info(f"Use item request - case_id: {case_id}, node_id: {req.node_id}, args: {req.arguments}") + STATS["use_items"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + item_node = scenario.nodes[req.node_id] + + if not item_node.is_revealed: + logger.warning(f"Attempt to use hidden item: {req.node_id}") + return {"ok": False, "error": "Item is not visible yet."} + + if item_node.type != "Item": + logger.warning(f"Attempt to use non-item node: {req.node_id} (type: {item_node.type})") + return {"ok": False, "error": "Only Item nodes can be used with use_item. Tools should be called with tool_call."} + + # 【新增】检查该 Item 是否已经被成功解锁 + # 如果已经被正确使用过,直接返回成功提示 + if item_node.if_success: + logger.info(f"Item already unlocked, returning success message: {req.node_id}") + return { + "ok": True, + "message": "This item has already been successfully unlocked by you." + } + + # 检查该 Item 是否真的需要通过 use_item 提供参数 + # 只有当 Item 有非 Item/Hidden_Item 类型的输入时,才应该使用 use_item + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + non_hidden_inputs = [ + inp for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + if not non_hidden_inputs: + # 该 Item 不需要参数,应该只使用 investigate + logger.warning(f"Attempt to use_item on a node that doesn't require parameters: {req.node_id}") + return { + "ok": False, + "error": "This item does not require parameters. Please use investigate to examine the item directly." + } + + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, item_node.golden_input_values) + + if not inputs_match_golden: + logger.info(f"✗ Item inputs do NOT match golden - node: {req.node_id}") + # 提供更详细的错误信息,帮助 Agent 理解问题 + # 只显示非 Item/Hidden_Item 类型的参数(Hidden_Item 由系统自动处理) + expected_params = [] + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + expected_params = [ + inp.get("name") for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + provided_params = list(req.arguments.keys()) if req.arguments else [] + + # 检查参数名是否匹配 + if set(expected_params) == set(provided_params): + # 参数名正确但值不匹配 - 不泄漏正确的值 + error_msg = f"Parameter names are correct, but the parameter values are incorrect. Please try using different parameter values." + else: + error_msg = f"Parameter names do not match. Expected parameter names: {expected_params}, you provided: {provided_params}." + + return { + "ok": False, + "error": error_msg + } + + logger.info(f"✓ Item inputs match golden - node: {req.node_id}, activating item") + + # 标记该 Item 已被正确使用 + item_node.if_success = True + + # 将 golden_output_values 追加到 actual_outputs_history + if item_node.golden_output_values: + item_node.actual_outputs_history.append(dict(item_node.golden_output_values)) + + # 触发 ITEM 类型边的掉落 + newly_revealed = [] + for edge in scenario.edges: + if edge.source_id == item_node.id and edge.connection_type == InterfaceType.ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from use_item on {req.node_id})") + + # 检查是否为 Win Node + win_node_id = scenario.win_node_id + is_win_node = (req.node_id == win_node_id) + + # 构建返回结果 + result = { + "ok": True, + "message": "Item used successfully.", + "content": item_node.golden_output_values if item_node.golden_output_values else None + } + + # 获取 narrative(如果存在) + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + narrative = raw_nodes_data[req.node_id].get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 如果是 Win Node,只记录日志 + if is_win_node: + logger.info(f"Win node (Item) unlocked via use_item - case: {case_id}, node: {req.node_id}") + + return result + + +class SubmitAnswerRequest(BaseModel): + answer: str = Field(..., description="The victory string to submit") + +@app.post("/env/{case_id}/submit_answer") +def submit_answer(case_id: str, req: SubmitAnswerRequest): + """ + 提交答案接口 + 被测模型在获得胜利字符串提示后,需要调用此接口提交答案 + """ + logger.info(f"Submit answer request - case_id: {case_id}, answer: {req.answer}") + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + + # 获取 win_node 的 golden_output_values + if not scenario.win_node_id: + logger.error(f"No win node defined for case: {case_id}") + return { + "ok": False, + "error": "This case has no victory node defined" + } + + win_node = scenario.nodes.get(scenario.win_node_id) + if not win_node: + logger.error(f"Win node not found: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node does not exist" + } + + # 获取正确的胜利字符串(取第一个 golden_output_value) + if win_node.golden_output_values: + correct_answer = list(win_node.golden_output_values.values())[0] + else: + logger.error(f"Win node has no golden_output_values: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node has no correct answer" + } + + # 验证提交的答案 + if req.answer == correct_answer: + logger.info(f"🎉 CORRECT ANSWER SUBMITTED - case: {case_id}, answer: {req.answer}") + return { + "ok": True, + "is_win": True, + "victory_message": f"🎉 Congratulations on successfully escaping the room! Your answer is correct: {req.answer}" + } + else: + logger.info(f"❌ INCORRECT ANSWER SUBMITTED - case: {case_id}, submitted: {req.answer}, correct: {correct_answer}") + return { + "ok": True, + "is_win": False, + "error": f"The submitted answer is incorrect. You submitted: {req.answer}" + } + +if __name__ == "__main__": + + uvicorn.run(app, host="0.0.0.0", port=8000) \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-ad399fad/environment/puzzle/upstream/simulator.py b/tasks/agentescape-25-skeleton-ad399fad/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-25-skeleton-ad399fad/environment/puzzle/upstream/simulator.py @@ -0,0 +1,2911 @@ +import hashlib +import hmac +import base64 +import binascii +import zlib +import json +import uuid +import math +import re +from typing import Dict, Any, List + +class ToolSimulator: + def __init__(self): + """工具模拟器 + + 文件处理工具(zip_unzip, zip_unzip_file, zip_unzip_item, json_get, csv_query, + regex_search, graph_shortest_path)不需要真实文件系统。 + 这些工具只验证输入参数,然后返回预先初始化好的 golden_outputs。 + """ + self.tool_map = { + # 数论 + "calc_bigmul": self.calc_bigmul, + "calc_modexp": self.calc_modexp, + "calc_modexp_int": self.calc_modexp_int, + "calc_gcd": self.calc_gcd, + "calc_gcd_int": self.calc_gcd_int, + "calc_inv_mod": self.calc_inv_mod, + "calc_inv_mod_int": self.calc_inv_mod_int, + + # 哈希 + "hash_sha256": self.hash_sha256, + "hash_md5": self.hash_md5, + "hmac_sha256": self.hmac_sha256, + + # 编码 + "base64_decode": self.base64_decode, + "base64_encode": self.base64_encode, + "hex_decode": self.hex_decode, + "hex_encode": self.hex_encode, + "zlib_inflate": self.zlib_inflate, + "zlib_deflate": self.zlib_deflate, + + # 文件 + "zip_unzip": self.zip_unzip, + "zip_unzip_file": self.zip_unzip_file, + "zip_unzip_item": self.zip_unzip_item, + "regex_search": self.regex_search, + "json_get": self.json_get, + "csv_query": self.csv_query, + "code_py_exec": self.code_py_exec, + + # 图 + "graph_shortest_path": self.graph_shortest_path, + + # 加解密 (简化模拟) + "crypto_aes_cbc_decrypt": self.crypto_aes_cbc_decrypt, + "crypto_rsa_decrypt_hex": self.crypto_rsa_decrypt_hex, + + # 其他 + "num_base_convert": self.num_base_convert, + "time_convert": self.time_convert, + "checksum_crc32": self.checksum_crc32, + "geo_haversine": self.geo_haversine, + "otp_totp_generate": self.otp_totp_generate, + "unicode_norm": self.unicode_norm, + "text_bidi_sanitize": self.text_bidi_sanitize, + "text_xor_hex": self.text_xor_hex, + "text_rotN": self.text_rotN, + "luhn_check": self.luhn_check, + "iban_validate": self.iban_validate, + + # 物理 + "matter_synthesizer": self.matter_synthesizer, + + # 终端机 + "terminal_1": self.terminal_1, + "terminal_2": self.terminal_2, + "Logic Terminal": self.logic_terminal, + "Math Terminal": self.math_terminal, + "Encryption Terminal": self.crypt_terminal, + "Sequence Terminal": self.sequence_terminal + } + + def execute(self, tool_name: str, inputs: Dict[str, Any]) -> Dict[str, Any]: + if tool_name not in self.tool_map: + # Fallback for unknown tools: return dummy outputs based on expected output types + # This should ideally not happen if all tools are implemented + return {} + + try: + return self.tool_map[tool_name](inputs) + except Exception as e: + print(f"Error executing {tool_name}: {e}") + # Return empty or error indication? For generation, we might want to fail hard or return dummy. + # For now, return dummy to keep flow going, but log error. + return {} + + # --- Implementations --- + + def calc_bigmul(self, inputs): + # Check if required parameters are present + if "a" not in inputs or "b" not in inputs: + raise ValueError("Missing required parameters 'a' and/or 'b'") + + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + return {"product": str(a * b)} + except (ValueError, TypeError) as e: + raise ValueError(f"Failed to convert parameters to integers: {str(e)}") + + def calc_modexp(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + try: + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if isinstance(base, str): + base = int(base) + elif not isinstance(base, int): + raise ValueError("Parameter 'base' must be a string or integer") + + if isinstance(exp, str): + exp = int(exp) + elif not isinstance(exp, int): + raise ValueError("Parameter 'exp' must be a string or integer") + + if isinstance(mod, str): + mod = int(mod) + elif not isinstance(mod, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": str(pow(base, exp, mod))} + + def calc_modexp_int(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["base"], int): + raise ValueError("Parameter 'base' must be an integer") + if not isinstance(inputs["exp"], int): + raise ValueError("Parameter 'exp' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": pow(base, exp, mod)} + + def calc_gcd(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + # 计算 GCD 并返回字符串格式(符合 Big_Int 输出类型) + result = math.gcd(a, b) + return {"gcd": str(result)} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def calc_gcd_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["b"], int): + raise ValueError("Parameter 'b' must be an integer") + + # 获取参数 + a = inputs["a"] + b = inputs["b"] + + return {"gcd": math.gcd(a, b)} + + def calc_inv_mod(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + m = inputs["mod"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(m, str): + m = int(m) + elif not isinstance(m, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": str(pow(a, -1, m))} + except ValueError as e: + # 模逆不存在时,返回一个特殊值(用于数据传递) + # 在 DAG 生成阶段,这允许数据流继续 + return {"inv": str(a)} + + def calc_inv_mod_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + a = inputs["a"] + m = inputs["mod"] + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": pow(a, -1, m)} + except ValueError as e: + raise ValueError(f"Modular inverse does not exist: {str(e)}") + + def hash_sha256(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.sha256(text.encode()).hexdigest()} + + def hash_md5(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.md5(text.encode()).hexdigest()} + + def hmac_sha256(self, inputs): + # 参数检查 + if "hex_key" not in inputs: + raise ValueError("Missing required parameter: hex_key") + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["hex_key"], str): + raise ValueError("Parameter 'hex_key' must be a string") + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + try: + key = bytes.fromhex(inputs["hex_key"]) + text = inputs["text"].encode() + return {"hex": hmac.new(key, text, hashlib.sha256).hexdigest()} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def base64_decode(self, inputs): + # 参数检查 + if "data" not in inputs: + raise ValueError("Missing required parameter: data") + + # 类型检查 + if not isinstance(inputs["data"], str): + raise ValueError("Parameter 'data' must be a string") + + data = inputs["data"] + try: + return {"bytes_hex": binascii.hexlify(base64.b64decode(data)).decode()} + except Exception as e: + raise ValueError(f"Base64 decode error: {str(e)}") + + def base64_encode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"b64": base64.b64encode(bytes.fromhex(hex_data)).decode()} + except Exception as e: + raise ValueError(f"Base64 encode error: {str(e)}") + + def hex_decode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"text": bytes.fromhex(hex_data).decode('utf-8', errors='ignore')} + except Exception as e: + raise ValueError(f"Hex decode error: {str(e)}") + + def hex_encode(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + try: + return {"hex": text.encode().hex()} + except Exception as e: + raise ValueError(f"Hex encode error: {str(e)}") + + + # 到此处实现已经更新 + + def zlib_inflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("Parameter 'hex' must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("Missing required parameter: hex") + + try: + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空字符串 + if not hex_data: + raise ValueError("Empty hex string provided") + + # 检查十六进制字符串的有效性 + if len(hex_data) % 2 != 0: + raise ValueError("Hex string must have even length") + + # 检查是否只包含有效的十六进制字符 + if not all(c in '0123456789abcdefABCDEF' for c in hex_data): + raise ValueError("Invalid hex string provided") + + # 尝试解压缩 + return {"text": zlib.decompress(bytes.fromhex(hex_data)).decode('utf-8')} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hex string provided") from e + raise ValueError(f"Invalid zlib data: {e}") from e + except Exception as e: + raise RuntimeError(f"Failed to inflate data: {e}") from e + + def zlib_deflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("Parameter 'text' must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("Missing required parameter: text") + + try: + # 压缩文本 + return {"hex": zlib.compress(text.encode('utf-8')).hex()} + except Exception as e: + raise RuntimeError(f"Failed to deflate data: {e}") from e + + # --- File Operations --- + + def zip_unzip(self, inputs): + """ZIP 解压工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"files": golden_outputs.get("files", "")} + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return {"files": golden_outputs.get("files", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "files" in golden_outputs: + # 验证必需参数 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 检查类型 + if has_zip_id and not isinstance(zip_id, str): + return {"error": "Parameter 'zip_id' must be a string type"} + if has_password and not isinstance(password, str): + return {"error": "Parameter 'password' must be a string type"} + + # 验证输入是否与预期匹配 + if golden_inputs: + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return {"files": golden_outputs["files"]} + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + # 没有golden_inputs但有golden_outputs,直接返回输出 + return {"files": golden_outputs["files"]} + + # 如果没有预期输出,返回空结果 + return {"files": ""} + + def regex_search(self, inputs): + """正则搜索工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"matches": golden_outputs.get("matches", "[]")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "matches" in golden_outputs: + # 提取实际参数 + pattern = inputs.get("pattern") + file_id = inputs.get("file_id") + text = inputs.get("text") + + # 1. 检查必需参数 + if pattern is None: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["pattern"], + "message": "Missing required parameter 'pattern'" + } + } + + # 类型检查 + if not isinstance(pattern, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "pattern", + "message": "Parameter 'pattern' must be a string type" + } + } + if file_id is not None and not isinstance(file_id, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if text is not None and not isinstance(text, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "text", + "message": "Parameter 'text' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合 + provided_params = {} + if pattern is not None: + provided_params["pattern"] = pattern + if file_id is not None: + provided_params["file_id"] = file_id + if text is not None: + provided_params["text"] = text + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数(关键改进) + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_pattern = golden_inputs.get("pattern") + expected_file_id = golden_inputs.get("file_id") + expected_text = golden_inputs.get("text") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_pattern is not None: + if str(pattern) != str(expected_pattern): + incorrect_params.append("pattern") + else: + correct_params.append("pattern") + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_text is not None: + if str(text) != str(expected_text): + incorrect_params.append("text") + else: + correct_params.append("text") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "matches": "[]", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "matches": golden_outputs["matches"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空列表 + return {"matches": "[]"} + + def json_get(self, inputs): + """JSON 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"values": golden_outputs.get("values", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "values" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + jsonpath = inputs.get("jsonpath", "") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if jsonpath is not None and not isinstance(jsonpath, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "jsonpath", + "message": "Parameter 'jsonpath' must be a string type" + } + } + + # 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:jsonpath有默认值"") + provided_params = {} + if file_id is not None: + provided_params["file_id"] = file_id + if jsonpath != "": + provided_params["jsonpath"] = jsonpath + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_jsonpath = golden_inputs.get("jsonpath") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_jsonpath is not None: + if str(jsonpath) != str(expected_jsonpath): + incorrect_params.append("jsonpath") + else: + correct_params.append("jsonpath") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "values": "", + "_validation": validation_info + } + + # 所有验证通过,返回正确输出 + return { + "values": golden_outputs["values"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"values": ""} + + def csv_query(self, inputs): + """CSV 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"rows": golden_outputs.get("rows", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "rows" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + select_columns = inputs.get("select", "") + where_clause = inputs.get("where", "") + + # 1. 检查必需参数 + if file_id is None: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["file_id"], + "message": "Missing required parameter 'file_id'" + } + } + + # 类型检查 + if not isinstance(file_id, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if not isinstance(select_columns, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "select", + "message": "Parameter 'select' must be a string type" + } + } + if not isinstance(where_clause, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "where", + "message": "Parameter 'where' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:select和where有默认值"") + provided_params = {"file_id": file_id} + if select_columns != "": + provided_params["select"] = select_columns + if where_clause != "": + provided_params["where"] = where_clause + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_select = golden_inputs.get("select") + expected_where = golden_inputs.get("where") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_select is not None: + if str(select_columns) != str(expected_select): + incorrect_params.append("select") + else: + correct_params.append("select") + + if expected_where is not None: + if str(where_clause) != str(expected_where): + incorrect_params.append("where") + else: + correct_params.append("where") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "rows": "", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "rows": golden_outputs["rows"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"rows": ""} + + def graph_shortest_path(self, inputs): + """图最短路径工具 + + 如果有 _golden_outputs 或 _init_outputs,验证输入并返回预设输出。 + 否则执行真实的 Dijkstra 算法。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 检查是否在预设模式中(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + if golden_outputs and "path" in golden_outputs: + # 评测阶段但没有 golden_inputs,直接返回 outputs + if not golden_inputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 评测模式:验证输入参数是否匹配 golden 值 + src = inputs.get("src") + dst = inputs.get("dst") + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + + has_src = src is not None and src != "" + has_dst = dst is not None and dst != "" + + # 验证必需参数 + if not has_src or not has_dst: + missing = [] + if not has_src: + missing.append("src") + if not has_dst: + missing.append("dst") + return {"error": "Missing required parameters: " + ", ".join(missing)} + + # 类型检查 + if not isinstance(src, str): + return {"error": "Parameter 'src' must be a string"} + if not isinstance(dst, str): + return {"error": "Parameter 'dst' must be a string"} + + # 验证输入是否匹配期望值 + if golden_inputs: + expected_src = golden_inputs.get("src") + expected_dst = golden_inputs.get("dst") + expected_file_id = golden_inputs.get("file_id") + expected_graph_data = golden_inputs.get("graph_data") + + # 收集验证结果 + incorrect_params = [] + correct_params = [] + + # 检查必需参数是否匹配 + if expected_src is not None: + if str(src) != str(expected_src): + incorrect_params.append("src") + else: + correct_params.append("src") + + if expected_dst is not None: + if str(dst) != str(expected_dst): + incorrect_params.append("dst") + else: + correct_params.append("dst") + + # 检查可选参数(如果在 expected_inputs 中定义了) + if expected_file_id is not None: + if file_id != expected_file_id: + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_graph_data is not None: + if graph_data != expected_graph_data: + incorrect_params.append("graph_data") + else: + correct_params.append("graph_data") + + # 如果有参数不正确,返回详细的反馈 + if incorrect_params: + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 验证通过,返回预设的输出 + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 获取参数(真实执行路径) + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + # Support both src/dst (interface definition) and start/end (original implementation) + start = inputs.get("src") + end = inputs.get("dst") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + raise TypeError("file_id must be a string") + + if graph_data is not None and not isinstance(graph_data, str): + raise TypeError("graph_data must be a string") + + if start is not None and not isinstance(start, str): + raise TypeError("src/start must be a string") + + if end is not None and not isinstance(end, str): + raise TypeError("dst/end must be a string") + + # 检查必需参数 + if file_id is None and graph_data is None: + raise ValueError("Either file_id or graph_data must be provided") + + if start is None: + raise ValueError("src/start parameter is required") + + if end is None: + raise ValueError("dst/end parameter is required") + + # Get graph content + content = None + if file_id is not None: + # 尝试从 VFS 获取(如果存在) + if hasattr(self, 'vfs') and file_id in self.vfs: + content = self.vfs[file_id] + else: + # VFS 不存在或文件不在 VFS 中 + # 返回一个默认的空图结果,或者抛出错误提示需要 init_outputs + raise ValueError( + f"File '{file_id}' not found. For tools that require files, " + f"please provide init_outputs in the initial_values." + ) + elif graph_data is not None: + content = graph_data + + if content is None: + content = "{}" + + try: + # Parse graph data + graph = json.loads(content) + + # 类型检查 + if not isinstance(graph, dict): + raise TypeError("Graph data must be a dictionary") + + # If graph is not in the expected format, try to extract adjacency list + if "nodes" in graph and "edges" in graph: + # 验证nodes和edges的类型 + if not isinstance(graph["nodes"], list): + raise TypeError("Nodes must be a list") + + if not isinstance(graph["edges"], list): + raise TypeError("Edges must be a list") + + # Convert from nodes/edges format to adjacency list + adjacency_list = {} + for node in graph["nodes"]: + # 验证node类型 + if not isinstance(node, dict): + raise TypeError("Each node must be a dictionary") + + # Use node ID as key, not the entire node dictionary + node_id = node.get("id", "") + if node_id: + adjacency_list[node_id] = {} + + for edge in graph["edges"]: + # 验证edge类型 + if not isinstance(edge, dict): + raise TypeError("Each edge must be a dictionary") + + u = edge["from"] + v = edge["to"] + weight = edge.get("weight", 1) # Default to unweighted + + # 类型检查 + if not isinstance(u, str): + raise TypeError("Edge 'from' must be a string") + + if not isinstance(v, str): + raise TypeError("Edge 'to' must be a string") + + if not isinstance(weight, (int, float)): + raise TypeError("Edge weight must be a number") + + if u not in adjacency_list: + adjacency_list[u] = {} + if v not in adjacency_list: + adjacency_list[v] = {} + + adjacency_list[u][v] = weight + # If undirected, add reverse edge + if not edge.get("directed", False): + adjacency_list[v][u] = weight + elif isinstance(graph, dict): + # Already in adjacency list format + adjacency_list = graph + + # 验证邻接表结构 + for node, neighbors in adjacency_list.items(): + if not isinstance(neighbors, dict): + raise TypeError("Adjacency list must be a dictionary of dictionaries") + + for neighbor, weight in neighbors.items(): + if not isinstance(weight, (int, float)): + raise TypeError("Edge weights must be numbers") + else: + raise TypeError("Graph data must be a dictionary") + + # 检查起点和终点是否为空 + if not start: + raise ValueError("Start node cannot be empty") + + if not end: + raise ValueError("End node cannot be empty") + + # 检查起点和终点是否在图中 + if start not in adjacency_list: + raise ValueError(f"Start node '{start}' not found in graph") + + if end not in adjacency_list: + raise ValueError(f"End node '{end}' not found in graph") + + # Dijkstra's algorithm implementation + import heapq + + # Initialize distances and previous nodes + distances = {node: float('infinity') for node in adjacency_list} + previous = {node: None for node in adjacency_list} + distances[start] = 0 + + # Priority queue + pq = [(0, start)] + heapq.heapify(pq) + + while pq: + current_dist, current_node = heapq.heappop(pq) + + # If we've reached the end node, we can break early + if current_node == end: + break + + # Nodes can be added multiple times to the priority queue, but we only process them once + if current_dist > distances[current_node]: + continue + + # Explore neighbors + for neighbor, weight in adjacency_list[current_node].items(): + distance = current_dist + weight + + # If a shorter path is found + if distance < distances[neighbor]: + distances[neighbor] = distance + previous[neighbor] = current_node + heapq.heappush(pq, (distance, neighbor)) + + # Reconstruct the shortest path + path = [] + current = end + while current is not None: + path.append(current) + current = previous[current] + path.reverse() # Reverse to get from start to end + + # Check if path exists + if not path or path[0] != start: + return {"path": "[]", "cost": 0} + + return { + "path": json.dumps(path), + "cost": distances[end] + } + except json.JSONDecodeError as e: + raise ValueError(f"Invalid JSON in graph data: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in graph_shortest_path: {str(e)}") + + # --- Crypto (Simplified) --- + def crypto_aes_cbc_decrypt(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 (使用模板中定义的参数名) + hex_cipher = inputs.get("hex_cipher") + hex_key = inputs.get("hex_key") + hex_iv = inputs.get("hex_iv") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + + if hex_key is not None and not isinstance(hex_key, str): + raise TypeError("hex_key must be a string") + + if hex_iv is not None and not isinstance(hex_iv, str): + raise TypeError("hex_iv must be a string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + + if hex_key is None: + raise ValueError("hex_key parameter is required") + + if hex_iv is None: + raise ValueError("hex_iv parameter is required") + + from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes + from cryptography.hazmat.backends import default_backend + from cryptography.hazmat.primitives import padding + + try: + # Convert hex strings to bytes + ciphertext = bytes.fromhex(hex_cipher) + key = bytes.fromhex(hex_key) + iv = bytes.fromhex(hex_iv) + + # Validate key length (AES-128, AES-192, AES-256) + if len(key) not in [16, 24, 32]: + raise ValueError("Invalid key length. Must be 16, 24, or 32 bytes.") + + if len(iv) != 16: + raise ValueError("Invalid IV length. Must be 16 bytes.") + + # Create cipher object + cipher = Cipher( + algorithms.AES(key), + modes.CBC(iv), + backend=default_backend() + ) + + decryptor = cipher.decryptor() + + # Decrypt the ciphertext + padded_plaintext = decryptor.update(ciphertext) + decryptor.finalize() + + # Remove PKCS7 padding + unpadder = padding.PKCS7(128).unpadder() + plaintext = unpadder.update(padded_plaintext) + unpadder.finalize() + + # Return decrypted text + return {"text": plaintext.decode('utf-8', errors='ignore')} + except ValueError as e: + if "non-hexadecimal number found in fromhex()" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher, hex_key, or hex_iv") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in crypto_aes_cbc_decrypt: {str(e)}") + + def crypto_rsa_decrypt_hex(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_cipher = inputs.get("hex_cipher") + n = inputs.get("n") + d = inputs.get("d") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + if n is not None and not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + if d is not None and not isinstance(d, (int, str)): + raise TypeError("d must be an integer or string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + if n is None: + raise ValueError("n parameter is required") + if d is None: + raise ValueError("d parameter is required") + + try: + # Convert parameters to appropriate types + cipher_int = int(hex_cipher, 16) + n_int = int(n) if isinstance(n, str) else n + d_int = int(d) if isinstance(d, str) else d + + # RSA decryption: plaintext = ciphertext^d mod n + plaintext_int = pow(cipher_int, d_int, n_int) + + # Convert result to hex and then to text + plaintext_hex = hex(plaintext_int)[2:] + + # Pad with leading zero if odd length + if len(plaintext_hex) % 2 != 0: + plaintext_hex = '0' + plaintext_hex + + # Convert hex to bytes and then to text + try: + plaintext_bytes = bytes.fromhex(plaintext_hex) + plaintext_text = plaintext_bytes.decode('utf-8', errors='ignore') + except: + # If decoding fails, return hex representation + plaintext_text = plaintext_hex + + return {"text": plaintext_text} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in crypto_rsa_decrypt_hex: {str(e)}") + + # --- Others --- + def num_base_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + s = inputs.get("s") + from_base = inputs.get("from_base") + to_base = inputs.get("to_base") + + # 类型检查 - 接受 str 或 int + if s is not None and not isinstance(s, (str, int)): + raise TypeError("s must be a string or integer") + + if from_base is not None and not isinstance(from_base, (int, str)): + raise TypeError("from_base must be an integer") + + if to_base is not None and not isinstance(to_base, (int, str)): + raise TypeError("to_base must be an integer") + + # 检查必需参数 + if s is None: + raise ValueError("s parameter is required") + + if from_base is None: + raise ValueError("from_base parameter is required") + + if to_base is None: + raise ValueError("to_base parameter is required") + + try: + # Convert to int if needed + from_base = int(from_base) if isinstance(from_base, str) else from_base + to_base = int(to_base) if isinstance(to_base, str) else to_base + s_str = str(s) + + # 验证基数范围 + if from_base < 2 or from_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + if to_base < 2 or to_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + # Convert from source base to decimal + val = int(s_str, from_base) + + # Convert from decimal to target base + if to_base == 10: + result = str(val) + elif to_base == 16: + result = hex(val)[2:] + elif to_base == 8: + result = oct(val)[2:] + elif to_base == 2: + result = bin(val)[2:] + else: + # Generic base conversion for other bases + if val == 0: + result = "0" + else: + digits = "0123456789abcdefghijklmnopqrstuvwxyz" + result = "" + n = abs(val) + while n: + result = digits[n % to_base] + result + n //= to_base + if val < 0: + result = "-" + result + + return {"str": result} + except ValueError as e: + raise ValueError(f"Invalid number format: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in num_base_convert: {str(e)}") + + def time_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iso = inputs.get("iso") + timestamp = inputs.get("timestamp") + datetime_str = inputs.get("datetime") + from_tz = inputs.get("from_tz") + to_tz = inputs.get("to_tz") + format_str = inputs.get("format") + + # 类型检查 + if iso is not None and not isinstance(iso, str): + raise TypeError("iso must be a string") + + if timestamp is not None and not isinstance(timestamp, (str, int, float)): + raise TypeError("timestamp must be a string, integer, or float") + + if datetime_str is not None and not isinstance(datetime_str, str): + raise TypeError("datetime must be a string") + + if from_tz is not None and not isinstance(from_tz, str): + raise TypeError("from_tz must be a string") + + if to_tz is not None and not isinstance(to_tz, str): + raise TypeError("to_tz must be a string") + + if format_str is not None and not isinstance(format_str, str): + raise TypeError("format must be a string") + + # 设置默认值 + if from_tz is None: + from_tz = "UTC" + + if to_tz is None: + to_tz = "UTC" + + import datetime + import pytz + + # 验证时区参数 + try: + if from_tz: + pytz.timezone(from_tz) + if to_tz: + pytz.timezone(to_tz) + except Exception: + raise ValueError("Invalid timezone provided") + + try: + # Parse input time + dt = None + + if iso is not None: + # Parse ISO 8601 format + dt = datetime.datetime.fromisoformat(iso.replace('Z', '+00:00')) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=pytz.UTC) + elif timestamp is not None: + # Parse Unix timestamp + timestamp = float(timestamp) + dt = datetime.datetime.fromtimestamp(timestamp, pytz.UTC) + elif datetime_str is not None: + # Parse datetime string + # Try common formats + formats_to_try = [ + "%Y-%m-%d %H:%M:%S", + "%Y-%m-%d %H:%M:%S.%f", + "%Y-%m-%d", + "%m/%d/%Y %H:%M:%S", + "%m/%d/%Y" + ] + + parse_success = False + for fmt in formats_to_try: + try: + dt = datetime.datetime.strptime(datetime_str, fmt) + dt = pytz.timezone(from_tz).localize(dt) + parse_success = True + break + except ValueError: + continue + + if not parse_success: + raise ValueError("Unable to parse datetime string with common formats") + else: + # 如果没有提供任何时间参数,则使用当前时间 + dt = datetime.datetime.now(pytz.UTC) + except ValueError as e: + raise ValueError(f"Error parsing time input: {str(e)}") + except Exception as e: + raise RuntimeError(f"Unexpected error parsing time input: {str(e)}") + + try: + # Convert timezone + if from_tz != to_tz: + dt = dt.astimezone(pytz.timezone(to_tz)) + + # Format outputs + result = { + "iso": dt.isoformat(), + "timestamp": str(dt.timestamp()), + "datetime": dt.strftime("%Y-%m-%d %H:%M:%S"), + "date": dt.strftime("%Y-%m-%d"), + "time": dt.strftime("%H:%M:%S"), + "timezone": to_tz + } + + # Add custom format if requested + if format_str: + try: + result["formatted"] = dt.strftime(format_str) + except ValueError as e: + raise ValueError(f"Invalid format string: {str(e)}") + + return result + except Exception as e: + raise RuntimeError(f"Error in time_convert: {str(e)}") + + def checksum_crc32(self, inputs): + import zlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("hex must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("hex parameter is required") + + try: + # 验证十六进制字符串 + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空 + if not hex_data: + raise ValueError("hex data cannot be empty") + + # 检查是否为有效的十六进制字符串 + if not all(c in "0123456789abcdefABCDEF" for c in hex_data): + raise ValueError("hex must be a valid hexadecimal string") + + # 检查长度是否为偶数 + if len(hex_data) % 2 != 0: + raise ValueError("hex must have even number of characters") + + val = zlib.crc32(bytes.fromhex(hex_data)) + # 确保 hex 输出是 8 位,前导补 0 + return {"hex": f"{val:08x}", "int": val} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in checksum_crc32: {str(e)}") + + def geo_haversine(self, inputs): + import math + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + lat1 = inputs.get("lat1") + lon1 = inputs.get("lon1") + lat2 = inputs.get("lat2") + lon2 = inputs.get("lon2") + + # 类型检查 + if lat1 is not None and not isinstance(lat1, (int, float, str)): + raise TypeError("lat1 must be a number or string") + if lon1 is not None and not isinstance(lon1, (int, float, str)): + raise TypeError("lon1 must be a number or string") + if lat2 is not None and not isinstance(lat2, (int, float, str)): + raise TypeError("lat2 must be a number or string") + if lon2 is not None and not isinstance(lon2, (int, float, str)): + raise TypeError("lon2 must be a number or string") + + # 检查必需参数 + if lat1 is None: + raise ValueError("lat1 parameter is required") + if lon1 is None: + raise ValueError("lon1 parameter is required") + if lat2 is None: + raise ValueError("lat2 parameter is required") + if lon2 is None: + raise ValueError("lon2 parameter is required") + + try: + # 转换为浮点数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(lat1, str): + lat1 = float(lat1) + elif not isinstance(lat1, (int, float)): + raise TypeError("lat1 must be a number or string") + else: + lat1 = float(lat1) + + if isinstance(lon1, str): + lon1 = float(lon1) + elif not isinstance(lon1, (int, float)): + raise TypeError("lon1 must be a number or string") + else: + lon1 = float(lon1) + + if isinstance(lat2, str): + lat2 = float(lat2) + elif not isinstance(lat2, (int, float)): + raise TypeError("lat2 must be a number or string") + else: + lat2 = float(lat2) + + if isinstance(lon2, str): + lon2 = float(lon2) + elif not isinstance(lon2, (int, float)): + raise TypeError("lon2 must be a number or string") + else: + lon2 = float(lon2) + + # Validate coordinates (approximate range check) + if not (-90 <= lat1 <= 90): + raise ValueError("lat1 must be between -90 and 90") + if not (-90 <= lat2 <= 90): + raise ValueError("lat2 must be between -90 and 90") + if not (-180 <= lon1 <= 180): + raise ValueError("lon1 must be between -180 and 180") + if not (-180 <= lon2 <= 180): + raise ValueError("lon2 must be between -180 and 180") + + # Earth radius in meters + R = 6371000 # Approximate radius of Earth + + # Convert degrees to radians + lat1_rad = math.radians(lat1) + lon1_rad = math.radians(lon1) + lat2_rad = math.radians(lat2) + lon2_rad = math.radians(lon2) + + # Calculate differences + delta_lat = lat2_rad - lat1_rad + delta_lon = lon2_rad - lon1_rad + + # Haversine formula + a = math.sin(delta_lat / 2) ** 2 + \ + math.cos(lat1_rad) * math.cos(lat2_rad) * \ + math.sin(delta_lon / 2) ** 2 + c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) + distance_m = R * c + + # Return distance in meters + return {"meters": round(distance_m, 2)} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in geo_haversine: {str(e)}") + + def otp_totp_generate(self, inputs): + import hmac + import hashlib + import base64 + import time + import struct + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + base32_secret = inputs.get("base32_secret") + step = inputs.get("step", 30) # Default to 30 seconds + digits = inputs.get("digits", 6) # Default to 6 digits + timestamp_iso = inputs.get("timestamp_iso", "") + algo = inputs.get("algo", "sha1") # Default to sha1 as current implementation only supports this + + # 类型检查 + if base32_secret is not None and not isinstance(base32_secret, str): + raise TypeError("base32_secret must be a string") + if not isinstance(step, (int, str)): + raise TypeError("step must be an integer or string") + if not isinstance(digits, (int, str)): + raise TypeError("digits must be an integer or string") + if not isinstance(timestamp_iso, str): + raise TypeError("timestamp_iso must be a string") + if not isinstance(algo, str): + raise TypeError("algo must be a string") + + # 检查必需参数 + if base32_secret is None: + raise ValueError("base32_secret parameter is required") + + try: + # Convert step and digits to appropriate types + step = int(step) + digits = int(digits) + if digits < 6 or digits > 8: + raise ValueError("Digits must be between 6 and 8") + + # Convert timestamp_iso to integer timestamp + if timestamp_iso: + import datetime + dt = datetime.datetime.fromisoformat(timestamp_iso.replace('Z', '+00:00')) + timestamp = int(dt.timestamp()) + else: + timestamp = int(time.time()) + + # Calculate counter value (T = floor(timestamp / step)) + counter = timestamp // step + + # Decode the base32 secret + # Add padding if necessary (base64 requires padding to be multiple of 8) + base32_secret = base32_secret.upper().replace(' ', '') + if len(base32_secret) % 8 != 0: + base32_secret += '=' * (8 - (len(base32_secret) % 8)) + key = base64.b32decode(base32_secret, casefold=True) + + # Calculate HMAC-SHA1 + counter_bytes = struct.pack('>Q', counter) # Big-endian 8-byte integer + hmac_hash = hmac.new(key, counter_bytes, hashlib.sha1).digest() + + # Dynamic truncation + offset = hmac_hash[-1] & 0xF + code = struct.unpack('>I', hmac_hash[offset:offset+4])[0] & 0x7FFFFFFF + + # Generate the OTP + otp = str(code % (10 ** digits)).zfill(digits) + + # Calculate remaining time until next OTP change + remaining_time = step - (timestamp % step) + + return {"totp": otp, "remaining_time": remaining_time, "time_step": step} + except ValueError as e: + if "invalid literal for int()" in str(e): + raise ValueError("step and digits must be valid integers") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in otp_totp_generate: {str(e)}") + + def unicode_norm(self, inputs): + import unicodedata + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + form = inputs.get("form", "NFC") # Default to NFC + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if form is not None and not isinstance(form, str): + raise TypeError("form must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Normalize form (NFC, NFD, NFKC, NFKD) + form = form.upper().strip() + + if form not in ['NFC', 'NFD', 'NFKC', 'NFKD']: + raise ValueError(f"Invalid normalization form: {form}. Must be one of: NFC, NFD, NFKC, NFKD") + + # Apply Unicode normalization + normalized_text = unicodedata.normalize(form, text) + + return {"text": normalized_text} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in unicode_norm: {str(e)}") + + def text_bidi_sanitize(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Bidi control characters to remove + bidi_controls = [ + '\u200E', # LEFT-TO-RIGHT MARK + '\u200F', # RIGHT-TO-LEFT MARK + '\u202A', # LEFT-TO-RIGHT EMBEDDING + '\u202B', # RIGHT-TO-LEFT EMBEDDING + '\u202C', # POP DIRECTIONAL FORMATTING + '\u202D', # LEFT-TO-RIGHT OVERRIDE + '\u202E', # RIGHT-TO-LEFT OVERRIDE + '\u2066', # LEFT-TO-RIGHT ISOLATE + '\u2067', # RIGHT-TO-LEFT ISOLATE + '\u2068', # FIRST STRONG ISOLATE + '\u2069', # POP DIRECTIONAL ISOLATE + ] + + # Remove all Bidi control characters + sanitized_text = text + for control_char in bidi_controls: + sanitized_text = sanitized_text.replace(control_char, '') + + return {"text": sanitized_text} + except Exception as e: + raise RuntimeError(f"Error in text_bidi_sanitize: {str(e)}") + + def text_xor_hex(self, inputs): + import binascii + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_a = inputs.get("hex_a") + hex_b = inputs.get("hex_b") + + # 类型检查 + if hex_a is not None and not isinstance(hex_a, str): + raise TypeError("hex_a must be a string") + if hex_b is not None and not isinstance(hex_b, str): + raise TypeError("hex_b must be a string") + + # 检查必需参数 + if hex_a is None: + raise ValueError("hex_a parameter is required") + if hex_b is None: + raise ValueError("hex_b parameter is required") + + try: + # Remove any whitespace + hex_a = hex_a.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + hex_b = hex_b.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + + # Validate hex strings + if not (all(c in "0123456789abcdefABCDEF" for c in hex_a) and len(hex_a) % 2 == 0): + raise ValueError("hex_a must be a valid hexadecimal string with even length") + if not (all(c in "0123456789abcdefABCDEF" for c in hex_b) and len(hex_b) % 2 == 0): + raise ValueError("hex_b must be a valid hexadecimal string with even length") + + # Convert hex strings to bytes + bytes_a = binascii.unhexlify(hex_a) + bytes_b = binascii.unhexlify(hex_b) + + # Make the byte arrays the same length by padding the shorter one with zeros + max_len = max(len(bytes_a), len(bytes_b)) + bytes_a = bytes_a.ljust(max_len, b'\x00') + bytes_b = bytes_b.ljust(max_len, b'\x00') + + # Perform XOR operation + result_bytes = bytes(a ^ b for a, b in zip(bytes_a, bytes_b)) + + # Convert result back to hex + result_hex = binascii.hexlify(result_bytes).decode('utf-8') + + return {"hex": result_hex} + except ValueError as e: + if "Non-hexadecimal digit found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in text_xor_hex: {str(e)}") + + def text_rotN(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + n = inputs.get("n", 0) + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + n = int(n) + except ValueError: + raise ValueError("n must be a valid integer") + + result = [] + for char in text: + if char.isupper(): + # Rotate uppercase letters + result_char = chr((ord(char) - ord('A') + n) % 26 + ord('A')) + result.append(result_char) + elif char.islower(): + # Rotate lowercase letters + result_char = chr((ord(char) - ord('a') + n) % 26 + ord('a')) + result.append(result_char) + else: + # Keep non-alphabetic characters unchanged + result.append(char) + + return {"text": ''.join(result)} + + def luhn_check(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数(支持 card_number 和 number 两个参数名) + card_number = inputs.get("number") or inputs.get("card_number") + + # 类型检查 + if card_number is not None and not isinstance(card_number, str): + raise TypeError("number must be a string") + + # 检查必需参数 + if card_number is None: + raise ValueError("number parameter is required") + + try: + # 如果输入是JSON数组或其他非数字字符串,返回该字符串本身(用于数据传递) + # 这种情况发生在DAG设计中类型不匹配时 + if card_number.startswith('[') or card_number.startswith('{'): + # 输入是JSON,直接返回原值(用于传递) + return {"valid": card_number} + + # Remove whitespace from card number + card_number = card_number.replace(" ", "").replace("-", "") + + # Check if card number is all digits + if not card_number.isdigit() or len(card_number) < 13: + return {"valid": "false"} + + # Implement Luhn algorithm + total = 0 + reverse_digits = card_number[::-1] # Reverse the number for easier processing + + for i, digit in enumerate(reverse_digits): + num = int(digit) + if i % 2 == 1: # Every second digit starting from the right (which is first in reversed string) + num *= 2 + if num > 9: + num -= 9 # Equivalent to sum of digits for 2-digit numbers + total += num + + # Check if total is divisible by 10 + is_valid = total % 10 == 0 + return {"valid": "true" if is_valid else "false"} + except Exception as e: + raise RuntimeError(f"Error in luhn_check: {str(e)}") + + def iban_validate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iban = inputs.get("iban") + + # 类型检查 + if iban is not None and not isinstance(iban, str): + raise TypeError("iban must be a string") + + # 检查必需参数 + if iban is None: + raise ValueError("iban parameter is required") + + try: + # Remove whitespace from IBAN + iban = iban.replace(" ", "") + + # Basic length and format check + if not (len(iban) >= 15 and len(iban) <= 34): + return {"valid": "False"} + + if not (iban[:2].isalpha() and iban[2:].isdigit()): + return {"valid": "False"} + + # Move first four characters to the end + rearranged = iban[4:] + iban[:4] + + # Replace letters with numbers (A=10, B=11, ..., Z=35) + numeric_iban = '' + for char in rearranged: + if char.isdigit(): + numeric_iban += char + else: + numeric_iban += str(ord(char.upper()) - ord('A') + 10) + + # Perform modulo 97 check + # Use step-by-step approach for very large numbers + remainder = 0 + for char in numeric_iban: + remainder = (remainder * 10 + int(char)) % 97 + + is_valid = remainder == 1 + return {"valid": "True" if is_valid else "False"} + except Exception as e: + raise RuntimeError(f"Error in iban_validate: {str(e)}") + + def matter_synthesizer(self, inputs): + import hashlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + blueprint = inputs.get("blueprint") + + # 类型检查 + if blueprint is not None and not isinstance(blueprint, str): + raise TypeError("blueprint must be a string") + + try: + # Get blueprint parameter as defined in interface + if blueprint is None: + blueprint = "" + + # Generate a unique item ID based on the blueprint + # This ensures the same blueprint always produces the same item + blueprint_hash = hashlib.sha256(blueprint.encode()).hexdigest()[:16] + + # Create a synthesized item with a deterministic ID based on blueprint + synthesized_item = f"synthesized_item_{blueprint_hash}" + + return {"output_slot": synthesized_item} + except Exception as e: + raise RuntimeError(f"Error in matter_synthesizer: {str(e)}") + + # --- Terminal Implementations --- + def terminal_1(self, inputs): + """ + terminal_1: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 只返回 text_output + - 只输入正确的 slot_b → 只返回 hex_output + - 同时输入正确的 slot_a 和 slot_b → 返回 item_dispenser(物品掉落) + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + # 检查哪些输入被提供了 + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值是否正确(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + expected_a = golden_inputs["slot_a"] + a_valid = str(slot_a) == str(expected_a) + + if has_b and "slot_b" in golden_inputs: + expected_b = golden_inputs["slot_b"] + b_valid = str(slot_b) == str(expected_b) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 item_dispenser + if has_a and has_b: + if a_valid and b_valid: + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 text_output + if has_a and not has_b: + if a_valid: + if "text_output" in golden_outputs: + result["text_output"] = golden_outputs["text_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 hex_output + if has_b and not has_a: + if b_valid: + if "hex_output" in golden_outputs: + result["hex_output"] = golden_outputs["hex_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def terminal_2(self, inputs): + """ + terminal_2: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 text_result + - 同时输入正确的 num1 和 num2 → 返回 hex_result 和 math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + # 检查哪些输入被提供了 + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值是否正确(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + expected_num1 = golden_inputs["num1"] + num1_valid = str(num1) == str(expected_num1) + + if has_num2 and "num2" in golden_inputs: + expected_num2 = golden_inputs["num2"] + num2_valid = str(num2) == str(expected_num2) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 hex_result 和 math_token + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 text_result + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "text_result" in golden_outputs: + result["text_result"] = golden_outputs["text_result"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def logic_terminal(self, inputs): + """ + Logic Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 返回 screen(部分输出) + - 只输入正确的 slot_b → 返回 screen 和 secondary_output + - 同时输入正确的 slot_a 和 slot_b → 返回 screen, secondary_output, item_dispenser + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + a_valid = str(slot_a) == str(golden_inputs["slot_a"]) + + if has_b and "slot_b" in golden_inputs: + b_valid = str(slot_b) == str(golden_inputs["slot_b"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出(包括 item_dispenser) + if has_a and has_b: + if a_valid and b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 screen(部分输出) + if has_a and not has_b: + if a_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 screen 和 secondary_output + if has_b and not has_a: + if b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def math_terminal(self, inputs): + """ + Math Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 result_display + - 同时输入正确的 num1 和 num2 → 返回 result_display, hex_result, math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + num1_valid = str(num1) == str(golden_inputs["num1"]) + + if has_num2 and "num2" in golden_inputs: + num2_valid = str(num2) == str(golden_inputs["num2"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 result_display + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def crypt_terminal(self, inputs): + """ + Encryption Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 plaintext → 返回 status(部分输出) + - 同时输入正确的 plaintext 和 key → 返回 status, encrypted_hex, encryption_chip + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + plaintext = inputs.get("plaintext") + key = inputs.get("key") + + has_plaintext = plaintext is not None and plaintext != "" + has_key = key is not None and key != "" + + # 验证输入值(与 golden values 比较) + plaintext_valid = False + key_valid = False + + if has_plaintext and "plaintext" in golden_inputs: + plaintext_valid = str(plaintext) == str(golden_inputs["plaintext"]) + + if has_key and "key" in golden_inputs: + key_valid = str(key) == str(golden_inputs["key"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_plaintext and has_key: + if plaintext_valid and key_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + if "encrypted_hex" in golden_outputs: + result["encrypted_hex"] = golden_outputs["encrypted_hex"] + if "encryption_chip" in golden_outputs: + result["encryption_chip"] = golden_outputs["encryption_chip"] + return result + else: + incorrect_params = [] + correct_params = [] + if not plaintext_valid: + incorrect_params.append("plaintext") + else: + correct_params.append("plaintext") + if not key_valid: + incorrect_params.append("key") + else: + correct_params.append("key") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 plaintext 且正确 → 返回 status(部分输出) + if has_plaintext and not has_key: + if plaintext_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: plaintext"} + + # 只提供 key 但没有 plaintext + if has_key and not has_plaintext: + return {"error": "plaintext required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + def sequence_terminal(self, inputs): + """ + Sequence Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 sequence → 返回 verification(部分输出) + - 同时输入正确的 sequence 和 checksum → 返回 verification, auth_code, access_card + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + sequence = inputs.get("sequence") + checksum = inputs.get("checksum") + + has_sequence = sequence is not None and sequence != "" + has_checksum = checksum is not None and checksum != "" + + # 验证输入值(与 golden values 比较) + sequence_valid = False + checksum_valid = False + + if has_sequence and "sequence" in golden_inputs: + sequence_valid = str(sequence) == str(golden_inputs["sequence"]) + + if has_checksum and "checksum" in golden_inputs: + checksum_valid = str(checksum) == str(golden_inputs["checksum"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_sequence and has_checksum: + if sequence_valid and checksum_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + if "auth_code" in golden_outputs: + result["auth_code"] = golden_outputs["auth_code"] + if "access_card" in golden_outputs: + result["access_card"] = golden_outputs["access_card"] + return result + else: + incorrect_params = [] + correct_params = [] + if not sequence_valid: + incorrect_params.append("sequence") + else: + correct_params.append("sequence") + if not checksum_valid: + incorrect_params.append("checksum") + else: + correct_params.append("checksum") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 sequence 且正确 → 返回 verification(部分输出) + if has_sequence and not has_checksum: + if sequence_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: sequence"} + + # 只提供 checksum 但没有 sequence + if has_checksum and not has_sequence: + return {"error": "sequence required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + # --- Additional File Tools --- + + def zip_unzip_file(self, inputs): + """ZIP 解压文件工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def zip_unzip_item(self, inputs): + """ZIP 解压道具工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def code_py_exec(self, inputs): + """Python 代码执行工具 + + 这是一个真实执行的工具,在 DAG 生成阶段和运行时评测阶段都会执行代码。 + 输入: code (Python 代码字符串) + 输出: stdout (标准输出,包含执行结果和错误信息) + + 特殊行为: + - 如果代码定义了 main() 函数,会自动调用它 + - 如果执行出错,错误信息会包含在 stdout 中 + """ + code = inputs.get("code", "") + + if not code: + return {"stdout": "Error: No code provided"} + + try: + # 创建一个受限的执行环境 + import io + import sys + + # 捕获标准输出和标准错误 + old_stdout = sys.stdout + old_stderr = sys.stderr + sys.stdout = io.StringIO() + sys.stderr = io.StringIO() + + # 执行代码 + exec_globals = {"__builtins__": __builtins__} + exec_locals = {} + exec(code, exec_globals, exec_locals) + + # 如果定义了 main() 函数,自动调用它 + if 'main' in exec_locals and callable(exec_locals['main']): + exec_locals['main']() + + # 获取输出 + stdout_value = sys.stdout.getvalue() + stderr_value = sys.stderr.getvalue() + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 合并 stdout 和 stderr + output = stdout_value + if stderr_value: + output += ("\n" if output else "") + f"[stderr] {stderr_value}" + + # 如果没有任何输出,尝试返回 result 变量的值 + if not output: + result = exec_locals.get("_result") or exec_locals.get("result") + if result is not None: + output = str(result) + + return {"stdout": output if output else "(no output)"} + + except Exception as e: + # 恢复标准输出和错误输出 + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 返回错误信息 + return {"stdout": f"Error: {type(e).__name__}: {str(e)}"} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-ad399fad/environment/puzzle/worker.Dockerfile b/tasks/agentescape-25-skeleton-ad399fad/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-25-skeleton-ad399fad/environment/puzzle/worker.Dockerfile @@ -0,0 +1,8 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends libseccomp2 && rm -rf /var/lib/apt/lists/* +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY worker.py child.py /app/ +COPY upstream/simulator.py /app/simulator.py +CMD ["uvicorn", "worker:app", "--host", "0.0.0.0", "--port", "8001", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-25-skeleton-ad399fad/environment/puzzle/worker.py b/tasks/agentescape-25-skeleton-ad399fad/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-25-skeleton-ad399fad/environment/puzzle/worker.py @@ -0,0 +1,73 @@ +"""Stateless Python tool worker. Never receives a scenario or reference values.""" + +import json +import os +import signal +import subprocess +import sys +import tempfile +import threading + +from fastapi import FastAPI +from pydantic import BaseModel, ConfigDict + +app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) +lock = threading.Lock() + + +class Execution(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + code: str + + +@app.get("/health") +def health(): + return {"ok": True} + + +@app.post("/execute") +def execute(request: Execution): + if len(request.code.encode()) > 65536: + return {"stdout": "Error: code exceeds 64 KiB limit"} + with lock, tempfile.TemporaryDirectory(prefix="escape-code-") as directory: + os.chown(directory, 65534, 65534) + with tempfile.TemporaryFile() as output: + process = subprocess.Popen( + [sys.executable, "-I", "/app/child.py"], + stdin=subprocess.PIPE, + stdout=output, + stderr=subprocess.DEVNULL, + cwd=directory, + user=65534, + group=65534, + extra_groups=[], + start_new_session=True, + env={"PATH": "/usr/local/bin:/usr/bin:/bin"}, + ) + try: + process.communicate( + json.dumps({"code": request.code}).encode(), timeout=5 + ) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + return {"stdout": "Error: Python execution timed out"} + finally: + # Also remove children still in the process group after normal exit. + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + output.seek(0) + value = output.read(65537) + if len(value) > 65536 or process.returncode != 0: + return { + "stdout": "Error: Python execution exceeded a resource limit or failed" + } + try: + result = json.loads(value) + if not isinstance(result.get("stdout"), str): + raise ValueError("Invalid worker response") + return result + except (ValueError, AttributeError): + return {"stdout": "Error: Python execution returned invalid output"} diff --git a/tasks/agentescape-25-skeleton-ad399fad/instruction.md b/tasks/agentescape-25-skeleton-ad399fad/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-25-skeleton-ad399fad/instruction.md @@ -0,0 +1,18 @@ +# Escape the room + +Discover the victory string and submit it with `escape submit-answer`. +Start with `escape observe`. This returns the room, available information, visible entities, and victory node ID. + +Use these commands (JSON responses): + +```sh +escape investigate NODE_ID +escape tool-call NODE_ID --arguments-json '{"parameter": "value"}' +escape use-item NODE_ID --arguments-json '{"parameter": "value"}' +escape submit-answer 'exact victory string' +escape state +``` + +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. + +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. diff --git a/tasks/agentescape-25-skeleton-ad399fad/solution/oracle.py b/tasks/agentescape-25-skeleton-ad399fad/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-25-skeleton-ad399fad/solution/oracle.py @@ -0,0 +1,133 @@ +"""Reference solver: use trusted inputs, but obtain the answer through public actions.""" + +import json +import urllib.request +from pathlib import Path + + +def http_action(base_url, payload): + request = urllib.request.Request( + base_url + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(request, timeout=30) as response: + return json.load(response) + + +def solve(scenario, act, observe): + nodes = {node["id"]: node for node in scenario["nodes"]} + visible = {entity["id"] for entity in observe["available_entities"]} + solved = set() + seen_outputs = {} + action_count = 0 + + def call(payload): + nonlocal action_count + action_count += 1 + response = act(payload) + visible.update(entity["id"] for entity in response.get("newly_revealed", [])) + if ( + response.get("episode", {}).get("termination_reason") + == "infrastructure_error" + ): + raise RuntimeError("Infrastructure failure") + return response + + for _round in range(len(nodes) + 2): + progress = False + for node_id, node in nodes.items(): + if node_id not in visible or node_id in solved: + continue + # Preserve graph order for data inputs; trigger/drop edges express visibility. + predecessors = [ + edge["source_id"] + for edge in scenario["edges"] + if edge["target_id"] == node_id + and edge["connection_type"] not in ("Item", "Hidden_Item") + ] + if any(pred not in solved for pred in predecessors): + continue + info = call({"action": "investigate", "node_id": node_id}) + if not info.get("ok"): + raise RuntimeError(f"Investigation failed: {node_id}: {info}") + inputs = { + port["name"]: port["value"] + for port in node.get("inputs", []) + if "value" in port + } + if node["type"] == "Tool": + result = call( + {"action": "tool_call", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok") or result.get("output_values", {}).get("error"): + raise RuntimeError(f"Tool failed: {node_id}: {result}") + output = result.get("output_values", {}) + if node.get("template_id") in ("terminal_1", "terminal_2"): + slots = { + port["name"]: inputs[port["name"]] + for port in node["inputs"] + if port["type"] not in ("Item", "Hidden_Item") + and port["name"] in inputs + } + triggers = { + key: value for key, value in inputs.items() if key not in slots + } + for key, value in slots.items(): + partial = call( + { + "action": "tool_call", + "node_id": node_id, + "arguments": {**triggers, key: value}, + } + ) + if partial.get("ok"): + output.update(partial.get("output_values", {})) + # HIDDEN_ITEM tool drops only occur on subsequent investigation. + call({"action": "investigate", "node_id": node_id}) + elif info.get("required_inputs"): + result = call( + {"action": "use_item", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok"): + raise RuntimeError(f"Item failed: {node_id}: {result}") + output = result.get("content") + else: + output = info.get("content") + seen_outputs[node_id] = output + solved.add(node_id) + progress = True + win_id = scenario["metadata"]["win_node_id"] + if win_id in solved and (len(solved) == len(nodes) or not progress): + outputs = seen_outputs[win_id] + if not outputs: + raise RuntimeError(f"Victory node returned no output: {win_id}") + # Upstream grades its first stored output port, independent of response order. + victory_port = next( + port["name"] for port in nodes[win_id]["outputs"] if "value" in port + ) + answer = outputs[victory_port] if isinstance(outputs, dict) else outputs + result = call({"action": "submit_answer", "answer": answer}) + if not result.get("is_win"): + raise RuntimeError(f"Victory submission failed: {result}") + return {"won": True, "actions": action_count, "visited_nodes": len(solved)} + if not progress: + raise RuntimeError(f"No progress: visible={visible}, solved={solved}") + raise RuntimeError("Reference solver exceeded graph traversal limit") + + +if __name__ == "__main__": + import os + + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000") + with urllib.request.urlopen(base + "/observation", timeout=20) as response: + observation = json.load(response) + print( + json.dumps( + solve( + json.loads(Path("/solution/scenario.json").read_text()), + lambda payload: http_action(base, payload), + observation, + ) + ) + ) diff --git a/tasks/agentescape-25-skeleton-ad399fad/solution/scenario.json b/tasks/agentescape-25-skeleton-ad399fad/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..6d90dba3a72244d687b0e5048af2679087185c3d --- /dev/null +++ b/tasks/agentescape-25-skeleton-ad399fad/solution/scenario.json @@ -0,0 +1,1449 @@ +{ + "metadata": { + "total_nodes": 25, + "total_edges": 37, + "win_node_id": "hex_encode", + "win_condition": { + "type": "tool_output", + "node_id": "hex_encode", + "output_port": "hex", + "output_type": "Hex_String", + "description": "Execute Text to Hex Encoder and get the output from port 'hex'" + }, + "source_init": { + "source_nodes": [ + "calc_modexp", + "graph_shortest_path", + "calc_modexp_bd8a", + "calc_bigmul", + "terminal_1", + "calc_gcd", + "calc_inv_mod_1089", + "terminal_1_b192", + "calc_inv_mod_fa78", + "item_15", + "luhn_check" + ], + "by_node": { + "calc_modexp": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "base": { + "type": "Big_Int", + "description": "Base" + } + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "Graph JSON file ID" + }, + "dst": { + "type": "Text_Generic", + "description": "Destination node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "calc_modexp_bd8a": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "calc_bigmul": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First large integer" + }, + "b": { + "type": "Big_Int", + "description": "Second large integer" + } + }, + "init_outputs": {} + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": {}, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + } + } + }, + "calc_gcd": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "b": { + "type": "Big_Int", + "description": "Second integer" + } + }, + "init_outputs": {} + }, + "calc_inv_mod_1089": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "Integer a" + }, + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "terminal_1_b192": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": {}, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + } + } + }, + "calc_inv_mod_fa78": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "Integer a" + }, + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "item_15": { + "node_name": "", + "node_type": "Item", + "template_id": "item_15", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Text_Generic", + "description": "Timezone text" + } + } + }, + "luhn_check": { + "node_name": "Luhn Checker", + "node_type": "Tool", + "template_id": "luhn_check", + "init_inputs": { + "number": { + "type": "Text_Generic", + "description": "Number string" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "calc_modexp": { + "init_inputs": { + "base": "17" + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": { + "file_id": "network_graph.json", + "dst": "target_node_88" + }, + "init_outputs": { + "path": "[\"node_1\", \"node_2\", \"node_3\", \"node_4\", \"target_node_88\"]", + "cost": "345678" + } + }, + "calc_modexp_bd8a": { + "init_inputs": { + "mod": "456787" + }, + "init_outputs": {} + }, + "calc_bigmul": { + "init_inputs": { + "a": "47382910475839201928", + "b": "58392019485739201847" + }, + "init_outputs": {} + }, + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "Data successfully processed in terminal slot A.", + "hex_output": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + } + }, + "calc_gcd": { + "init_inputs": { + "b": "38475920193847583920" + }, + "init_outputs": {} + }, + "calc_inv_mod_1089": { + "init_inputs": { + "a": "83940582918374659201", + "mod": "876541" + }, + "init_outputs": {} + }, + "terminal_1_b192": { + "init_inputs": {}, + "init_outputs": { + "text_output": "Terminal B operational state confirmed and verified.", + "hex_output": "112233445566778899aabbccddeeff00" + } + }, + "calc_inv_mod_fa78": { + "init_inputs": { + "a": "49583029182746583920", + "mod": "100003" + }, + "init_outputs": {} + }, + "item_15": { + "init_inputs": {}, + "init_outputs": { + "content": "America/Los_Angeles" + } + }, + "luhn_check": { + "init_inputs": { + "number": "45327189394028" + }, + "init_outputs": {} + } + }, + "intro_narrative": "Welcome to the lost sanctum of Archmage Vaelen. For centuries, this floating tower has been hidden by powerful enchantments. As a seeker of arcane knowledge, you have breached the outer wards, but the true prize—a legendary spell scroll—remains sealed by a complex web of magical devices. The artifacts in this room are intertwined, their energies feeding into one another. You must explore the sanctum, master these archaic tools, and trace the flow of mana to unravel the grand puzzle. Your ultimate goal is to decipher the final incantation before the sanctum crumbles into the aether.", + "narrative_style": "fantasy" + }, + "nodes": [ + { + "id": "hex_encode", + "name": "Text to Hex Encoder", + "description": "Encode UTF-8 text to hex.", + "type": "Tool", + "template_id": "hex_encode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "\u0003rH" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Encoded hex", + "value": "037248" + } + ], + "narrative": "This is The Final Translation Scroll. It requires input from The Grand Archmage's Deciphering Orb to reveal the ultimate secret." + }, + { + "id": "crypto_rsa_decrypt_hex", + "name": "RSA Decrypt", + "description": "RSA decrypt (hex cipher) with n,d (decimal).", + "type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex_cipher", + "type": "Hex_String", + "description": "Ciphertext (Hex)", + "value": "112233445566778899aabbccddeeff00" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Modulus n", + "value": "283032" + }, + { + "name": "d", + "type": "Big_Int", + "description": "Private exponent d", + "value": "283032" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decrypted text", + "value": "\u0003rH" + } + ], + "narrative": "This is The Grand Archmage's Deciphering Orb. It requires inputs from The Altar of Reversal, The Enchanted Astrolabe, and The Oracle's Basin to break the ancient ciphers." + }, + { + "id": "calc_inv_mod", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "283032" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "36963" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "283032" + } + ], + "narrative": "This is The Altar of Reversal. It requires inputs from The Elemental Transmuter and The Enchanted Astrolabe to flip the magical polarity." + }, + { + "id": "calc_modexp", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "17" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "345678" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "370159" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "283032" + } + ], + "init": { + "inputs": { + "base": "17" + }, + "outputs": {} + }, + "narrative": "This is The Enchanted Astrolabe. It requires inputs from The Map of Ley Lines and The Obsidian Focusing Crystal to align the celestial forces." + }, + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "network_graph.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "America/Los_Angeles" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "target_node_88" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"node_1\", \"node_2\", \"node_3\", \"node_4\", \"target_node_88\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "345678" + } + ], + "init": { + "inputs": { + "file_id": "network_graph.json", + "dst": "target_node_88" + }, + "outputs": { + "path": "[\"node_1\", \"node_2\", \"node_3\", \"node_4\", \"target_node_88\"]", + "cost": "345678" + } + }, + "narrative": "This is The Map of Ley Lines. It requires input from The Star Parchment to chart the magical paths across the sanctum." + }, + { + "id": "num_base_convert", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "36963" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "10059" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "370159" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "36963" + } + ], + "narrative": "This is The Elemental Transmuter. It requires inputs from The Obsidian Focusing Crystal, The Mirror of Reflection, and The Stone of Inversion to shift the arcane states." + }, + { + "id": "calc_modexp_bd8a", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "72966" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "2766783831796238835646601554020183561016" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "456787" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "370159" + } + ], + "init": { + "inputs": { + "mod": "456787" + }, + "outputs": {} + }, + "narrative": "This is The Obsidian Focusing Crystal. It requires inputs from The Loom of Multiplication and The Forge of Amplification to concentrate raw mana." + }, + { + "id": "container_3", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_3", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Big_Int", + "description": "Fingerprint Hash", + "value": "72966" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is The Silver Reliquary. It requires input from The Forge of Amplification to unlock its magical seals." + }, + { + "id": "calc_inv_mod_148f", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "36963" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "43264" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "10059" + } + ], + "narrative": "This is The Mirror of Reflection. It requires inputs from The Celestial Orrery and The Stone of Inversion to reveal hidden truths." + }, + { + "id": "calc_bigmul", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "47382910475839201928" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "58392019485739201847" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "2766783831796238835646601554020183561016" + } + ], + "init": { + "inputs": { + "a": "47382910475839201928", + "b": "58392019485739201847" + }, + "outputs": {} + }, + "narrative": "An arcane loom that weaves numbers and spells together into much larger, intricate patterns." + }, + { + "id": "calc_modexp_3695", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "2766783831796238835646601554020183561016" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "2" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "283032" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "43264" + } + ], + "narrative": "This is The Celestial Orrery. It requires inputs from The Loom of Multiplication, The Enchanted Astrolabe, and The Scale of Balance to track the cosmic movements." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A mysterious rune stone vibrating with latent, ancient energy." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "false" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "72966" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Data successfully processed in terminal slot A." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "Data successfully processed in terminal slot A.", + "hex_output": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + } + }, + "narrative": "This is The Golem Control Pedestal. It requires inputs from The Forge of Amplification and The Truth Seeker's Eye to command the sanctum's guardians." + }, + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "345678" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "38475920193847583920" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "2" + } + ], + "init": { + "inputs": { + "b": "38475920193847583920" + }, + "outputs": {} + }, + "narrative": "This is The Scale of Balance. It requires input from The Map of Ley Lines to find the harmonic resonance between magics." + }, + { + "id": "calc_bigmul_a22e", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "2" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "36483" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "72966" + } + ], + "narrative": "This is The Forge of Amplification. It requires inputs from The Scale of Balance and The Shadow Pendulum to empower the elemental energies." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A delicate, humming amulet that seems to contain the essence of fractured time." + }, + { + "id": "calc_inv_mod_1089", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "83940582918374659201" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "876541" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "36963" + } + ], + "init": { + "inputs": { + "a": "83940582918374659201", + "mod": "876541" + }, + "outputs": {} + }, + "narrative": "An ancient stone engraved with paradoxical runes that seem to contradict themselves." + }, + { + "id": "terminal_1_b192", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "[\"node_1\", \"node_2\", \"node_3\", \"node_4\", \"target_node_88\"]" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "36963" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Terminal B operational state confirmed and verified." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "112233445566778899aabbccddeeff00" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "Terminal B operational state confirmed and verified.", + "hex_output": "112233445566778899aabbccddeeff00" + } + }, + "narrative": "This is The Oracle's Basin. It requires inputs from The Map of Ley Lines and The Stone of Inversion to project visions of the past." + }, + { + "id": "calc_inv_mod_fa78", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "49583029182746583920" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "100003" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "36483" + } + ], + "init": { + "inputs": { + "a": "49583029182746583920", + "mod": "100003" + }, + "outputs": {} + }, + "narrative": "A mystical pendulum swinging in a rhythm that defies the natural laws of motion." + }, + { + "id": "container_3_d78b", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_3", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Big_Int", + "description": "Fingerprint Hash", + "value": "2766783831796238835646601554020183561016" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is The Golden Chalice. It requires input from The Loom of Multiplication to break its warding spell." + }, + { + "id": "item_8_5a2c", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A dark gem that constantly whispers forgotten names and forbidden spells." + }, + { + "id": "item_15", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_15", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Text_Generic", + "description": "Timezone text", + "value": "America/Los_Angeles" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "America/Los_Angeles" + } + }, + "narrative": "An illuminated parchment depicting the night sky as it appeared ten thousand years ago." + }, + { + "id": "luhn_check", + "name": "Luhn Checker", + "description": "Luhn validity of number string.", + "type": "Tool", + "template_id": "luhn_check", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "number", + "type": "Text_Generic", + "description": "Number string", + "value": "45327189394028" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "false" + } + ], + "init": { + "inputs": { + "number": "45327189394028" + }, + "outputs": {} + }, + "narrative": "A magical eye artifact designed to distinguish true cosmic constants from illusions and falsehoods." + }, + { + "id": "item_8_fb5f", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A permanently frozen shard of magical ice that chills the air around it." + }, + { + "id": "item_8_f626", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A burning shard of volcanic glass that emits a perpetual, warming glow." + } + ], + "edges": [ + { + "source_id": "crypto_rsa_decrypt_hex", + "target_id": "hex_encode", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "text" + }, + { + "source_id": "calc_inv_mod", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "n" + }, + { + "source_id": "calc_modexp", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "d" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "exp" + }, + { + "source_id": "num_base_convert", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "mod" + }, + { + "source_id": "calc_modexp_bd8a", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "to_base" + }, + { + "source_id": "calc_modexp", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "a" + }, + { + "source_id": "calc_modexp_bd8a", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "mod" + }, + { + "source_id": "container_3", + "target_id": "calc_inv_mod", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "calc_inv_mod_148f", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "from_base" + }, + { + "source_id": "calc_bigmul", + "target_id": "calc_modexp_bd8a", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "exp" + }, + { + "source_id": "calc_modexp_3695", + "target_id": "calc_inv_mod_148f", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "mod" + }, + { + "source_id": "item_8", + "target_id": "container_3", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "calc_bigmul", + "target_id": "calc_modexp_3695", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "base" + }, + { + "source_id": "calc_modexp", + "target_id": "calc_modexp_3695", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "mod" + }, + { + "source_id": "terminal_1", + "target_id": "calc_bigmul", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "trigger_item" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_modexp_3695", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "exp" + }, + { + "source_id": "calc_bigmul_a22e", + "target_id": "container_3", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "fingerprint_input" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "a" + }, + { + "source_id": "calc_bigmul_a22e", + "target_id": "calc_modexp_bd8a", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "base" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_bigmul_a22e", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "a" + }, + { + "source_id": "calc_bigmul_a22e", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "slot_b" + }, + { + "source_id": "item_16", + "target_id": "calc_bigmul_a22e", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "calc_inv_mod_1089", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "s" + }, + { + "source_id": "terminal_1_b192", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "source_tool" + }, + { + "source_id": "graph_shortest_path", + "target_id": "terminal_1_b192", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "slot_a" + }, + { + "source_id": "calc_inv_mod_fa78", + "target_id": "calc_bigmul_a22e", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "b" + }, + { + "source_id": "container_3_d78b", + "target_id": "calc_modexp_bd8a", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "calc_bigmul", + "target_id": "container_3_d78b", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "fingerprint_input" + }, + { + "source_id": "item_8_5a2c", + "target_id": "calc_inv_mod_fa78", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "item_15", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "content", + "target_port": "src" + }, + { + "source_id": "luhn_check", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "slot_a" + }, + { + "source_id": "calc_inv_mod_1089", + "target_id": "terminal_1_b192", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "slot_b" + }, + { + "source_id": "terminal_1_b192", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Hex_String", + "source_port": "hex_output", + "target_port": "hex_cipher" + }, + { + "source_id": "calc_inv_mod_1089", + "target_id": "calc_inv_mod_148f", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "a" + }, + { + "source_id": "item_8_fb5f", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_8_f626", + "target_id": "container_3_d78b", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-ad399fad/solution/solve.sh b/tasks/agentescape-25-skeleton-ad399fad/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-25-skeleton-ad399fad/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-25-skeleton-ad399fad/task.toml b/tasks/agentescape-25-skeleton-ad399fad/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e57c63a76f8f2264cd08302254e805e157348b87 --- /dev/null +++ b/tasks/agentescape-25-skeleton-ad399fad/task.toml @@ -0,0 +1,38 @@ +schema_version = "1.4" +source = "https://github.com/AGI-Eval-Official/Repo-of-AgentEscapeBench" + +[[artifacts]] +source = "/evidence/final.json" +service = "puzzle" + +[[artifacts]] +source = "/evidence/trace.jsonl" +service = "puzzle" + +[task] +name = "edbeeching/agentescape-25-skeleton-ad399fad" +version = "0.1.0" + +[metadata] +difficulty = 25 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "a13be2c936ca30d050a7ff14fc3b90f4ddc23a23d7d3a9d19c43fb47639381b5" +protocol = "harbor-cli-action-budget-v1" +max_actions = 500 + +[agent] +timeout_sec = 1200 + +[environment] +build_timeout_sec = 900 +cpus = 1 +memory_mb = 1024 + +[verifier] +environment_mode = "separate" +timeout_sec = 60 + +[[verifier.collect]] +service = "puzzle" +command = "python -I /app/export.py" +timeout_sec = 15 diff --git a/tasks/agentescape-25-skeleton-ad399fad/tests/Dockerfile b/tasks/agentescape-25-skeleton-ad399fad/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-25-skeleton-ad399fad/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-25-skeleton-ad399fad/tests/expected.json b/tasks/agentescape-25-skeleton-ad399fad/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..a8459eb79d6a2354d82e17ec674f66f1edfda54f --- /dev/null +++ b/tasks/agentescape-25-skeleton-ad399fad/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "a13be2c936ca30d050a7ff14fc3b90f4ddc23a23d7d3a9d19c43fb47639381b5", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-ad399fad/tests/grade.py b/tasks/agentescape-25-skeleton-ad399fad/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-25-skeleton-ad399fad/tests/grade.py @@ -0,0 +1,21 @@ +"""Grade only Harbor-collected sidecar evidence in a fresh verifier container.""" + +import json +from pathlib import Path + +expected = json.loads(Path("/tests/expected.json").read_text()) +state = json.loads(Path("/evidence/final.json").read_text()) +assert state["collected_from_live_service"] is True, "Missing trusted service export" +assert state["scenario_sha256"] == expected["scenario_sha256"], ( + "Wrong scenario evidence" +) +assert state["max_actions"] == expected["max_actions"], "Wrong budget" +assert type(state["won"]) is bool +assert 0 <= state["action_count"] <= state["max_actions"] +assert state["termination_reason"] != "infrastructure_error", ( + "Infrastructure failure is not a puzzle failure" +) +assert not state["won"] or state["termination_reason"] == "success" +Path("/logs/verifier").mkdir(parents=True, exist_ok=True) +Path("/logs/verifier/state.json").write_text(json.dumps(state, indent=2)) +Path("/logs/verifier/reward.txt").write_text("1.0\n" if state["won"] else "0.0\n") diff --git a/tasks/agentescape-25-skeleton-ad399fad/tests/test.sh b/tasks/agentescape-25-skeleton-ad399fad/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-25-skeleton-ad399fad/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-25-skeleton-b5fbf361/environment/Dockerfile b/tasks/agentescape-25-skeleton-b5fbf361/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-25-skeleton-b5fbf361/environment/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-25-skeleton-b5fbf361/environment/agent/Dockerfile b/tasks/agentescape-25-skeleton-b5fbf361/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-25-skeleton-b5fbf361/environment/agent/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-25-skeleton-b5fbf361/environment/agent/cli.py b/tasks/agentescape-25-skeleton-b5fbf361/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-25-skeleton-b5fbf361/environment/agent/cli.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Public agent client; depends only on the Python standard library.""" + +import argparse +import json +import os +import sys +import urllib.error +import urllib.request + + +def main(): + parser = argparse.ArgumentParser(description="Interact with the escape room") + parser.add_argument( + "action", + choices=[ + "observe", + "state", + "investigate", + "tool-call", + "use-item", + "submit-answer", + ], + ) + parser.add_argument("value", nargs="?") + parser.add_argument("--arguments-json", default="{}") + args = parser.parse_args() + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000").rstrip("/") + if args.action in ("observe", "state"): + request = urllib.request.Request( + base + ("/observation" if args.action == "observe" else "/state") + ) + else: + if args.value is None: + parser.error("node ID or answer is required") + payload = {"action": args.action.replace("-", "_")} + if args.action == "submit-answer": + payload["answer"] = args.value + else: + payload["node_id"] = args.value + if args.action in ("tool-call", "use-item"): + payload["arguments"] = json.loads(args.arguments_json) + request = urllib.request.Request( + base + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=30) as response: + print(json.dumps(json.load(response), ensure_ascii=False)) + except (urllib.error.URLError, ValueError) as exc: + print(json.dumps({"ok": False, "error": str(exc)})) + sys.exit(2) + + +if __name__ == "__main__": + main() diff --git a/tasks/agentescape-25-skeleton-b5fbf361/environment/docker-compose.yaml b/tasks/agentescape-25-skeleton-b5fbf361/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..49f6969f1173f7461343de27e99a6c6b8b56d832 --- /dev/null +++ b/tasks/agentescape-25-skeleton-b5fbf361/environment/docker-compose.yaml @@ -0,0 +1,50 @@ +services: + main: + image: agentescapebench-agent:aab05a0a9ddb + build: + context: ./agent + networks: [default, puzzle] + security_opt: [no-new-privileges:true] + depends_on: + puzzle: + condition: service_healthy + puzzle: + image: agentescapebench-puzzle:agentescape-25-skeleton-b5fbf361-aab05a0a9ddb + build: + context: ./puzzle + networks: [puzzle, execution] + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 512m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"] + interval: 1s + timeout: 3s + retries: 30 + depends_on: + worker: + condition: service_healthy + worker: + image: agentescapebench-worker:aab05a0a9ddb + build: + context: ./puzzle + dockerfile: worker.Dockerfile + networks: [execution] + read_only: true + tmpfs: ["/tmp:size=64m,mode=1777"] + cap_drop: [ALL] + cap_add: [SETUID, SETGID, KILL, CHOWN, DAC_OVERRIDE] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 384m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8001/health')"] + interval: 1s + timeout: 3s + retries: 30 +networks: + puzzle: + internal: true + execution: + internal: true diff --git a/tasks/agentescape-25-skeleton-b5fbf361/environment/puzzle/Dockerfile b/tasks/agentescape-25-skeleton-b5fbf361/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-25-skeleton-b5fbf361/environment/puzzle/Dockerfile @@ -0,0 +1,9 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY upstream /app/upstream +COPY service.py export.py /app/ +COPY scenario.json /private/scenario.json +ENV SCENARIO_PATH=/private/scenario.json EVIDENCE_DIR=/evidence WORKER_URL=http://worker:8001 MAX_ACTIONS=500 +CMD ["uvicorn", "service:create_app", "--factory", "--host", "0.0.0.0", "--port", "8000", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-25-skeleton-b5fbf361/environment/puzzle/child.py b/tasks/agentescape-25-skeleton-b5fbf361/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-25-skeleton-b5fbf361/environment/puzzle/child.py @@ -0,0 +1,59 @@ +"""Run the original Python tool after reducing privileges and blocking networking.""" + +import ctypes +import errno +import json +import resource +import sys + +resource.setrlimit(resource.RLIMIT_CPU, (3, 3)) +resource.setrlimit(resource.RLIMIT_AS, (256 * 1024 * 1024, 256 * 1024 * 1024)) +resource.setrlimit(resource.RLIMIT_FSIZE, (65536, 65536)) +resource.setrlimit(resource.RLIMIT_NOFILE, (32, 32)) +resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + +# Filters survive fork/exec. Fail closed if seccomp cannot be loaded. +lib = ctypes.CDLL("libseccomp.so.2", use_errno=True) +lib.seccomp_init.argtypes = [ctypes.c_uint32] +lib.seccomp_init.restype = ctypes.c_void_p +lib.seccomp_rule_add.argtypes = [ + ctypes.c_void_p, + ctypes.c_uint32, + ctypes.c_int, + ctypes.c_uint, +] +lib.seccomp_syscall_resolve_name.argtypes = [ctypes.c_char_p] +lib.seccomp_load.argtypes = [ctypes.c_void_p] +lib.seccomp_release.argtypes = [ctypes.c_void_p] +ctx = lib.seccomp_init(0x7FFF0000) # SCMP_ACT_ALLOW +if not ctx: + raise RuntimeError("Cannot initialize execution isolation") +try: + for name in ( + "socket", + "socketpair", + "connect", + "ptrace", + "process_vm_readv", + "process_vm_writev", + "mount", + "unshare", + "setns", + "bpf", + ): + number = lib.seccomp_syscall_resolve_name(name.encode()) + if ( + number >= 0 + and lib.seccomp_rule_add(ctx, 0x00050000 | errno.EPERM, number, 0) != 0 + ): + raise RuntimeError("Cannot install execution isolation rule") + if lib.seccomp_load(ctx) != 0: + raise RuntimeError("Cannot activate execution isolation") +finally: + lib.seccomp_release(ctx) + +sys.path.insert(0, "/app") +from simulator import ToolSimulator # noqa: E402 + +request = json.load(sys.stdin) +json.dump(ToolSimulator().code_py_exec(request), sys.stdout) diff --git a/tasks/agentescape-25-skeleton-b5fbf361/environment/puzzle/export.py b/tasks/agentescape-25-skeleton-b5fbf361/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-25-skeleton-b5fbf361/environment/puzzle/export.py @@ -0,0 +1,13 @@ +"""Harbor invokes this inside the puzzle service after stopping the agent.""" + +import json +import pathlib +import urllib.request + +with urllib.request.urlopen("http://127.0.0.1:8000/state", timeout=10) as response: + state = json.load(response) +state["collected_from_live_service"] = True +target = pathlib.Path("/evidence/final.json") +temp = target.with_suffix(".tmp") +temp.write_text(json.dumps(state)) +temp.replace(target) diff --git a/tasks/agentescape-25-skeleton-b5fbf361/environment/puzzle/requirements.txt b/tasks/agentescape-25-skeleton-b5fbf361/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-25-skeleton-b5fbf361/environment/puzzle/requirements.txt @@ -0,0 +1,57 @@ +annotated-doc==0.0.5 + # via fastapi +annotated-types==0.8.0 + # via pydantic +anyio==4.16.0 + # via starlette +certifi==2026.10.23 + # via requests +cffi==2.1.1 ; platform_python_implementation != 'PyPy' + # via cryptography +charset-normalizer==3.5.2 + # via requests +click==8.5.0 + # via uvicorn +cryptography==50.0.2 + # via agentescapebench-harbor +fastapi==0.162.0 + # via agentescapebench-harbor +h11==0.16.0 + # via uvicorn +idna==3.20 + # via + # anyio + # requests +opentelemetry-api==1.45.2 + # via fastapi +pycparser==3.12 ; implementation_name != 'PyPy' and platform_python_implementation != 'PyPy' + # via cffi +pydantic==2.14.2 + # via + # agentescapebench-harbor + # fastapi +pydantic-core==2.50.2 + # via pydantic +pytz==2025.2 + # via agentescapebench-harbor +requests==2.34.2 + # via agentescapebench-harbor +starlette==1.10.0 + # via fastapi +typing-extensions==4.16.0 + # via + # anyio + # fastapi + # opentelemetry-api + # pydantic + # pydantic-core + # starlette + # typing-inspection +typing-inspection==0.4.4 + # via + # fastapi + # pydantic +urllib3==2.8.0 + # via requests +uvicorn==0.54.0 + # via agentescapebench-harbor diff --git a/tasks/agentescape-25-skeleton-b5fbf361/environment/puzzle/scenario.json b/tasks/agentescape-25-skeleton-b5fbf361/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..f8cdcf95bd7be5df6e8fcecc6f546cd8e28606e6 --- /dev/null +++ b/tasks/agentescape-25-skeleton-b5fbf361/environment/puzzle/scenario.json @@ -0,0 +1,1558 @@ +{ + "metadata": { + "total_nodes": 25, + "total_edges": 28, + "win_node_id": "zip_unzip_item", + "win_condition": { + "type": "tool_output", + "node_id": "zip_unzip_item", + "output_port": "item", + "output_type": "Item", + "description": "Execute Zip Unzipper and get the output from port 'item'" + }, + "source_init": { + "source_nodes": [ + "zip_unzip_item", + "zip_unzip_file", + "crypto_rsa_decrypt_hex", + "num_base_convert", + "calc_gcd", + "calc_inv_mod_9968", + "zip_unzip_file_f293", + "zip_unzip_file_148f", + "container_3", + "calc_modexp", + "calc_gcd_d1ba", + "terminal_1", + "num_base_convert_0b44", + "time_convert", + "item_10", + "item_4", + "calc_bigmul", + "calc_gcd_232c" + ], + "by_node": { + "zip_unzip_item": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_item", + "init_inputs": {}, + "init_outputs": { + "item": { + "type": "Item", + "description": "item in the zip" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "crypto_rsa_decrypt_hex": { + "node_name": "RSA Decrypt", + "node_type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "init_inputs": { + "n": { + "type": "Big_Int", + "description": "Modulus n" + } + }, + "init_outputs": {} + }, + "num_base_convert": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "s": { + "type": "Big_Int", + "description": "Input integer value" + }, + "to_base": { + "type": "Big_Int", + "description": "To base" + } + }, + "init_outputs": {} + }, + "calc_gcd": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "b": { + "type": "Big_Int", + "description": "Second integer" + } + }, + "init_outputs": {} + }, + "calc_inv_mod_9968": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "zip_unzip_file_f293": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "zip_unzip_file_148f": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "container_3": { + "node_name": "", + "node_type": "Item", + "template_id": "container_3", + "init_inputs": { + "fingerprint_input": { + "type": "Big_Int", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + }, + "calc_modexp": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "exp": { + "type": "Big_Int", + "description": "Exponent" + } + }, + "init_outputs": {} + }, + "calc_gcd_d1ba": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "b": { + "type": "Big_Int", + "description": "Second integer" + } + }, + "init_outputs": {} + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": { + "slot_a": { + "type": "Text_Generic", + "description": "Input Slot A" + } + }, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + }, + "item_dispenser": { + "type": "Item", + "description": "Item output when both slots are provided" + } + } + }, + "num_base_convert_0b44": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "s": { + "type": "Big_Int", + "description": "Input integer value" + } + }, + "init_outputs": {} + }, + "time_convert": { + "node_name": "Timezone Converter", + "node_type": "Tool", + "template_id": "time_convert", + "init_inputs": { + "iso": { + "type": "Text_Generic", + "description": "ISO Timestamp" + }, + "from_tz": { + "type": "Text_Generic", + "description": "From Timezone" + }, + "to_tz": { + "type": "Text_Generic", + "description": "To Timezone" + } + }, + "init_outputs": {} + }, + "item_10": { + "node_name": "", + "node_type": "Item", + "template_id": "item_10", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Big_Int", + "description": "The number" + } + } + }, + "item_4": { + "node_name": "", + "node_type": "Item", + "template_id": "item_4", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "File_Id", + "description": "Zip file path" + } + } + }, + "calc_bigmul": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "b": { + "type": "Big_Int", + "description": "Second large integer" + } + }, + "init_outputs": {} + }, + "calc_gcd_232c": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First integer" + }, + "b": { + "type": "Big_Int", + "description": "Second integer" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "zip_unzip_item": { + "init_inputs": {}, + "init_outputs": { + "item": "I ·· V ·· X ·· L ·· C ·· D ·· M" + } + }, + "zip_unzip_file": { + "init_inputs": { + "password": "secret_pass_123!" + }, + "init_outputs": { + "files": "extracted_content1.zip" + } + }, + "crypto_rsa_decrypt_hex": { + "init_inputs": { + "n": "98237498237498273498237498237498" + }, + "init_outputs": {} + }, + "num_base_convert": { + "init_inputs": { + "s": "12345678901234567890", + "to_base": "10" + }, + "init_outputs": {} + }, + "calc_gcd": { + "init_inputs": { + "b": "1203984712039487123984" + }, + "init_outputs": {} + }, + "calc_inv_mod_9968": { + "init_inputs": { + "mod": "997333" + }, + "init_outputs": {} + }, + "zip_unzip_file_f293": { + "init_inputs": { + "password": "another_password_here" + }, + "init_outputs": { + "files": "intermediate_files.zip" + } + }, + "zip_unzip_file_148f": { + "init_inputs": {}, + "init_outputs": { + "files": "initial_layer_data.zip" + } + }, + "container_3": { + "init_inputs": { + "fingerprint_input": "546987123654987123654" + }, + "init_outputs": {} + }, + "calc_modexp": { + "init_inputs": { + "exp": "234985729384759283749" + }, + "init_outputs": {} + }, + "calc_gcd_d1ba": { + "init_inputs": { + "b": "85739485739485739485" + }, + "init_outputs": {} + }, + "terminal_1": { + "init_inputs": { + "slot_a": "terminal_input_string" + }, + "init_outputs": { + "text_output": "Terminal output generated successfully.", + "hex_output": "1a2b3c4d5e6f7a8b", + "item_dispenser": "dispensed useless item from terminal" + } + }, + "num_base_convert_0b44": { + "init_inputs": { + "s": "59483726152439485736" + }, + "init_outputs": {} + }, + "time_convert": { + "init_inputs": { + "iso": "2023-10-01T12:00:00Z", + "from_tz": "UTC", + "to_tz": "Asia/Shanghai" + }, + "init_outputs": {} + }, + "item_10": { + "init_inputs": {}, + "init_outputs": { + "content": "123098457120938471203" + } + }, + "item_4": { + "init_inputs": {}, + "init_outputs": { + "content": "start_file_package.zip" + } + }, + "calc_bigmul": { + "init_inputs": { + "b": "48573948573948573948" + }, + "init_outputs": {} + }, + "calc_gcd_232c": { + "init_inputs": { + "a": "98765432109876543210", + "b": "13579246801357924680" + }, + "init_outputs": {} + } + }, + "intro_narrative": "The rain outside falls like static, illuminated by the sickly neon signs of Sector 4. You find yourself locked inside an underground data-smuggling den, a haven for rogue hackers and digital ghosts. Your objective is simple but highly dangerous: extract a classified blueprint from a deeply buried, password-protected archive before the corporate hit squads breach the reinforced door. The room is littered with archaic decryption modules, modular matrices, and biometric scanners that form a complex web of cryptographic security. You'll need to trace the data flow, operate multiple computing units, and synthesize access tools to peel back the layers of encryption. Time is running out, and every terminal you activate brings you one step closer to uncovering the final objective hidden within the zipped corporate files.", + "narrative_style": "cyberpunk" + }, + "nodes": [ + { + "id": "zip_unzip_item", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_item", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "extracted_content1.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "?/utTH*S\u0019" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip", + "value": "I ·· V ·· X ·· L ·· C ·· D ·· M" + } + ], + "init": { + "inputs": {}, + "outputs": { + "item": "I ·· V ·· X ·· L ·· C ·· D ·· M" + } + }, + "narrative": "This is the Final Extraction Console. It requires inputs from both the Secondary Archive Decoder and the Asymmetric Cipher Deck to securely unpack the final objective." + }, + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "intermediate_files.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "secret_pass_123!" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_content1.zip" + } + ], + "init": { + "inputs": { + "password": "secret_pass_123!" + }, + "outputs": { + "files": "extracted_content1.zip" + } + }, + "narrative": "This is the Secondary Archive Decoder. It requires input from the Intermediate Archive Decoder to peel back the penultimate security shell." + }, + { + "id": "crypto_rsa_decrypt_hex", + "name": "RSA Decrypt", + "description": "RSA decrypt (hex cipher) with n,d (decimal).", + "type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex_cipher", + "type": "Hex_String", + "description": "Ciphertext (Hex)", + "value": "1a2b3c4d5e6f7a8b" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Modulus n", + "value": "98237498237498273498237498237498" + }, + { + "name": "d", + "type": "Big_Int", + "description": "Private exponent d", + "value": "205143" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decrypted text", + "value": "?/utTH*S\u0019" + } + ], + "init": { + "inputs": { + "n": "98237498237498273498237498237498" + }, + "outputs": {} + }, + "narrative": "This is the Asymmetric Cipher Deck. It requires inputs from both the Core Reversal Matrix and the Mainframe Terminal to shatter the cipher." + }, + { + "id": "calc_inv_mod", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "12345678901234567890" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "549739" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "205143" + } + ], + "narrative": "This is the Core Reversal Matrix. It requires inputs from both the Neural Formatter and the Modular Reversal Unit to calculate the final cryptographic inverse." + }, + { + "id": "num_base_convert", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "12345678901234567890" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "1" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "10" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "12345678901234567890" + } + ], + "init": { + "inputs": { + "s": "12345678901234567890", + "to_base": "10" + }, + "outputs": {} + }, + "narrative": "This is the Neural Formatter. It requires input from the Primary Algorithmic Relay to shift numeric structures properly." + }, + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "549739" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "1203984712039487123984" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "init": { + "inputs": { + "b": "1203984712039487123984" + }, + "outputs": {} + }, + "narrative": "This is the Primary Algorithmic Relay. It requires input from the Modular Reversal Unit to find the common denominator of the security mesh." + }, + { + "id": "calc_inv_mod_9968", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "76213956695489749433" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "997333" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "549739" + } + ], + "init": { + "inputs": { + "mod": "997333" + }, + "outputs": {} + }, + "narrative": "This is the Modular Reversal Unit. It requires input from the Cryptographic Matrix to reverse-engineer mathematical locks." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A Discarded Memory Stick covered in neon grime." + }, + { + "id": "item_16_0d2c", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by", + "value": "synthesized_item_4ae59e4ec058aa76" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A freshly printed Synthetic Access Card." + }, + { + "id": "zip_unzip_file_f293", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "initial_layer_data.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "another_password_here" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "intermediate_files.zip" + } + ], + "init": { + "inputs": { + "password": "another_password_here" + }, + "outputs": { + "files": "intermediate_files.zip" + } + }, + "narrative": "This is the Intermediate Archive Decoder. It requires input from the Primary Archive Decoder to strip the second layer of encryption." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "An Old Security Badge dropped by a previous runner." + }, + { + "id": "matter_synthesizer", + "name": "Matter Synthesizer", + "description": "Synthesizes physical objects from data blueprints.", + "type": "Tool", + "template_id": "matter_synthesizer", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "blueprint", + "type": "Text_Generic", + "description": "Object Blueprint", + "value": "2023-10-01T20:00:00+08:00" + } + ], + "outputs": [ + { + "name": "output_slot", + "type": "Item", + "description": "Synthesized Object", + "value": "synthesized_item_4ae59e4ec058aa76" + } + ], + "narrative": "This is the Matter Synthesizer. It requires input from the Temporal Protocol Converter to materialize physical blueprints." + }, + { + "id": "zip_unzip_file_148f", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "start_file_package.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Terminal output generated successfully." + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "initial_layer_data.zip" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "initial_layer_data.zip" + } + }, + "narrative": "This is the Primary Archive Decoder. It requires inputs from both the Mainframe Terminal and the Encrypted Data Drive to begin the extraction process." + }, + { + "id": "container_3", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_3", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Big_Int", + "description": "Fingerprint Hash", + "value": "546987123654987123654" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "546987123654987123654" + }, + "outputs": {} + }, + "narrative": "A heavy Biometric Vault embedded in the wall, securing valuable contraband." + }, + { + "id": "calc_modexp", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "5" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "234985729384759283749" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "123098457120938471203" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "76213956695489749433" + } + ], + "init": { + "inputs": { + "exp": "234985729384759283749" + }, + "outputs": {} + }, + "narrative": "This is the Cryptographic Matrix. It requires inputs from both the Data Synchronization Relay and the Datapad Integer Core to process complex calculations." + }, + { + "id": "calc_gcd_d1ba", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "900000000090" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "85739485739485739485" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "5" + } + ], + "init": { + "inputs": { + "b": "85739485739485739485" + }, + "outputs": {} + }, + "narrative": "This is the Data Synchronization Relay. It requires input from the Initial Algorithmic Processor to align its internal clocks." + }, + { + "id": "item_16_d2f9", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A Cracked Biometric Key that still holds a faint charge." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "terminal_input_string" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "59483726152439485736" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Terminal output generated successfully." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "1a2b3c4d5e6f7a8b" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided", + "value": "dispensed useless item from terminal" + } + ], + "init": { + "inputs": { + "slot_a": "terminal_input_string" + }, + "outputs": { + "text_output": "Terminal output generated successfully.", + "hex_output": "1a2b3c4d5e6f7a8b", + "item_dispenser": "dispensed useless item from terminal" + } + }, + "narrative": "This is the Mainframe Terminal. It requires input from the Alpha Signal Converter to establish a stable connection." + }, + { + "id": "num_base_convert_0b44", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "59483726152439485736" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "12345678901234567890" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "5979378125724878931175680762413114019444" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "59483726152439485736" + } + ], + "init": { + "inputs": { + "s": "59483726152439485736" + }, + "outputs": {} + }, + "narrative": "This is the Alpha Signal Converter. It requires inputs from both the Neural Formatter and the Integer Multiplier to translate the raw machine code." + }, + { + "id": "item_16_95bc", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A Forgotten Neuro-chip coated in synthetic fluid." + }, + { + "id": "time_convert", + "name": "Timezone Converter", + "description": "Convert ISO time between timezones.", + "type": "Tool", + "template_id": "time_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "iso", + "type": "Text_Generic", + "description": "ISO Timestamp", + "value": "2023-10-01T12:00:00Z" + }, + { + "name": "from_tz", + "type": "Text_Generic", + "description": "From Timezone", + "value": "UTC" + }, + { + "name": "to_tz", + "type": "Text_Generic", + "description": "To Timezone", + "value": "Asia/Shanghai" + } + ], + "outputs": [ + { + "name": "iso", + "type": "Text_Generic", + "description": "Converted ISO Timestamp", + "value": "2023-10-01T20:00:00+08:00" + } + ], + "init": { + "inputs": { + "iso": "2023-10-01T12:00:00Z", + "from_tz": "UTC", + "to_tz": "Asia/Shanghai" + }, + "outputs": {} + }, + "narrative": "This is the Temporal Protocol Converter. A rusted device used to translate old earth timeframes." + }, + { + "id": "item_10", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_10", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Big_Int", + "description": "The number", + "value": "123098457120938471203" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "123098457120938471203" + } + }, + "narrative": "A scratched Datapad Integer Core isolated from the main grid." + }, + { + "id": "item_4", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_4", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "File_Id", + "description": "Zip file path", + "value": "start_file_package.zip" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "start_file_package.zip" + } + }, + "narrative": "A heavily Encrypted Data Drive found in the debris." + }, + { + "id": "calc_bigmul", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "123098457120938471203" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "48573948573948573948" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "5979378125724878931175680762413114019444" + } + ], + "init": { + "inputs": { + "b": "48573948573948573948" + }, + "outputs": {} + }, + "narrative": "This is the Integer Multiplier. It requires input from the Datapad Integer Core to amplify the numeric signal." + }, + { + "id": "calc_gcd_232c", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "98765432109876543210" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "13579246801357924680" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "900000000090" + } + ], + "init": { + "inputs": { + "a": "98765432109876543210", + "b": "13579246801357924680" + }, + "outputs": {} + }, + "narrative": "This is the Initial Algorithmic Processor. An old piece of tech used for basic cryptographic operations." + } + ], + "edges": [ + { + "source_id": "zip_unzip_file", + "target_id": "zip_unzip_item", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "crypto_rsa_decrypt_hex", + "target_id": "zip_unzip_item", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "password" + }, + { + "source_id": "calc_inv_mod", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "d" + }, + { + "source_id": "num_base_convert", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "a" + }, + { + "source_id": "calc_gcd", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "from_base" + }, + { + "source_id": "calc_inv_mod_9968", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "a" + }, + { + "source_id": "item_16", + "target_id": "calc_gcd", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "item_16_0d2c", + "target_id": "num_base_convert", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "zip_unzip_file_f293", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "item_8", + "target_id": "calc_inv_mod_9968", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "matter_synthesizer", + "target_id": "item_16_0d2c", + "connection_type": "Item", + "source_port": "output_slot", + "target_port": "source_tool" + }, + { + "source_id": "zip_unzip_file_148f", + "target_id": "zip_unzip_file_f293", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "container_3", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "calc_modexp", + "target_id": "calc_inv_mod_9968", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "a" + }, + { + "source_id": "calc_inv_mod_9968", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "mod" + }, + { + "source_id": "calc_gcd_d1ba", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "base" + }, + { + "source_id": "item_16_d2f9", + "target_id": "zip_unzip_file_148f", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "terminal_1", + "target_id": "zip_unzip_file_148f", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "password" + }, + { + "source_id": "num_base_convert_0b44", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "slot_b" + }, + { + "source_id": "item_16_95bc", + "target_id": "num_base_convert_0b44", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "time_convert", + "target_id": "matter_synthesizer", + "connection_type": "Text_Generic", + "source_port": "iso", + "target_port": "blueprint" + }, + { + "source_id": "terminal_1", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Hex_String", + "source_port": "hex_output", + "target_port": "hex_cipher" + }, + { + "source_id": "item_10", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "content", + "target_port": "mod" + }, + { + "source_id": "item_4", + "target_id": "zip_unzip_file_148f", + "connection_type": "File_Id", + "source_port": "content", + "target_port": "zip_id" + }, + { + "source_id": "num_base_convert", + "target_id": "num_base_convert_0b44", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "from_base" + }, + { + "source_id": "calc_bigmul", + "target_id": "num_base_convert_0b44", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "to_base" + }, + { + "source_id": "item_10", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "content", + "target_port": "a" + }, + { + "source_id": "calc_gcd_232c", + "target_id": "calc_gcd_d1ba", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "a" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-b5fbf361/environment/puzzle/service.py b/tasks/agentescape-25-skeleton-b5fbf361/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-25-skeleton-b5fbf361/environment/puzzle/service.py @@ -0,0 +1,212 @@ +"""Restricted facade over the unchanged, pinned upstream puzzle handlers.""" + +import hashlib +import json +import logging +import os +import sys +import threading +import urllib.request +import uuid +from pathlib import Path + +from fastapi import FastAPI, HTTPException +from fastapi.responses import JSONResponse +from pydantic import BaseModel, ConfigDict + +sys.path.insert(0, str(Path(__file__).parent / "upstream")) +import server as upstream # noqa: E402 + +log = logging.getLogger(__name__) + + +def public(value): + """Keep upstream agent-internal template hints out of the public response.""" + if isinstance(value, dict): + return {k: public(v) for k, v in value.items() if not k.startswith("_")} + if isinstance(value, list): + return [public(v) for v in value] + return value + + +class Action(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + action: str + node_id: str | None = None + arguments: dict | None = None + answer: str | None = None + + +class Episode: + def __init__( + self, scenario_path, max_actions=500, evidence_dir=None, worker_url=None + ): + if max_actions < 1: + raise ValueError("max_actions must be positive") + self.lock = threading.Lock() + self.max_actions = max_actions + self.count = 0 + self.won = False + self.reason = None + self.evidence_dir = Path(evidence_dir) if evidence_dir else None + self.scenario_hash = hashlib.sha256( + Path(scenario_path).read_bytes() + ).hexdigest() + self.initial = upstream.reset_case( + case_file_path=str(scenario_path), session_id=uuid.uuid4().hex + ) + self.case_id = self.initial["case_id"] + # Hide source file paths; no upstream reset/stats/routes are mounted. + self.initial.pop("message", None) + simulator = upstream.SIMULATORS[self.case_id] + if worker_url is None: + + def no_worker(_inputs): + self.reason = "infrastructure_error" + raise RuntimeError("isolated Python worker is not configured") + + simulator.tool_map["code_py_exec"] = no_worker + else: + + def execute_python(inputs): + request = urllib.request.Request( + worker_url + "/execute", + data=json.dumps({"code": inputs.get("code", "")}).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=12) as response: + result = json.load(response) + if not isinstance(result.get("stdout"), str): + raise RuntimeError("Invalid Python worker response") + return result + except Exception: + self.reason = "infrastructure_error" + raise + + simulator.tool_map["code_py_exec"] = execute_python + self.save() + if self.evidence_dir is not None: + (self.evidence_dir / "trace.jsonl").touch() + + def state(self): + return { + "scenario_sha256": self.scenario_hash, + "action_count": self.count, + "max_actions": self.max_actions, + "won": self.won, + "termination_reason": self.reason, + } + + def save(self, action=None, result=None): + if self.evidence_dir is None: + return + self.evidence_dir.mkdir(parents=True, exist_ok=True) + target = self.evidence_dir / "outcome.json" + temp = target.with_suffix(".tmp") + temp.write_text(json.dumps(self.state())) + temp.replace(target) + if action is not None: + with (self.evidence_dir / "trace.jsonl").open("a") as handle: + handle.write( + json.dumps( + {"index": self.count, "action": action, "result": result} + ) + + "\n" + ) + + def dispatch(self, payload): + with self.lock: + if self.reason is not None: + return { + "ok": False, + "error": "Episode has ended", + "episode": self.state(), + } + self.count += 1 + try: + action = Action.model_validate(payload) + if action.action == "submit_answer" and action.answer is not None: + result = upstream.submit_answer( + self.case_id, upstream.SubmitAnswerRequest(answer=action.answer) + ) + if result.get("is_win"): + self.won = True + self.reason = "success" + elif action.action == "investigate" and action.node_id is not None: + result = upstream.investigate( + self.case_id, + upstream.InvestigateRequest(node_id=action.node_id), + ) + elif ( + action.action in ("tool_call", "use_item") + and action.node_id is not None + ): + request_type, handler = ( + (upstream.ToolCallRequest, upstream.tool_call) + if action.action == "tool_call" + else (upstream.UseItemRequest, upstream.use_item) + ) + result = handler( + self.case_id, + request_type( + node_id=action.node_id, arguments=action.arguments or {} + ), + ) + else: + result = { + "ok": False, + "error": "Unknown action or missing action parameter", + } + except HTTPException as exc: + result = {"ok": False, "error": exc.detail} + except ValueError: + result = {"ok": False, "error": "Malformed action"} + except Exception: + log.exception("Puzzle service failure") + self.reason = "infrastructure_error" + self.save() + raise + if self.reason is None and self.count >= self.max_actions: + self.reason = "action_budget_exhausted" + result = public(result) + result["episode"] = self.state() + self.save(payload, result) + return result + + +def create_app( + scenario_path=None, max_actions=None, evidence_dir=None, worker_url=None +): + episode = Episode( + scenario_path or os.environ["SCENARIO_PATH"], + max_actions or int(os.environ.get("MAX_ACTIONS", "500")), + evidence_dir if evidence_dir is not None else os.environ.get("EVIDENCE_DIR"), + worker_url if worker_url is not None else os.environ.get("WORKER_URL"), + ) + app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) + app.state.episode = episode + + @app.get("/health") + def health(): + return {"ok": True} + + @app.get("/observation") + def observation(): + return {**public(episode.initial), "episode": episode.state()} + + @app.get("/state") + def state(): + return episode.state() + + @app.post("/action") + def action(payload: dict): + try: + return episode.dispatch(payload) + except Exception: + return JSONResponse( + status_code=503, + content={"ok": False, "error": "Puzzle infrastructure failure"}, + ) + + return app diff --git a/tasks/agentescape-25-skeleton-b5fbf361/environment/puzzle/upstream/models.py b/tasks/agentescape-25-skeleton-b5fbf361/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-25-skeleton-b5fbf361/environment/puzzle/upstream/models.py @@ -0,0 +1,108 @@ +from enum import Enum +from typing import List, Dict, Any, Optional +from pydantic import BaseModel, Field + +# 1. 细粒度接口类型定义 +class InterfaceType(str, Enum): + ''' + BIG_INT + TEXT_GENERIC + HEX_STRING + FILE_ID + HEX_STRING_KEY_AES + HEX_STRING_IV_AES + CODE_PYTHON + HIDDEN_ITEM + ITEM + ''' + # --- 基础类型 --- + TEXT_GENERIC = "Text_Generic" + BIG_INT = "Big_Int" + + # --- 编码/格式化字符串 --- + HEX_STRING = "Hex_String" # 通用 Hex + + # --- 特定用途的 Hex 字符串 (用于精确匹配) --- + HEX_STRING_KEY_AES = "Hex_String_Key_AES" + HEX_STRING_IV_AES = "Hex_String_IV_AES" + + # --- 文件类型 --- + FILE_ID = "File_Id" + + # --- 代码/脚本 --- + CODE_PYTHON = "Code_Python" + + # --- 实体交互类型 (严格命名) --- + ITEM = "Item" # 主动掉落接口 (Tool -> Item) + HIDDEN_ITEM = "Hidden_Item" # 被动掉落接口 (Item -> Item) + +# 3. 端口定义 +class Port(BaseModel): + name: str + type: InterfaceType + description: str + +# 4. 统一节点定义 (融合工具和物品) +class Node(BaseModel): + id: str + name: str + description: str + type: str # "Tool" or "Item" + + # 接口定义 + inputs: List[Port] = [] + outputs: List[Port] = [] + + # 状态字段 + content: Optional[Any] = None # 物品有内容,工具为None + if_success: Optional[bool] = None # 工具初始为False,物品为None + initial_visible: bool = False + + # 运行时状态 (Server维护) + is_revealed: bool = False + + # 标记该 Tool 节点是否有待触发的 HIDDEN_ITEM 掉落 + # 当 Tool 按照 golden_input 正确执行且有 HIDDEN_ITEM 输出边时设为 True + # 在 investigate 该 Tool 时触发掉落并重置为 False + has_hidden_item_ready: bool = False + + # 初始输入值 (metadata.initial_values.init_inputs,用于渐进式暴露判断) + init_input_values: Dict[str, Any] = {} + + # Golden 输入值 (nodes[].inputs[].value,用于评测验证) + golden_input_values: Dict[str, Any] = {} + + # Golden 输出值 (nodes[].outputs[].value,用于评测验证和 Item 节点的 content) + golden_output_values: Dict[str, Any] = {} + + # 实际获得的输出值历史 (工具每次执行后实际返回的输出列表,用于渐进式暴露判断) + # 格式: List[Dict[str, Any]],每个元素是一次执行的输出字典 + actual_outputs_history: List[Dict[str, Any]] = [] + + # 逻辑规则 (用于终端机等复杂物品) + logic_rules: Optional[Dict[str, Any]] = None + + def copy(self, **kwargs): + """Helper to create a copy with updated fields.""" + data = self.dict() + data.update(kwargs) + return Node(**data) + +# 5. 边定义 (拓扑结构) +class Edge(BaseModel): + source_id: str + target_id: str + connection_type: InterfaceType # 直接使用 InterfaceType + # 如果是 Data_Flow,指定端口对应关系 + source_port: Optional[str] = None + target_port: Optional[str] = None + +# 6. 完整图定义 +class GraphScenario(BaseModel): + case_id: str + title: str + intro_narrative: str + nodes: Dict[str, Node] + edges: List[Edge] + difficulty: int + win_node_id: str # 标记哪个节点是最终目标(通常是一个提交工具或最终物品) diff --git a/tasks/agentescape-25-skeleton-b5fbf361/environment/puzzle/upstream/server.py b/tasks/agentescape-25-skeleton-b5fbf361/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-25-skeleton-b5fbf361/environment/puzzle/upstream/server.py @@ -0,0 +1,1490 @@ +import json +import os +import time +import logging +import random +from pathlib import Path +from typing import Dict, Any, List, Optional +from datetime import datetime +from collections import defaultdict +from fastapi import FastAPI, HTTPException, Request +from fastapi.responses import JSONResponse +from fastapi.middleware.cors import CORSMiddleware +from pydantic import BaseModel, Field + +from models import GraphScenario, Node, InterfaceType +# from generator import ScenarioGenerator +from simulator import ToolSimulator +import uvicorn + +# 配置日志 +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler('server.log'), + logging.StreamHandler() + ] +) +logger = logging.getLogger(__name__) + +app = FastAPI( + title="AgentEscapeBench Universal Server", + version="1.0.0", + description="Industrial-grade evaluation server for escape room AI agents" +) + +# 添加 CORS 支持 +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# In-memory State +SCENARIOS: Dict[str, GraphScenario] = {} +SIMULATORS: Dict[str, ToolSimulator] = {} # case_id -> ToolSimulator +RAW_NODES_DATA: Dict[str, Dict[str, Any]] = {} # case_id -> node_id -> raw node data (for template_id) +FILE_METADATA: Dict[str, Dict[str, Any]] = {} # case_id -> metadata (for initial_values access) + +# Performance monitoring +STATS: Dict[str, Any] = { + "total_requests": 0, + "successful_requests": 0, + "failed_requests": 0, + "tool_calls": defaultdict(int), + "investigates": defaultdict(int), + "use_items": defaultdict(int), + "case_loads": 0, + "start_time": datetime.now() +} + +# Request timing middleware +@app.middleware("http") +async def add_process_time_header(request: Request, call_next): + start_time = time.time() + STATS["total_requests"] += 1 + + try: + response = await call_next(request) + STATS["successful_requests"] += 1 + process_time = time.time() - start_time + response.headers["X-Process-Time"] = str(process_time) + logger.info(f"{request.method} {request.url.path} - {response.status_code} - {process_time:.3f}s") + return response + except Exception as e: + STATS["failed_requests"] += 1 + logger.error(f"{request.method} {request.url.path} - Error: {str(e)}") + raise + +# Exception handler +@app.exception_handler(Exception) +async def global_exception_handler(request: Request, exc: Exception): + logger.error(f"Unhandled exception: {exc}", exc_info=True) + return JSONResponse( + status_code=500, + content={ + "ok": False, + "error": "Internal server error", + "detail": str(exc) if os.getenv("DEBUG") else "An error occurred" + } + ) + +# Health check endpoint +@app.get("/health") +def health_check(): + """健康检查端点""" + uptime = (datetime.now() - STATS["start_time"]).total_seconds() + return { + "status": "healthy", + "version": "1.0.0", + "uptime_seconds": uptime, + "loaded_cases": len(SCENARIOS), + "stats": { + "total_requests": STATS["total_requests"], + "successful_requests": STATS["successful_requests"], + "failed_requests": STATS["failed_requests"], + "success_rate": STATS["successful_requests"] / max(STATS["total_requests"], 1) + } + } + +# Statistics endpoint +@app.get("/stats") +def get_stats(): + """获取详细统计信息""" + return { + "stats": STATS, + "loaded_cases": list(SCENARIOS.keys()), + "uptime": str(datetime.now() - STATS["start_time"]) + } + +def _apply_progressive_reveal_at_init(scenario: GraphScenario): + """ + 在初始化时应用渐进式暴露机制(基于ITEM/HIDDEN_ITEM边) + + 新逻辑: + - 如果一个节点没有 ITEM/HIDDEN_ITEM 类型的入边,它就是初始可见的 + - 如果一个节点有 ITEM/HIDDEN_ITEM 类型的入边,它初始不可见,需要等待上游触发 + + Args: + scenario: 场景对象 + """ + # 收集所有有 ITEM/HIDDEN_ITEM 入边的节点 + nodes_with_item_edges = set() + for edge in scenario.edges: + if edge.connection_type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + nodes_with_item_edges.add(edge.target_id) + + logger.info(f"Nodes with ITEM/HIDDEN_ITEM incoming edges: {nodes_with_item_edges}") + + # 设置初始可见性:没有 ITEM/HIDDEN_ITEM 入边的节点初始可见 + initially_visible_count = 0 + for node_id, node in scenario.nodes.items(): + if node_id not in nodes_with_item_edges: + node.is_revealed = True + initially_visible_count += 1 + logger.info(f"Initial visible (no ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + else: + node.is_revealed = False + logger.debug(f"Initial hidden (has ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + + logger.info(f"Progressive reveal initialized: {initially_visible_count}/{len(scenario.nodes)} nodes initially visible") + + +def _check_inputs_match_golden(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> bool: + """ + 检查实际输入参数是否与 golden inputs 完全匹配 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + True 表示所有 golden inputs 都存在且值匹配 + """ + if not golden_inputs: + return True # 如果没有 golden inputs,认为匹配 + + for key, expected_value in golden_inputs.items(): + actual_value = arguments.get(key) + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) != str(expected_value): + logger.debug(f"Input mismatch for '{key}': expected '{expected_value}', got '{actual_value}'") + return False + + return True + + +def _get_parameter_validation_feedback(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> Dict[str, Any]: + """ + 对源头节点的参数进行详细验证,返回验证反馈 + + 注意:不返回期望值(expected),避免泄漏答案 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + 包含验证结果的字典: + - all_correct: bool - 所有参数是否正确 + - correct_params: List[str] - 正确的参数名列表 + - incorrect_params: List[str] - 错误的参数名列表(不包含期望值) + """ + if not golden_inputs: + return { + "all_correct": True, + "correct_params": [], + "incorrect_params": [] + } + + correct_params = [] + incorrect_params = [] + + for key, actual_value in arguments.items(): + # 只对用户实际提交的参数给反馈,未提交的参数不评价 + if key not in golden_inputs: + continue # 该参数不在 golden 中,跳过(如 _golden_inputs 等内部参数) + expected_value = golden_inputs[key] + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) == str(expected_value): + correct_params.append(key) + else: + # 只记录参数名,不包含期望值,避免泄漏答案 + incorrect_params.append(key) + + # all_correct:用户提交的所有参数都正确,且覆盖了全部 golden 参数 + all_provided_correct = len(incorrect_params) == 0 + all_golden_covered = all(k in arguments for k in golden_inputs) + return { + "all_correct": all_provided_correct and all_golden_covered, + "correct_params": correct_params, + "incorrect_params": incorrect_params + } + + +def _is_source_node(node_id: str, scenario: GraphScenario) -> bool: + """ + 判断节点是否是源头节点(完全没有任何入边的节点) + + 源头节点定义: + - 没有任何类型的入边(包括 DATA、ITEM、HIDDEN_ITEM) + - 即没有任何上游节点 + + Args: + node_id: 节点ID + scenario: 场景对象 + + Returns: + True 表示是源头节点 + """ + for edge in scenario.edges: + if edge.target_id == node_id: + # 只要有任何入边,就不是源头节点 + return False + + return True + + +def _check_and_reveal_ready_nodes(scenario: GraphScenario, recent_outputs: Dict[str, Any], source_node_id: str) -> List[Dict[str, Any]]: + """ + 检查并释放参数齐全的隐藏节点(渐进式暴露机制) + + 核心逻辑: + 1. 维护"可见值集合":包含所有被测模型当前可以看到的值 + - init_inputs 的值(初始可见) + - 工具执行后的实际输出值(运行时获得) + - 可见 Item 的输出值 + 2. 检查隐藏节点:该节点的所有 golden_input 值是否都在可见值集合中 + 3. 如果是,则释放该节点 + + Args: + scenario: 场景对象 + recent_outputs: 最近执行的工具的输出 + source_node_id: 刚执行的工具节点ID + + Returns: + 新释放的节点列表 + """ + newly_revealed = [] + + # 构建"可见值集合"(Set of visible values) + # 存储格式:set of values (转为字符串) + visible_values = set() + + # 1. 添加有意义的 init_inputs 值到可见值集合 + # Item 的 init_inputs 不应该加入,因为它们在密室中完全用不到 + for node_id, node in scenario.nodes.items(): + # 跳过源头 Item 节点(没有入边的 Item) + if node.type == "Item": + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,跳过其 init_inputs + continue + + # 添加其他节点的 init_inputs + for port_name, init_value in node.init_input_values.items(): + if init_value: + visible_values.add(str(init_value)) + + # 2. 添加已执行工具的所有历史输出值 + for node_id, node in scenario.nodes.items(): + if node.type == "Tool" and node.if_success and node.actual_outputs_history: + # 遍历所有历史执行记录 + for output_dict in node.actual_outputs_history: + for output_port_name, output_value in output_dict.items(): + if output_value: + visible_values.add(str(output_value)) + + # 3. 添加已被 investigate 的 Item 的 golden 输出值 + # 注意:Item 可见不等于其输出值可见,需要 investigate 后才能获得 + # 这里我们使用 actual_outputs_history 来标记 Item 是否已被 investigate + for node_id, node in scenario.nodes.items(): + if node.type == "Item" and node.is_revealed and node.actual_outputs_history: + # Item 通常只会被 investigate 一次,但为了一致性也使用历史列表 + for output_dict in node.actual_outputs_history: + for port_name, port_value in output_dict.items(): + if port_value: + visible_values.add(str(port_value)) + + # 遍历所有隐藏的节点,检查其 golden_input 是否都在可见值集合中 + for node_id, node in scenario.nodes.items(): + # 跳过已可见的节点 + if node.is_revealed: + continue + + # 只检查工具节点(物品节点由 ITEM 输出触发) + if node.type != "Tool": + continue + + # 检查该节点的所有 golden_input 值是否都在可见值集合中 + all_inputs_ready = True + missing_values = [] + + for input_port_name, golden_input_value in node.golden_input_values.items(): + # 检查这个 golden 值是否在可见值集合中 + if str(golden_input_value) not in visible_values: + all_inputs_ready = False + missing_values.append(f"{input_port_name}={golden_input_value}") + + # 如果所有 golden_input 值都在可见值集合中,释放该节点 + if all_inputs_ready and len(node.golden_input_values) > 0: + logger.info(f"All golden inputs ready for {node_id}: {list(node.golden_input_values.values())}") + + # 如果所有输入都齐全,释放该节点 + if all_inputs_ready: + node.is_revealed = True + + # 构建节点信息返回给模型 + node_info = { + "id": node.id, + "type": node.type, + "can_investigate": True, + "hint": "This tool's input parameters are now complete, you can use investigate to view detailed information" + } + + # if node.name: + # node_info["name"] = node.name + if node.description: + node_info["description"] = node.description + + newly_revealed.append(node_info) + logger.info(f"Progressive reveal: {node_id} is now ready (all inputs satisfied)") + + return newly_revealed + + +def _initialize_node_values(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]): + """ + Initialize node state and load values from port value fields. + 应用渐进式暴露机制:初始时只显示参数齐全的节点(源头节点) + + 重要区分: + 1. input_values: 只加载 metadata.initial_values 中的 init_inputs(真正的初始值) + 2. output_values: 加载 nodes[].outputs[].value(golden 输出,用于验证) + """ + # 第一步:加载所有节点的值,并将所有节点初始设为隐藏 + initial_values = metadata.get('initial_values', {}) + + for node_id, node in scenario.nodes.items(): + # 忽略 initial_visible 字段,初始全部隐藏 + # 由渐进式暴露机制根据参数齐全情况决定是否显示 + node.is_revealed = False + + if node.type == "Tool": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + elif node.type == "Item": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + + # 从 JSON 加载值 + if node_id in raw_nodes_data: + node_data = raw_nodes_data[node_id] # node_data是json文件中nodes中的字典 + + # 【重要】只加载 metadata.initial_values 中的初始输入值 + if node_id in initial_values: + init_data = initial_values[node_id] + # 加载初始输入值(用于渐进式暴露判断) + for port_name, port_value in init_data.get('init_inputs', {}).items(): + node.init_input_values[port_name] = port_value + + # 【评测用】加载 golden 输入值(用于验证模型传入的参数是否正确) + for input_port_data in node_data.get('inputs', []): + if 'value' in input_port_data: + node.golden_input_values[input_port_data['name']] = input_port_data['value'] + + # 【评测用】加载 golden 输出值(用于验证工具调用是否正确,以及 Item 节点的 content) + for output_port_data in node_data.get('outputs', []): + if 'value' in output_port_data: + node.golden_output_values[output_port_data['name']] = output_port_data['value'] + + # For Items, set content from golden_output_values + if node.type == "Item" and node.golden_output_values: + # Item 的 content 是其第一个 golden 输出值 + node.content = list(node.golden_output_values.values())[0] + + # 第二步:应用渐进式暴露机制 + # 检查所有节点,根据参数齐全情况释放源头节点(工具 + Item) + _apply_progressive_reveal_at_init(scenario) + +def _build_node_info(node: Node, raw_nodes_data: Dict[str, Any]) -> Dict[str, Any]: + """ + 构建节点信息(工具或物品) + + Args: + node: 节点对象 + raw_nodes_data: 原始节点数据(用于获取 template_id 等) + + Returns: + 节点信息字典 + """ + if node.type == "Tool": + # 过滤掉输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口) + # 这些端口仅用于控制掉落机制,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + tool_info = { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Tool", + "inputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.inputs if p.type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]], + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id(工具的标准名称) + if node.id in raw_nodes_data: + node_data = raw_nodes_data[node.id] + template_id = node_data.get('template_id') + if template_id: + tool_info['template_id'] = template_id + + return tool_info + + elif node.type == "Item": + return { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Item" + } + + else: + return { + "id": node.id, + # "name": node.name, + "type": node.type + } + +def _get_initial_observation(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]) -> Dict[str, Any]: + """ + Generate initial observation for the agent (what they see when entering the room). + + 策略: + - Tools: 只显示名称和描述,不显示接口定义。需要 investigate 才能获得详细接口信息。 + - Items: 只显示存在,不显示内容。需要 investigate 才能获得内容值。 + - init_inputs: 作为"可用信息"告诉模型,这些是可以用作工具参数的初始值。 + - init_outputs: 不告诉模型(这些是答案,需要模型通过调用工具获得)。 + """ + available_entities = [] # 统一的实体列表(Tools 和 Items) + available_information = [] # 可用的初始信息(来自 init_inputs) + + # 从 metadata.initial_values 提取 init_inputs 作为可用信息 + # 只提供值本身,不透露这些值对应哪个节点的哪个参数,让模型自己推理 + # 注意:跳过源头 Item(没有入边的 Item)的 init_inputs,因为它们在密室中完全用不到 + initial_values = metadata.get('initial_values', {}) + # initial_values字段的格式 + # "initial_values": { + # "terminal_1": { + # "init_inputs": {}, + # "init_outputs": { + # "text_output": "System initialization complete.", + # "hex_output": "48656c6c6f20576f726c64", + # "item_dispenser": "掉落了一张纸条,上面写着“请勿随意触摸终端”" + # } + # } + # } + for node_id, init_data in initial_values.items(): + # 获取节点信息,判断是否为源头 Item + node = scenario.nodes.get(node_id) + if node and node.type == "Item": + # 检查是否为源头 Item(没有入边) + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,检查是否有 init_inputs + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 有 init_inputs,需要暴露这些参数 + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + # 处理完后跳过后续的通用逻辑 + continue + + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 为每个 init_input 值创建一个信息条目(不包含 source_node 和 parameter 信息) + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + + for node in scenario.nodes.values(): + if node.is_revealed: + # Tools: 只显示基本信息,提示可以 investigate 查看详细接口 + if node.type == "Tool": + tool_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Tool", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the tool's detailed interface information for calling" + } + # 只在 name 非空时添加 + # if node.name: + # tool_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_info["description"] = node.description + + available_entities.append(tool_info) + + # Items: 只显示基本信息,提示可以 investigate 查看内容 + elif node.type == "Item": + item_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Item", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the item's content" + } + # 只在 name 非空时添加 + # if node.name: + # item_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + item_info["description"] = node.description + + available_entities.append(item_info) + + return { + "narrative": scenario.intro_narrative, + "available_entities": available_entities, # 使用统一的实体列表 + "available_information": available_information, # 可用的初始信息(只包含 init_inputs) + "win_node_id": scenario.win_node_id # 胜利节点ID,让模型知道需要关注哪个节点 + } + +@app.post("/env/reset") +def reset_case(case_id: str = None, case_file_path: str = None, session_id: str = None): + """Loads a specific case from file and resets it. + + Args: + case_id: Optional case ID for resetting an existing case + case_file_path: Path to case file for loading a new case + session_id: Optional session ID to ensure isolation between concurrent evaluations + """ + logger.info(f"Reset request - case_id: {case_id}, case_file_path: {case_file_path}, session_id: {session_id}") + STATS["case_loads"] += 1 + + if case_file_path: + if not os.path.exists(case_file_path): + logger.error(f"Case file not found: {case_file_path}") + raise HTTPException(status_code=404, detail=f"File not found: {case_file_path}") + try: + with open(case_file_path, "r", encoding="utf-8") as f: + file_data = json.load(f) + + # 转换格式:从 DAG executor 生成的格式转换为 GraphScenario 格式 + # 1. 提取 metadata + metadata = file_data.get('metadata', {}) + + # 2. 生成 case_id, title, intro_narrative + # 【修复】为每个评测会话生成唯一的 case_id,防止并发评测时状态污染 + base_name = os.path.basename(case_file_path).replace('.json', '').replace('_full', '').replace('_full2', '') + + if session_id: + # 如果提供了 session_id,使用它来确保唯一性 + case_id = f"{base_name}_{session_id}" + else: + # 否则使用时间戳和随机数确保唯一性 + unique_suffix = f"{int(time.time() * 1000)}_{random.randint(1000, 9999)}" + case_id = f"{base_name}_{unique_suffix}" + + file_data['case_id'] = case_id + logger.info(f"Generated unique case_id: {case_id} (base: {base_name}, session: {session_id})") + + if 'title' not in file_data: + file_data['title'] = f"Escape Room: {file_data['case_id']}" + + if 'intro_narrative' not in file_data: # 目前的json文件中已经有了intro_narrative字段,不会使用下面一行的内容,而是使用每个评测问题的json文件中的对应字段 + 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]".' + + # 3. 转换 nodes 列表为字典(DAG executor 生成的文件中 nodes 是列表格式) + nodes_dict = {} + for node_data in file_data['nodes']: + nodes_dict[node_data['id']] = node_data # 这里的id是template_id之后可能添加一个后缀 + file_data['nodes'] = nodes_dict # 把列表转成一个字典 + + # 4. 添加缺失的字段 + if 'difficulty' not in file_data: + file_data['difficulty'] = metadata.get('total_nodes', 5) + + if 'win_node_id' not in file_data: + file_data['win_node_id'] = metadata.get('win_node_id', '') + + scenario = GraphScenario(**file_data) + + # Extract raw nodes data for template_id access + # nodes 已经在上面转换为字典格式 + raw_nodes_data = file_data.get('nodes', {}) + RAW_NODES_DATA[scenario.case_id] = raw_nodes_data + + # Store metadata for initial values access + FILE_METADATA[scenario.case_id] = metadata + + logger.info(f"Successfully parsed case file: {scenario.case_id}, nodes: {len(scenario.nodes)}, edges: {len(scenario.edges)}") + except Exception as e: + logger.error(f"Failed to load case file: {str(e)}", exc_info=True) + raise HTTPException(status_code=500, detail=f"Failed to load case file: {str(e)}") + + # Initialize node state and load values + _initialize_node_values(scenario, raw_nodes_data, metadata) + + SCENARIOS[scenario.case_id] = scenario + simulator = ToolSimulator() + SIMULATORS[scenario.case_id] = simulator + + 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'])}") + + # 生成初始观察信息(进入密室后看到的环境) + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + ''' + initial_observation的格式: + { + "narrative": scenario.intro_narrative, + "available_entities": available_entities # 使用统一的实体列表 + "available_information": available_information # 可用的初始信息(只包含 init_inputs) + } + ''' + + return { + "ok": True, + "message": f"Case loaded from {case_file_path}", + "case_id": scenario.case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果没有提供 case_file_path,但提供了 case_id,则尝试从内存重置 + if case_id and case_id in SCENARIOS: + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + metadata = FILE_METADATA.get(case_id, {}) + + # Reset dynamic fields and re-apply progressive reveal + # 重新初始化节点状态(包括渐进式暴露) + _initialize_node_values(scenario, raw_nodes_data, metadata) + + 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'])}") + + # 生成初始观察信息 + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + + return { + "ok": True, + "message": f"Case {case_id} reset.", + "case_id": case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果既没有 case_file_path,也没有在内存中找到,返回错误 + raise HTTPException( + status_code=400, + detail="Must provide case_file_path to load a new case, or use case_id to reset an existing case." + ) + +class InvestigateRequest(BaseModel): + node_id: str + +@app.post("/env/{case_id}/investigate") +def investigate(case_id: str, req: InvestigateRequest): + """ + Investigates a Tool or Item to reveal detailed information. + + - For Tools: Returns detailed interface information (inputs/outputs) needed to call the tool + - For Items: Returns content value and triggers hidden item drops + """ + logger.info(f"Investigate request - case_id: {case_id}, node_id: {req.node_id}") + STATS["investigates"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + node = scenario.nodes[req.node_id] + + if not node.is_revealed: + logger.warning(f"Attempt to investigate hidden node: {req.node_id}") + return {"ok": False, "error": "Node is not visible yet."} + + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + newly_revealed = [] + + # 处理 Tool 的 investigate + if node.type == "Tool": + logger.info(f"Investigating tool: {req.node_id}") + + # 返回工具的详细接口信息 + # id 字段使用 node.id(节点唯一标识),agent 用这个字段识别和调用具体的节点 + # template_id 是工具类型标识符,Agent 内部用于判断工具特性(如 terminal 类工具参数可选) + # 注意:只过滤输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口),这些端口仅用于控制掉落,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + # 【端口上游依赖提示 & 初始值直接给出】 + # 针对参数语义模糊(全为数字类型)的工具,在 investigate 返回信息中标注 + # 哪个输入端口来自哪个上游节点(upstream_from)。 + # 对于所有工具:若该节点不是纯源头节点(有任意数据流入边), + # 且某个端口没有上游入边(值来自初始可见参数),则直接给出该端口的 golden input 值。 + AMBIGUOUS_TOOLS = { + "num_base_convert", "calc_modexp", "calc_modexp_int", + "calc_inv_mod", "calc_inv_mod_int", "crypto_rsa_decrypt_hex", "geo_haversine" + } + # Terminal 类工具自带参数对错反馈机制,玩家/模型可自行试错, + # 无需在 investigate 时直接暴露 init_value + SELF_FEEDBACK_TOOLS = { + "terminal_1", "terminal_2", + "Logic Terminal", "Math Terminal", "Encryption Terminal", "Sequence Terminal" + } + _template_id_for_hint = raw_nodes_data.get(node.id, {}).get("template_id", "") + # 构建数据流入边映射(对所有工具):{target_port -> (source_node_id, source_port)} + _upstream_map = {} + for _edge in scenario.edges: + if (_edge.target_id == node.id + and _edge.connection_type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM] + and _edge.target_port is not None): + _upstream_map[_edge.target_port] = (_edge.source_id, _edge.source_port) + # 判断该节点是否有任意数据流入边(即不是纯源头节点) + _has_any_upstream = len(_upstream_map) > 0 + # 判断该节点是否有任意入边(包括 ITEM/HIDDEN_ITEM 掉落边) + # 有任意入边(含掉落边)但无数据流入边的节点,其输入来自初始可见参数,应直接给出 + _has_any_edge = any(_edge.target_id == node.id for _edge in scenario.edges) + # 构建 inputs 列表 + _inputs_list = [] + for p in node.inputs: + if p.type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + continue + port_dict = {"name": p.name, "type": p.type, "description": p.description} + if p.name in _upstream_map: + # 该端口有上游数据流依赖,且属于语义模糊工具 → 标注来源 + if _template_id_for_hint in AMBIGUOUS_TOOLS: + src_node_id, src_port = _upstream_map[p.name] + port_dict["upstream_from"] = f"{src_node_id}.{src_port}" if src_port else src_node_id + elif _has_any_edge and _template_id_for_hint not in SELF_FEEDBACK_TOOLS: + # 该节点有任意入边,但此端口没有数据流入边 → 值来自初始可见参数,直接给出 + # 排除自带反馈机制的 terminal 类工具(它们通过执行结果反馈对错,无需提前暴露参数值) + golden_val = node.golden_input_values.get(p.name) + if golden_val is not None: + port_dict["init_value"] = golden_val + _inputs_list.append(port_dict) + + tool_details = { + "id": node.id, # 节点 ID,用于唯一标识和调用这个具体节点 + "type": "Tool", + "inputs": _inputs_list, + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id 用于 Agent 内部判断工具类型(不会展示给被测模型) + if node.id in raw_nodes_data: + template_id = raw_nodes_data[node.id].get('template_id') + if template_id: + tool_details["_template_id"] = template_id # 使用下划线前缀标记为内部字段 + + # 只在 name 非空时添加 + # if node.name: + # tool_details["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_details["description"] = node.description + + # 添加 narrative 字段(如果存在) + if node.id in raw_nodes_data: + narrative = raw_nodes_data[node.id].get('narrative') + if narrative: + tool_details['narrative'] = narrative + + # 不再返回 init_values,避免泄漏答案 + # investigate 只应该返回工具的接口定义,不应该暴露初始值 + + # 【新增】检查该 Tool 是否有待触发的 HIDDEN_ITEM 掉落 + # 如果该工具已按照 golden_input 正确执行,且有 HIDDEN_ITEM 输出边,则触发掉落 + if node.has_hidden_item_ready: + logger.info(f"Tool has HIDDEN_ITEM ready - triggering passive drop for: {req.node_id}") + + # 遍历该工具的所有 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + # 重置标志,已经触发过了,避免重复 + node.has_hidden_item_ready = False + + logger.info(f"Tool investigation successful - node: {req.node_id}, revealed: {len(newly_revealed)}") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Tool", + "details": tool_details + } + + # 如果有新掉落的节点,添加到响应中 + if newly_revealed: + result["newly_revealed"] = newly_revealed + + return result + + # 处理 Item 的 investigate + elif node.type == "Item": + logger.info(f"Investigating item: {req.node_id}") + + # 【第一步】检查该 Item 是否有需要参数的输入端口 + # 如果有,且尚未通过 use_item 验证,则不返回内容,只返回参数要求 + required_inputs = [] + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + inputs_info = raw_node.get('inputs', []) + required_inputs = [ + { + "name": inp.get("name"), + "type": inp.get("type"), + "description": inp.get("description", "") + } + for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + # 如果有 required_inputs 且尚未通过 use_item 验证(if_success == False) + # 则不返回内容,只返回参数要求提示 + if required_inputs and not node.if_success: + logger.info(f"Item has required inputs and not yet unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "required_inputs": required_inputs + } + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + param_names = ', '.join([inp['name'] for inp in required_inputs]) + 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}" + + return result + + # 【新增】如果有 required_inputs 且已经通过 use_item 验证(if_success == True) + # 则返回提示:该节点已经被成功解决 + if required_inputs and node.if_success: + logger.info(f"Item has required inputs and already unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "message": "This item has already been successfully unlocked by you." + } + return result + + # 【第二步】该 Item 没有 required_inputs 或已通过验证,返回内容 + # 1. 返回 Item 的 golden_output_values(即 Item 的内容) + # 注意:某些 Item 仅用于触发 HIDDEN_ITEM 掉落,没有实际内容 + has_actual_content = bool(node.golden_output_values) or node.content is not None + content = node.golden_output_values if node.golden_output_values else node.content + + # 【关键】将 golden_output_values 追加到 actual_outputs_history,标记该 Item 已被 investigate + # 这样在渐进式暴露时,这些值才会被加入可见值集合 + # 即使是空字典(仅触发 HIDDEN_ITEM 的 Item),也要记录,以便渐进式暴露逻辑知道该 Item 已被调查 + if node.golden_output_values is not None: + node.actual_outputs_history.append(dict(node.golden_output_values)) + + # 2. Trigger Hidden Item Drops (Passive Drop) + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + logger.info(f"Item investigation successful - node: {req.node_id}, has_content: {has_actual_content}, revealed: {len(newly_revealed)}") + + # 【渐进式暴露】旧机制(基于 golden_input)已禁用 + # 现在完全由 ITEM/HIDDEN_ITEM 边触发控制节点可见性 + # 上面的 HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, node.golden_output_values or {}, node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # logger.info(f"Progressive reveal after Item investigate: {len(progressive_revealed)} nodes now ready") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Item" + } + + # 只在有实际内容时才添加 content 字段 + # 对于仅触发 HIDDEN_ITEM 掉落的 Item,不返回 content 字段,避免返回 None 或空字典让模型困惑 + if has_actual_content: + result["content"] = content + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型通过 investigate 获得内容后,需要自己识别这是否是胜利字符串 + + return result + + else: + logger.warning(f"Attempt to investigate unknown node type: {req.node_id} (type: {node.type})") + return {"ok": False, "error": f"Cannot investigate node type: {node.type}"} + +class ToolCallRequest(BaseModel): + node_id: str # 使用 node_id 精确指定要调用的节点 + arguments: Dict[str, Any] + +@app.post("/env/{case_id}/tool_call") +def tool_call(case_id: str, req: ToolCallRequest): + """Executes a tool and triggers item drops.""" + logger.info(f"Tool call request - case_id: {case_id}, node_id: {req.node_id}, args: {list(req.arguments.keys())}") + STATS["tool_calls"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + + # 通过 node_id 精确查找节点 + node_id = req.node_id + if node_id not in scenario.nodes: + logger.error(f"Node not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + tool_node = scenario.nodes[node_id] + + if not tool_node: + logger.error(f"Tool not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Tool not found") + + if not tool_node.is_revealed: + logger.warning(f"Attempt to call hidden tool: {node_id}") + return {"ok": False, "error": "Tool is not visible yet."} + + if tool_node.type != "Tool": + logger.warning(f"Attempt to call non-tool node: {node_id} (type: {tool_node.type})") + return {"ok": False, "error": "Only tools can be called."} + + # 1. Execute Tool (Real Execution via Simulator) + simulator = SIMULATORS[case_id] + + # Get tool name from template_id if available, otherwise use node name + tool_name = tool_node.name + if case_id in RAW_NODES_DATA and node_id in RAW_NODES_DATA[case_id]: + template_id = RAW_NODES_DATA[case_id][node_id].get('template_id') + if template_id: + tool_name = template_id + + # 文件处理工具和 Terminal 需要验证输入并返回预先计算的输出 + # 传递节点的实际输入输出值(从 DAG 执行后填充的数据) + tool_arguments = dict(req.arguments) # Make a copy + + # 传递节点的 golden values(从 JSON 的 inputs[].value 和 outputs[].value 加载) + # 用于在评测阶段验证被测模型传入的参数是否正确 + if tool_node.golden_input_values: + tool_arguments['_golden_inputs'] = tool_node.golden_input_values + if tool_node.golden_output_values: + tool_arguments['_golden_outputs'] = tool_node.golden_output_values + + logger.debug(f"Executing tool {tool_name} (node: {tool_node.name}) with args {tool_arguments}") + + try: + output_values = simulator.execute(tool_name, tool_arguments) + logger.info(f"Tool invoked - {tool_name}: {list(output_values.keys())}") + except Exception as e: + logger.error(f"Tool execution failed - {tool_name}: {str(e)}", exc_info=True) + return {"ok": False, "error": f"Tool execution failed: {str(e)}"} + + # 检查验证结果(精细化错误反馈) + validation = output_values.pop("_validation", {"valid": True}) + + if not validation["valid"]: + # 根据错误类型构造友好的错误消息 + error_type = validation.get("error_type") + + if error_type == "missing_required": + missing = validation.get("missing_params", []) + error_msg = f"Error: Missing required parameters {', '.join(missing)}" + + elif error_type == "type_error": + param = validation.get("param_name") + message = validation.get("message", "Parameter type error") + error_msg = f"Error: {message}" + + elif error_type == "incomplete_optional": + provided = validation.get("provided_params", []) + missing = validation.get("missing_params", []) + error_msg = ( + f"Hint: You provided some parameters ({', '.join(provided)}), " + f"but may also need: {', '.join(missing)}.\n" + f"Trying to provide these parameters together might yield better results." + ) + + elif error_type == "value_mismatch": + param = validation.get("param_name") + hint = validation.get("hint", "Parameter value may be incorrect") + error_msg = f"Hint: {hint}.\nPlease check if this parameter value meets the requirements." + + else: + error_msg = validation.get("hint") or validation.get("message", "Parameter validation failed") + + logger.info(f"Tool validation failed - {tool_name}: {error_type}") + return { + "ok": False, + "error": error_msg, + "error_type": error_type + } + + # Simulate success + tool_node.if_success = True + + # 【关键】将本次执行的输出值追加到历史列表(用于渐进式暴露判断) + # 每次调用都会记录,不会覆盖之前的执行结果 + tool_node.actual_outputs_history.append(dict(output_values)) + + # 2. 检查是否应该触发掉落(只有输入参数正确时才掉落) + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, tool_node.golden_input_values) + + newly_revealed = [] + investigate_hints = [] # 提示模型哪些节点可以 investigate 来发现隐藏内容 + + if inputs_match_golden: + logger.info(f"✓ Tool inputs match golden - node: {node_id}, triggering drops") + + # 检查该工具是否有 ITEM 或 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == tool_node.id: + target_node = scenario.nodes[edge.target_id] + + # ITEM 边:立即掉落(主动掉落) + if edge.connection_type == InterfaceType.ITEM: + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from {node_id})") + + # HIDDEN_ITEM 边:不立即掉落,标记并提示(被动掉落) + elif edge.connection_type == InterfaceType.HIDDEN_ITEM: + # 标记该工具有待触发的 HIDDEN_ITEM 掉落 + tool_node.has_hidden_item_ready = True + + # 提示模型可以 investigate 这个工具来发现隐藏内容 + hint_info = { + "tool_id": tool_node.id, + "hint": f"Tool '{tool_node.id}' seems to hide something, try investigating it to discover more information" + } + # if tool_node.name: + # hint_info["tool_name"] = tool_node.name + + investigate_hints.append(hint_info) + logger.info(f"HIDDEN_ITEM ready: {tool_node.id} -> {target_node.id} (will drop on investigate)") + else: + logger.info(f"✗ Tool inputs do NOT match golden - node: {node_id}, no drops triggered") + + response = { + "ok": True, + "message": "Tool invoked", + "output_values": output_values # Return raw outputs to Agent + } + + # 【新增】对源头节点进行参数验证反馈 + # 源头节点:没有数据流入边的节点,这些节点的参数需要模型自己推理 + # 验证模型使用的参数是否正确,并提供明确的反馈 + if _is_source_node(node_id, scenario) and tool_node.golden_input_values: + validation_feedback = _get_parameter_validation_feedback(req.arguments, tool_node.golden_input_values) + + if validation_feedback["all_correct"]: + # 用户提交了全部 golden 参数且全部正确 + response["parameter_feedback"] = { + "status": "correct", + "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." + } + logger.info(f"✓ Source node parameters all correct - node: {node_id}") + elif validation_feedback["incorrect_params"]: + # 有提交了但值错误的参数,只对这些参数给出反馈 + incorrect_list = [] + for param_name in validation_feedback["incorrect_params"]: + incorrect_list.append(f" - Parameter '{param_name}' is incorrect") + + correct_info = "" + if validation_feedback["correct_params"]: + correct_info = f"\n✓ Correct parameters: {', '.join(validation_feedback['correct_params'])}" + + response["parameter_feedback"] = { + "status": "incorrect", + "message": ( + f"⚠️ Some parameters are incorrect:\n" + + "\n".join(incorrect_list) + + correct_info + + 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." + ), + "incorrect_params": validation_feedback["incorrect_params"], + "correct_params": validation_feedback["correct_params"] + } + logger.info(f"✗ Source node parameters incorrect - node: {node_id}, incorrect: {validation_feedback['incorrect_params']}") + # else: 部分提交且全部正确 → 不给任何 parameter_feedback,避免对未提交的参数发表意见 + + # 检查工具调用是否完全正确(输出与 golden outputs 匹配) + # 用于给模型正向反馈,让它知道这个工具已经正确调用过,避免重复调用 + # 注意:只有当输出完全匹配时才标记为 correct,不会在错误时提供具体错误信息 + # if tool_node.golden_output_values and output_values: + # is_correct = True + # for port_name, expected_value in tool_node.golden_output_values.items(): + # actual_value = output_values.get(port_name) + # if str(actual_value) != str(expected_value): + # is_correct = False + # break + + # if is_correct: + # response["tool_call_correct"] = True + # logger.info(f"✓ Tool called with correct result - node: {node_id}") + + # 只在有新内容掉落时才返回 newly_revealed + if newly_revealed: + response["newly_revealed"] = newly_revealed + + # 添加 investigate 提示(对于有待触发 HIDDEN_ITEM 掉落的工具) + if investigate_hints: + response["investigate_hints"] = investigate_hints + + # 3. 渐进式暴露机制 - 现在完全由 ITEM/HIDDEN_ITEM 边控制 + # 旧机制(基于 golden_input 检查)已被禁用 + # 新机制中,节点的可见性只由 ITEM/HIDDEN_ITEM 边触发决定 + # 上面的 ITEM/HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, output_values, tool_node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # response["newly_revealed"] = newly_revealed + # logger.info(f"Progressive reveal: {len(progressive_revealed)} nodes now ready") + + # Check if this is the win node + if node_id == scenario.win_node_id: + # 验证输出值是否等于预期的胜利值 + # 从节点的 golden_output_values 中获取预期值(在 _initialize_node_values 时从 JSON 加载) + expected_outputs = tool_node.golden_output_values + + # 检查实际输出是否与预期输出匹配 + is_correct = False + victory_string = None + mismatch_info = [] + + if expected_outputs and output_values: + # 检查每个预期输出端口的值是否匹配 + is_correct = True + for port_name, expected_value in expected_outputs.items(): + actual_value = output_values.get(port_name) + if actual_value != expected_value: + is_correct = False + mismatch_info.append(f"Port '{port_name}': expected '{expected_value}', actual '{actual_value}'") + logger.warning(f"Win node output mismatch - port: {port_name}, expected: {expected_value}, actual: {actual_value}") + + # 如果所有输出都匹配,使用第一个输出作为胜利字符串 + if is_correct and output_values: + victory_string = list(output_values.values())[0] + else: + logger.warning(f"Win node called but missing output values - expected: {expected_outputs}, actual: {output_values}") + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型调用工具获得输出后,需要自己识别这是否是胜利字符串并提交 + if is_correct: + logger.info(f"🎯 Win node called with correct output - case: {case_id}, node: {node_id}, victory: {victory_string}") + else: + logger.info(f"❌ Win node called with incorrect output - case: {case_id}, node: {node_id}") + + return response + +class UseItemRequest(BaseModel): + node_id: str = Field(..., description="The ID of the Item node to use (must be Item type)") + arguments: Dict[str, Any] = Field(default_factory=dict, description="Input arguments to provide to the item") + +@app.post("/env/{case_id}/use_item") +def use_item(case_id: str, req: UseItemRequest): + """ + Use an Item node by providing input arguments. + + This is specifically for Item nodes that require parameters to be "unlocked" or "activated", + such as containers that need a password/fingerprint. + + - Validates that the node is of type Item + - Checks if provided arguments match the item's golden_input_values + - If match: triggers ITEM-type edge drops and returns the item's content + - If not match: returns error message + """ + logger.info(f"Use item request - case_id: {case_id}, node_id: {req.node_id}, args: {req.arguments}") + STATS["use_items"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + item_node = scenario.nodes[req.node_id] + + if not item_node.is_revealed: + logger.warning(f"Attempt to use hidden item: {req.node_id}") + return {"ok": False, "error": "Item is not visible yet."} + + if item_node.type != "Item": + logger.warning(f"Attempt to use non-item node: {req.node_id} (type: {item_node.type})") + return {"ok": False, "error": "Only Item nodes can be used with use_item. Tools should be called with tool_call."} + + # 【新增】检查该 Item 是否已经被成功解锁 + # 如果已经被正确使用过,直接返回成功提示 + if item_node.if_success: + logger.info(f"Item already unlocked, returning success message: {req.node_id}") + return { + "ok": True, + "message": "This item has already been successfully unlocked by you." + } + + # 检查该 Item 是否真的需要通过 use_item 提供参数 + # 只有当 Item 有非 Item/Hidden_Item 类型的输入时,才应该使用 use_item + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + non_hidden_inputs = [ + inp for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + if not non_hidden_inputs: + # 该 Item 不需要参数,应该只使用 investigate + logger.warning(f"Attempt to use_item on a node that doesn't require parameters: {req.node_id}") + return { + "ok": False, + "error": "This item does not require parameters. Please use investigate to examine the item directly." + } + + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, item_node.golden_input_values) + + if not inputs_match_golden: + logger.info(f"✗ Item inputs do NOT match golden - node: {req.node_id}") + # 提供更详细的错误信息,帮助 Agent 理解问题 + # 只显示非 Item/Hidden_Item 类型的参数(Hidden_Item 由系统自动处理) + expected_params = [] + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + expected_params = [ + inp.get("name") for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + provided_params = list(req.arguments.keys()) if req.arguments else [] + + # 检查参数名是否匹配 + if set(expected_params) == set(provided_params): + # 参数名正确但值不匹配 - 不泄漏正确的值 + error_msg = f"Parameter names are correct, but the parameter values are incorrect. Please try using different parameter values." + else: + error_msg = f"Parameter names do not match. Expected parameter names: {expected_params}, you provided: {provided_params}." + + return { + "ok": False, + "error": error_msg + } + + logger.info(f"✓ Item inputs match golden - node: {req.node_id}, activating item") + + # 标记该 Item 已被正确使用 + item_node.if_success = True + + # 将 golden_output_values 追加到 actual_outputs_history + if item_node.golden_output_values: + item_node.actual_outputs_history.append(dict(item_node.golden_output_values)) + + # 触发 ITEM 类型边的掉落 + newly_revealed = [] + for edge in scenario.edges: + if edge.source_id == item_node.id and edge.connection_type == InterfaceType.ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from use_item on {req.node_id})") + + # 检查是否为 Win Node + win_node_id = scenario.win_node_id + is_win_node = (req.node_id == win_node_id) + + # 构建返回结果 + result = { + "ok": True, + "message": "Item used successfully.", + "content": item_node.golden_output_values if item_node.golden_output_values else None + } + + # 获取 narrative(如果存在) + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + narrative = raw_nodes_data[req.node_id].get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 如果是 Win Node,只记录日志 + if is_win_node: + logger.info(f"Win node (Item) unlocked via use_item - case: {case_id}, node: {req.node_id}") + + return result + + +class SubmitAnswerRequest(BaseModel): + answer: str = Field(..., description="The victory string to submit") + +@app.post("/env/{case_id}/submit_answer") +def submit_answer(case_id: str, req: SubmitAnswerRequest): + """ + 提交答案接口 + 被测模型在获得胜利字符串提示后,需要调用此接口提交答案 + """ + logger.info(f"Submit answer request - case_id: {case_id}, answer: {req.answer}") + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + + # 获取 win_node 的 golden_output_values + if not scenario.win_node_id: + logger.error(f"No win node defined for case: {case_id}") + return { + "ok": False, + "error": "This case has no victory node defined" + } + + win_node = scenario.nodes.get(scenario.win_node_id) + if not win_node: + logger.error(f"Win node not found: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node does not exist" + } + + # 获取正确的胜利字符串(取第一个 golden_output_value) + if win_node.golden_output_values: + correct_answer = list(win_node.golden_output_values.values())[0] + else: + logger.error(f"Win node has no golden_output_values: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node has no correct answer" + } + + # 验证提交的答案 + if req.answer == correct_answer: + logger.info(f"🎉 CORRECT ANSWER SUBMITTED - case: {case_id}, answer: {req.answer}") + return { + "ok": True, + "is_win": True, + "victory_message": f"🎉 Congratulations on successfully escaping the room! Your answer is correct: {req.answer}" + } + else: + logger.info(f"❌ INCORRECT ANSWER SUBMITTED - case: {case_id}, submitted: {req.answer}, correct: {correct_answer}") + return { + "ok": True, + "is_win": False, + "error": f"The submitted answer is incorrect. You submitted: {req.answer}" + } + +if __name__ == "__main__": + + uvicorn.run(app, host="0.0.0.0", port=8000) \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-b5fbf361/environment/puzzle/upstream/simulator.py b/tasks/agentescape-25-skeleton-b5fbf361/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-25-skeleton-b5fbf361/environment/puzzle/upstream/simulator.py @@ -0,0 +1,2911 @@ +import hashlib +import hmac +import base64 +import binascii +import zlib +import json +import uuid +import math +import re +from typing import Dict, Any, List + +class ToolSimulator: + def __init__(self): + """工具模拟器 + + 文件处理工具(zip_unzip, zip_unzip_file, zip_unzip_item, json_get, csv_query, + regex_search, graph_shortest_path)不需要真实文件系统。 + 这些工具只验证输入参数,然后返回预先初始化好的 golden_outputs。 + """ + self.tool_map = { + # 数论 + "calc_bigmul": self.calc_bigmul, + "calc_modexp": self.calc_modexp, + "calc_modexp_int": self.calc_modexp_int, + "calc_gcd": self.calc_gcd, + "calc_gcd_int": self.calc_gcd_int, + "calc_inv_mod": self.calc_inv_mod, + "calc_inv_mod_int": self.calc_inv_mod_int, + + # 哈希 + "hash_sha256": self.hash_sha256, + "hash_md5": self.hash_md5, + "hmac_sha256": self.hmac_sha256, + + # 编码 + "base64_decode": self.base64_decode, + "base64_encode": self.base64_encode, + "hex_decode": self.hex_decode, + "hex_encode": self.hex_encode, + "zlib_inflate": self.zlib_inflate, + "zlib_deflate": self.zlib_deflate, + + # 文件 + "zip_unzip": self.zip_unzip, + "zip_unzip_file": self.zip_unzip_file, + "zip_unzip_item": self.zip_unzip_item, + "regex_search": self.regex_search, + "json_get": self.json_get, + "csv_query": self.csv_query, + "code_py_exec": self.code_py_exec, + + # 图 + "graph_shortest_path": self.graph_shortest_path, + + # 加解密 (简化模拟) + "crypto_aes_cbc_decrypt": self.crypto_aes_cbc_decrypt, + "crypto_rsa_decrypt_hex": self.crypto_rsa_decrypt_hex, + + # 其他 + "num_base_convert": self.num_base_convert, + "time_convert": self.time_convert, + "checksum_crc32": self.checksum_crc32, + "geo_haversine": self.geo_haversine, + "otp_totp_generate": self.otp_totp_generate, + "unicode_norm": self.unicode_norm, + "text_bidi_sanitize": self.text_bidi_sanitize, + "text_xor_hex": self.text_xor_hex, + "text_rotN": self.text_rotN, + "luhn_check": self.luhn_check, + "iban_validate": self.iban_validate, + + # 物理 + "matter_synthesizer": self.matter_synthesizer, + + # 终端机 + "terminal_1": self.terminal_1, + "terminal_2": self.terminal_2, + "Logic Terminal": self.logic_terminal, + "Math Terminal": self.math_terminal, + "Encryption Terminal": self.crypt_terminal, + "Sequence Terminal": self.sequence_terminal + } + + def execute(self, tool_name: str, inputs: Dict[str, Any]) -> Dict[str, Any]: + if tool_name not in self.tool_map: + # Fallback for unknown tools: return dummy outputs based on expected output types + # This should ideally not happen if all tools are implemented + return {} + + try: + return self.tool_map[tool_name](inputs) + except Exception as e: + print(f"Error executing {tool_name}: {e}") + # Return empty or error indication? For generation, we might want to fail hard or return dummy. + # For now, return dummy to keep flow going, but log error. + return {} + + # --- Implementations --- + + def calc_bigmul(self, inputs): + # Check if required parameters are present + if "a" not in inputs or "b" not in inputs: + raise ValueError("Missing required parameters 'a' and/or 'b'") + + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + return {"product": str(a * b)} + except (ValueError, TypeError) as e: + raise ValueError(f"Failed to convert parameters to integers: {str(e)}") + + def calc_modexp(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + try: + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if isinstance(base, str): + base = int(base) + elif not isinstance(base, int): + raise ValueError("Parameter 'base' must be a string or integer") + + if isinstance(exp, str): + exp = int(exp) + elif not isinstance(exp, int): + raise ValueError("Parameter 'exp' must be a string or integer") + + if isinstance(mod, str): + mod = int(mod) + elif not isinstance(mod, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": str(pow(base, exp, mod))} + + def calc_modexp_int(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["base"], int): + raise ValueError("Parameter 'base' must be an integer") + if not isinstance(inputs["exp"], int): + raise ValueError("Parameter 'exp' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": pow(base, exp, mod)} + + def calc_gcd(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + # 计算 GCD 并返回字符串格式(符合 Big_Int 输出类型) + result = math.gcd(a, b) + return {"gcd": str(result)} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def calc_gcd_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["b"], int): + raise ValueError("Parameter 'b' must be an integer") + + # 获取参数 + a = inputs["a"] + b = inputs["b"] + + return {"gcd": math.gcd(a, b)} + + def calc_inv_mod(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + m = inputs["mod"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(m, str): + m = int(m) + elif not isinstance(m, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": str(pow(a, -1, m))} + except ValueError as e: + # 模逆不存在时,返回一个特殊值(用于数据传递) + # 在 DAG 生成阶段,这允许数据流继续 + return {"inv": str(a)} + + def calc_inv_mod_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + a = inputs["a"] + m = inputs["mod"] + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": pow(a, -1, m)} + except ValueError as e: + raise ValueError(f"Modular inverse does not exist: {str(e)}") + + def hash_sha256(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.sha256(text.encode()).hexdigest()} + + def hash_md5(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.md5(text.encode()).hexdigest()} + + def hmac_sha256(self, inputs): + # 参数检查 + if "hex_key" not in inputs: + raise ValueError("Missing required parameter: hex_key") + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["hex_key"], str): + raise ValueError("Parameter 'hex_key' must be a string") + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + try: + key = bytes.fromhex(inputs["hex_key"]) + text = inputs["text"].encode() + return {"hex": hmac.new(key, text, hashlib.sha256).hexdigest()} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def base64_decode(self, inputs): + # 参数检查 + if "data" not in inputs: + raise ValueError("Missing required parameter: data") + + # 类型检查 + if not isinstance(inputs["data"], str): + raise ValueError("Parameter 'data' must be a string") + + data = inputs["data"] + try: + return {"bytes_hex": binascii.hexlify(base64.b64decode(data)).decode()} + except Exception as e: + raise ValueError(f"Base64 decode error: {str(e)}") + + def base64_encode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"b64": base64.b64encode(bytes.fromhex(hex_data)).decode()} + except Exception as e: + raise ValueError(f"Base64 encode error: {str(e)}") + + def hex_decode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"text": bytes.fromhex(hex_data).decode('utf-8', errors='ignore')} + except Exception as e: + raise ValueError(f"Hex decode error: {str(e)}") + + def hex_encode(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + try: + return {"hex": text.encode().hex()} + except Exception as e: + raise ValueError(f"Hex encode error: {str(e)}") + + + # 到此处实现已经更新 + + def zlib_inflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("Parameter 'hex' must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("Missing required parameter: hex") + + try: + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空字符串 + if not hex_data: + raise ValueError("Empty hex string provided") + + # 检查十六进制字符串的有效性 + if len(hex_data) % 2 != 0: + raise ValueError("Hex string must have even length") + + # 检查是否只包含有效的十六进制字符 + if not all(c in '0123456789abcdefABCDEF' for c in hex_data): + raise ValueError("Invalid hex string provided") + + # 尝试解压缩 + return {"text": zlib.decompress(bytes.fromhex(hex_data)).decode('utf-8')} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hex string provided") from e + raise ValueError(f"Invalid zlib data: {e}") from e + except Exception as e: + raise RuntimeError(f"Failed to inflate data: {e}") from e + + def zlib_deflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("Parameter 'text' must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("Missing required parameter: text") + + try: + # 压缩文本 + return {"hex": zlib.compress(text.encode('utf-8')).hex()} + except Exception as e: + raise RuntimeError(f"Failed to deflate data: {e}") from e + + # --- File Operations --- + + def zip_unzip(self, inputs): + """ZIP 解压工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"files": golden_outputs.get("files", "")} + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return {"files": golden_outputs.get("files", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "files" in golden_outputs: + # 验证必需参数 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 检查类型 + if has_zip_id and not isinstance(zip_id, str): + return {"error": "Parameter 'zip_id' must be a string type"} + if has_password and not isinstance(password, str): + return {"error": "Parameter 'password' must be a string type"} + + # 验证输入是否与预期匹配 + if golden_inputs: + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return {"files": golden_outputs["files"]} + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + # 没有golden_inputs但有golden_outputs,直接返回输出 + return {"files": golden_outputs["files"]} + + # 如果没有预期输出,返回空结果 + return {"files": ""} + + def regex_search(self, inputs): + """正则搜索工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"matches": golden_outputs.get("matches", "[]")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "matches" in golden_outputs: + # 提取实际参数 + pattern = inputs.get("pattern") + file_id = inputs.get("file_id") + text = inputs.get("text") + + # 1. 检查必需参数 + if pattern is None: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["pattern"], + "message": "Missing required parameter 'pattern'" + } + } + + # 类型检查 + if not isinstance(pattern, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "pattern", + "message": "Parameter 'pattern' must be a string type" + } + } + if file_id is not None and not isinstance(file_id, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if text is not None and not isinstance(text, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "text", + "message": "Parameter 'text' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合 + provided_params = {} + if pattern is not None: + provided_params["pattern"] = pattern + if file_id is not None: + provided_params["file_id"] = file_id + if text is not None: + provided_params["text"] = text + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数(关键改进) + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_pattern = golden_inputs.get("pattern") + expected_file_id = golden_inputs.get("file_id") + expected_text = golden_inputs.get("text") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_pattern is not None: + if str(pattern) != str(expected_pattern): + incorrect_params.append("pattern") + else: + correct_params.append("pattern") + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_text is not None: + if str(text) != str(expected_text): + incorrect_params.append("text") + else: + correct_params.append("text") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "matches": "[]", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "matches": golden_outputs["matches"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空列表 + return {"matches": "[]"} + + def json_get(self, inputs): + """JSON 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"values": golden_outputs.get("values", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "values" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + jsonpath = inputs.get("jsonpath", "") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if jsonpath is not None and not isinstance(jsonpath, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "jsonpath", + "message": "Parameter 'jsonpath' must be a string type" + } + } + + # 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:jsonpath有默认值"") + provided_params = {} + if file_id is not None: + provided_params["file_id"] = file_id + if jsonpath != "": + provided_params["jsonpath"] = jsonpath + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_jsonpath = golden_inputs.get("jsonpath") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_jsonpath is not None: + if str(jsonpath) != str(expected_jsonpath): + incorrect_params.append("jsonpath") + else: + correct_params.append("jsonpath") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "values": "", + "_validation": validation_info + } + + # 所有验证通过,返回正确输出 + return { + "values": golden_outputs["values"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"values": ""} + + def csv_query(self, inputs): + """CSV 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"rows": golden_outputs.get("rows", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "rows" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + select_columns = inputs.get("select", "") + where_clause = inputs.get("where", "") + + # 1. 检查必需参数 + if file_id is None: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["file_id"], + "message": "Missing required parameter 'file_id'" + } + } + + # 类型检查 + if not isinstance(file_id, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if not isinstance(select_columns, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "select", + "message": "Parameter 'select' must be a string type" + } + } + if not isinstance(where_clause, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "where", + "message": "Parameter 'where' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:select和where有默认值"") + provided_params = {"file_id": file_id} + if select_columns != "": + provided_params["select"] = select_columns + if where_clause != "": + provided_params["where"] = where_clause + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_select = golden_inputs.get("select") + expected_where = golden_inputs.get("where") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_select is not None: + if str(select_columns) != str(expected_select): + incorrect_params.append("select") + else: + correct_params.append("select") + + if expected_where is not None: + if str(where_clause) != str(expected_where): + incorrect_params.append("where") + else: + correct_params.append("where") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "rows": "", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "rows": golden_outputs["rows"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"rows": ""} + + def graph_shortest_path(self, inputs): + """图最短路径工具 + + 如果有 _golden_outputs 或 _init_outputs,验证输入并返回预设输出。 + 否则执行真实的 Dijkstra 算法。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 检查是否在预设模式中(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + if golden_outputs and "path" in golden_outputs: + # 评测阶段但没有 golden_inputs,直接返回 outputs + if not golden_inputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 评测模式:验证输入参数是否匹配 golden 值 + src = inputs.get("src") + dst = inputs.get("dst") + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + + has_src = src is not None and src != "" + has_dst = dst is not None and dst != "" + + # 验证必需参数 + if not has_src or not has_dst: + missing = [] + if not has_src: + missing.append("src") + if not has_dst: + missing.append("dst") + return {"error": "Missing required parameters: " + ", ".join(missing)} + + # 类型检查 + if not isinstance(src, str): + return {"error": "Parameter 'src' must be a string"} + if not isinstance(dst, str): + return {"error": "Parameter 'dst' must be a string"} + + # 验证输入是否匹配期望值 + if golden_inputs: + expected_src = golden_inputs.get("src") + expected_dst = golden_inputs.get("dst") + expected_file_id = golden_inputs.get("file_id") + expected_graph_data = golden_inputs.get("graph_data") + + # 收集验证结果 + incorrect_params = [] + correct_params = [] + + # 检查必需参数是否匹配 + if expected_src is not None: + if str(src) != str(expected_src): + incorrect_params.append("src") + else: + correct_params.append("src") + + if expected_dst is not None: + if str(dst) != str(expected_dst): + incorrect_params.append("dst") + else: + correct_params.append("dst") + + # 检查可选参数(如果在 expected_inputs 中定义了) + if expected_file_id is not None: + if file_id != expected_file_id: + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_graph_data is not None: + if graph_data != expected_graph_data: + incorrect_params.append("graph_data") + else: + correct_params.append("graph_data") + + # 如果有参数不正确,返回详细的反馈 + if incorrect_params: + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 验证通过,返回预设的输出 + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 获取参数(真实执行路径) + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + # Support both src/dst (interface definition) and start/end (original implementation) + start = inputs.get("src") + end = inputs.get("dst") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + raise TypeError("file_id must be a string") + + if graph_data is not None and not isinstance(graph_data, str): + raise TypeError("graph_data must be a string") + + if start is not None and not isinstance(start, str): + raise TypeError("src/start must be a string") + + if end is not None and not isinstance(end, str): + raise TypeError("dst/end must be a string") + + # 检查必需参数 + if file_id is None and graph_data is None: + raise ValueError("Either file_id or graph_data must be provided") + + if start is None: + raise ValueError("src/start parameter is required") + + if end is None: + raise ValueError("dst/end parameter is required") + + # Get graph content + content = None + if file_id is not None: + # 尝试从 VFS 获取(如果存在) + if hasattr(self, 'vfs') and file_id in self.vfs: + content = self.vfs[file_id] + else: + # VFS 不存在或文件不在 VFS 中 + # 返回一个默认的空图结果,或者抛出错误提示需要 init_outputs + raise ValueError( + f"File '{file_id}' not found. For tools that require files, " + f"please provide init_outputs in the initial_values." + ) + elif graph_data is not None: + content = graph_data + + if content is None: + content = "{}" + + try: + # Parse graph data + graph = json.loads(content) + + # 类型检查 + if not isinstance(graph, dict): + raise TypeError("Graph data must be a dictionary") + + # If graph is not in the expected format, try to extract adjacency list + if "nodes" in graph and "edges" in graph: + # 验证nodes和edges的类型 + if not isinstance(graph["nodes"], list): + raise TypeError("Nodes must be a list") + + if not isinstance(graph["edges"], list): + raise TypeError("Edges must be a list") + + # Convert from nodes/edges format to adjacency list + adjacency_list = {} + for node in graph["nodes"]: + # 验证node类型 + if not isinstance(node, dict): + raise TypeError("Each node must be a dictionary") + + # Use node ID as key, not the entire node dictionary + node_id = node.get("id", "") + if node_id: + adjacency_list[node_id] = {} + + for edge in graph["edges"]: + # 验证edge类型 + if not isinstance(edge, dict): + raise TypeError("Each edge must be a dictionary") + + u = edge["from"] + v = edge["to"] + weight = edge.get("weight", 1) # Default to unweighted + + # 类型检查 + if not isinstance(u, str): + raise TypeError("Edge 'from' must be a string") + + if not isinstance(v, str): + raise TypeError("Edge 'to' must be a string") + + if not isinstance(weight, (int, float)): + raise TypeError("Edge weight must be a number") + + if u not in adjacency_list: + adjacency_list[u] = {} + if v not in adjacency_list: + adjacency_list[v] = {} + + adjacency_list[u][v] = weight + # If undirected, add reverse edge + if not edge.get("directed", False): + adjacency_list[v][u] = weight + elif isinstance(graph, dict): + # Already in adjacency list format + adjacency_list = graph + + # 验证邻接表结构 + for node, neighbors in adjacency_list.items(): + if not isinstance(neighbors, dict): + raise TypeError("Adjacency list must be a dictionary of dictionaries") + + for neighbor, weight in neighbors.items(): + if not isinstance(weight, (int, float)): + raise TypeError("Edge weights must be numbers") + else: + raise TypeError("Graph data must be a dictionary") + + # 检查起点和终点是否为空 + if not start: + raise ValueError("Start node cannot be empty") + + if not end: + raise ValueError("End node cannot be empty") + + # 检查起点和终点是否在图中 + if start not in adjacency_list: + raise ValueError(f"Start node '{start}' not found in graph") + + if end not in adjacency_list: + raise ValueError(f"End node '{end}' not found in graph") + + # Dijkstra's algorithm implementation + import heapq + + # Initialize distances and previous nodes + distances = {node: float('infinity') for node in adjacency_list} + previous = {node: None for node in adjacency_list} + distances[start] = 0 + + # Priority queue + pq = [(0, start)] + heapq.heapify(pq) + + while pq: + current_dist, current_node = heapq.heappop(pq) + + # If we've reached the end node, we can break early + if current_node == end: + break + + # Nodes can be added multiple times to the priority queue, but we only process them once + if current_dist > distances[current_node]: + continue + + # Explore neighbors + for neighbor, weight in adjacency_list[current_node].items(): + distance = current_dist + weight + + # If a shorter path is found + if distance < distances[neighbor]: + distances[neighbor] = distance + previous[neighbor] = current_node + heapq.heappush(pq, (distance, neighbor)) + + # Reconstruct the shortest path + path = [] + current = end + while current is not None: + path.append(current) + current = previous[current] + path.reverse() # Reverse to get from start to end + + # Check if path exists + if not path or path[0] != start: + return {"path": "[]", "cost": 0} + + return { + "path": json.dumps(path), + "cost": distances[end] + } + except json.JSONDecodeError as e: + raise ValueError(f"Invalid JSON in graph data: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in graph_shortest_path: {str(e)}") + + # --- Crypto (Simplified) --- + def crypto_aes_cbc_decrypt(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 (使用模板中定义的参数名) + hex_cipher = inputs.get("hex_cipher") + hex_key = inputs.get("hex_key") + hex_iv = inputs.get("hex_iv") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + + if hex_key is not None and not isinstance(hex_key, str): + raise TypeError("hex_key must be a string") + + if hex_iv is not None and not isinstance(hex_iv, str): + raise TypeError("hex_iv must be a string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + + if hex_key is None: + raise ValueError("hex_key parameter is required") + + if hex_iv is None: + raise ValueError("hex_iv parameter is required") + + from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes + from cryptography.hazmat.backends import default_backend + from cryptography.hazmat.primitives import padding + + try: + # Convert hex strings to bytes + ciphertext = bytes.fromhex(hex_cipher) + key = bytes.fromhex(hex_key) + iv = bytes.fromhex(hex_iv) + + # Validate key length (AES-128, AES-192, AES-256) + if len(key) not in [16, 24, 32]: + raise ValueError("Invalid key length. Must be 16, 24, or 32 bytes.") + + if len(iv) != 16: + raise ValueError("Invalid IV length. Must be 16 bytes.") + + # Create cipher object + cipher = Cipher( + algorithms.AES(key), + modes.CBC(iv), + backend=default_backend() + ) + + decryptor = cipher.decryptor() + + # Decrypt the ciphertext + padded_plaintext = decryptor.update(ciphertext) + decryptor.finalize() + + # Remove PKCS7 padding + unpadder = padding.PKCS7(128).unpadder() + plaintext = unpadder.update(padded_plaintext) + unpadder.finalize() + + # Return decrypted text + return {"text": plaintext.decode('utf-8', errors='ignore')} + except ValueError as e: + if "non-hexadecimal number found in fromhex()" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher, hex_key, or hex_iv") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in crypto_aes_cbc_decrypt: {str(e)}") + + def crypto_rsa_decrypt_hex(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_cipher = inputs.get("hex_cipher") + n = inputs.get("n") + d = inputs.get("d") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + if n is not None and not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + if d is not None and not isinstance(d, (int, str)): + raise TypeError("d must be an integer or string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + if n is None: + raise ValueError("n parameter is required") + if d is None: + raise ValueError("d parameter is required") + + try: + # Convert parameters to appropriate types + cipher_int = int(hex_cipher, 16) + n_int = int(n) if isinstance(n, str) else n + d_int = int(d) if isinstance(d, str) else d + + # RSA decryption: plaintext = ciphertext^d mod n + plaintext_int = pow(cipher_int, d_int, n_int) + + # Convert result to hex and then to text + plaintext_hex = hex(plaintext_int)[2:] + + # Pad with leading zero if odd length + if len(plaintext_hex) % 2 != 0: + plaintext_hex = '0' + plaintext_hex + + # Convert hex to bytes and then to text + try: + plaintext_bytes = bytes.fromhex(plaintext_hex) + plaintext_text = plaintext_bytes.decode('utf-8', errors='ignore') + except: + # If decoding fails, return hex representation + plaintext_text = plaintext_hex + + return {"text": plaintext_text} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in crypto_rsa_decrypt_hex: {str(e)}") + + # --- Others --- + def num_base_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + s = inputs.get("s") + from_base = inputs.get("from_base") + to_base = inputs.get("to_base") + + # 类型检查 - 接受 str 或 int + if s is not None and not isinstance(s, (str, int)): + raise TypeError("s must be a string or integer") + + if from_base is not None and not isinstance(from_base, (int, str)): + raise TypeError("from_base must be an integer") + + if to_base is not None and not isinstance(to_base, (int, str)): + raise TypeError("to_base must be an integer") + + # 检查必需参数 + if s is None: + raise ValueError("s parameter is required") + + if from_base is None: + raise ValueError("from_base parameter is required") + + if to_base is None: + raise ValueError("to_base parameter is required") + + try: + # Convert to int if needed + from_base = int(from_base) if isinstance(from_base, str) else from_base + to_base = int(to_base) if isinstance(to_base, str) else to_base + s_str = str(s) + + # 验证基数范围 + if from_base < 2 or from_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + if to_base < 2 or to_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + # Convert from source base to decimal + val = int(s_str, from_base) + + # Convert from decimal to target base + if to_base == 10: + result = str(val) + elif to_base == 16: + result = hex(val)[2:] + elif to_base == 8: + result = oct(val)[2:] + elif to_base == 2: + result = bin(val)[2:] + else: + # Generic base conversion for other bases + if val == 0: + result = "0" + else: + digits = "0123456789abcdefghijklmnopqrstuvwxyz" + result = "" + n = abs(val) + while n: + result = digits[n % to_base] + result + n //= to_base + if val < 0: + result = "-" + result + + return {"str": result} + except ValueError as e: + raise ValueError(f"Invalid number format: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in num_base_convert: {str(e)}") + + def time_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iso = inputs.get("iso") + timestamp = inputs.get("timestamp") + datetime_str = inputs.get("datetime") + from_tz = inputs.get("from_tz") + to_tz = inputs.get("to_tz") + format_str = inputs.get("format") + + # 类型检查 + if iso is not None and not isinstance(iso, str): + raise TypeError("iso must be a string") + + if timestamp is not None and not isinstance(timestamp, (str, int, float)): + raise TypeError("timestamp must be a string, integer, or float") + + if datetime_str is not None and not isinstance(datetime_str, str): + raise TypeError("datetime must be a string") + + if from_tz is not None and not isinstance(from_tz, str): + raise TypeError("from_tz must be a string") + + if to_tz is not None and not isinstance(to_tz, str): + raise TypeError("to_tz must be a string") + + if format_str is not None and not isinstance(format_str, str): + raise TypeError("format must be a string") + + # 设置默认值 + if from_tz is None: + from_tz = "UTC" + + if to_tz is None: + to_tz = "UTC" + + import datetime + import pytz + + # 验证时区参数 + try: + if from_tz: + pytz.timezone(from_tz) + if to_tz: + pytz.timezone(to_tz) + except Exception: + raise ValueError("Invalid timezone provided") + + try: + # Parse input time + dt = None + + if iso is not None: + # Parse ISO 8601 format + dt = datetime.datetime.fromisoformat(iso.replace('Z', '+00:00')) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=pytz.UTC) + elif timestamp is not None: + # Parse Unix timestamp + timestamp = float(timestamp) + dt = datetime.datetime.fromtimestamp(timestamp, pytz.UTC) + elif datetime_str is not None: + # Parse datetime string + # Try common formats + formats_to_try = [ + "%Y-%m-%d %H:%M:%S", + "%Y-%m-%d %H:%M:%S.%f", + "%Y-%m-%d", + "%m/%d/%Y %H:%M:%S", + "%m/%d/%Y" + ] + + parse_success = False + for fmt in formats_to_try: + try: + dt = datetime.datetime.strptime(datetime_str, fmt) + dt = pytz.timezone(from_tz).localize(dt) + parse_success = True + break + except ValueError: + continue + + if not parse_success: + raise ValueError("Unable to parse datetime string with common formats") + else: + # 如果没有提供任何时间参数,则使用当前时间 + dt = datetime.datetime.now(pytz.UTC) + except ValueError as e: + raise ValueError(f"Error parsing time input: {str(e)}") + except Exception as e: + raise RuntimeError(f"Unexpected error parsing time input: {str(e)}") + + try: + # Convert timezone + if from_tz != to_tz: + dt = dt.astimezone(pytz.timezone(to_tz)) + + # Format outputs + result = { + "iso": dt.isoformat(), + "timestamp": str(dt.timestamp()), + "datetime": dt.strftime("%Y-%m-%d %H:%M:%S"), + "date": dt.strftime("%Y-%m-%d"), + "time": dt.strftime("%H:%M:%S"), + "timezone": to_tz + } + + # Add custom format if requested + if format_str: + try: + result["formatted"] = dt.strftime(format_str) + except ValueError as e: + raise ValueError(f"Invalid format string: {str(e)}") + + return result + except Exception as e: + raise RuntimeError(f"Error in time_convert: {str(e)}") + + def checksum_crc32(self, inputs): + import zlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("hex must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("hex parameter is required") + + try: + # 验证十六进制字符串 + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空 + if not hex_data: + raise ValueError("hex data cannot be empty") + + # 检查是否为有效的十六进制字符串 + if not all(c in "0123456789abcdefABCDEF" for c in hex_data): + raise ValueError("hex must be a valid hexadecimal string") + + # 检查长度是否为偶数 + if len(hex_data) % 2 != 0: + raise ValueError("hex must have even number of characters") + + val = zlib.crc32(bytes.fromhex(hex_data)) + # 确保 hex 输出是 8 位,前导补 0 + return {"hex": f"{val:08x}", "int": val} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in checksum_crc32: {str(e)}") + + def geo_haversine(self, inputs): + import math + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + lat1 = inputs.get("lat1") + lon1 = inputs.get("lon1") + lat2 = inputs.get("lat2") + lon2 = inputs.get("lon2") + + # 类型检查 + if lat1 is not None and not isinstance(lat1, (int, float, str)): + raise TypeError("lat1 must be a number or string") + if lon1 is not None and not isinstance(lon1, (int, float, str)): + raise TypeError("lon1 must be a number or string") + if lat2 is not None and not isinstance(lat2, (int, float, str)): + raise TypeError("lat2 must be a number or string") + if lon2 is not None and not isinstance(lon2, (int, float, str)): + raise TypeError("lon2 must be a number or string") + + # 检查必需参数 + if lat1 is None: + raise ValueError("lat1 parameter is required") + if lon1 is None: + raise ValueError("lon1 parameter is required") + if lat2 is None: + raise ValueError("lat2 parameter is required") + if lon2 is None: + raise ValueError("lon2 parameter is required") + + try: + # 转换为浮点数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(lat1, str): + lat1 = float(lat1) + elif not isinstance(lat1, (int, float)): + raise TypeError("lat1 must be a number or string") + else: + lat1 = float(lat1) + + if isinstance(lon1, str): + lon1 = float(lon1) + elif not isinstance(lon1, (int, float)): + raise TypeError("lon1 must be a number or string") + else: + lon1 = float(lon1) + + if isinstance(lat2, str): + lat2 = float(lat2) + elif not isinstance(lat2, (int, float)): + raise TypeError("lat2 must be a number or string") + else: + lat2 = float(lat2) + + if isinstance(lon2, str): + lon2 = float(lon2) + elif not isinstance(lon2, (int, float)): + raise TypeError("lon2 must be a number or string") + else: + lon2 = float(lon2) + + # Validate coordinates (approximate range check) + if not (-90 <= lat1 <= 90): + raise ValueError("lat1 must be between -90 and 90") + if not (-90 <= lat2 <= 90): + raise ValueError("lat2 must be between -90 and 90") + if not (-180 <= lon1 <= 180): + raise ValueError("lon1 must be between -180 and 180") + if not (-180 <= lon2 <= 180): + raise ValueError("lon2 must be between -180 and 180") + + # Earth radius in meters + R = 6371000 # Approximate radius of Earth + + # Convert degrees to radians + lat1_rad = math.radians(lat1) + lon1_rad = math.radians(lon1) + lat2_rad = math.radians(lat2) + lon2_rad = math.radians(lon2) + + # Calculate differences + delta_lat = lat2_rad - lat1_rad + delta_lon = lon2_rad - lon1_rad + + # Haversine formula + a = math.sin(delta_lat / 2) ** 2 + \ + math.cos(lat1_rad) * math.cos(lat2_rad) * \ + math.sin(delta_lon / 2) ** 2 + c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) + distance_m = R * c + + # Return distance in meters + return {"meters": round(distance_m, 2)} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in geo_haversine: {str(e)}") + + def otp_totp_generate(self, inputs): + import hmac + import hashlib + import base64 + import time + import struct + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + base32_secret = inputs.get("base32_secret") + step = inputs.get("step", 30) # Default to 30 seconds + digits = inputs.get("digits", 6) # Default to 6 digits + timestamp_iso = inputs.get("timestamp_iso", "") + algo = inputs.get("algo", "sha1") # Default to sha1 as current implementation only supports this + + # 类型检查 + if base32_secret is not None and not isinstance(base32_secret, str): + raise TypeError("base32_secret must be a string") + if not isinstance(step, (int, str)): + raise TypeError("step must be an integer or string") + if not isinstance(digits, (int, str)): + raise TypeError("digits must be an integer or string") + if not isinstance(timestamp_iso, str): + raise TypeError("timestamp_iso must be a string") + if not isinstance(algo, str): + raise TypeError("algo must be a string") + + # 检查必需参数 + if base32_secret is None: + raise ValueError("base32_secret parameter is required") + + try: + # Convert step and digits to appropriate types + step = int(step) + digits = int(digits) + if digits < 6 or digits > 8: + raise ValueError("Digits must be between 6 and 8") + + # Convert timestamp_iso to integer timestamp + if timestamp_iso: + import datetime + dt = datetime.datetime.fromisoformat(timestamp_iso.replace('Z', '+00:00')) + timestamp = int(dt.timestamp()) + else: + timestamp = int(time.time()) + + # Calculate counter value (T = floor(timestamp / step)) + counter = timestamp // step + + # Decode the base32 secret + # Add padding if necessary (base64 requires padding to be multiple of 8) + base32_secret = base32_secret.upper().replace(' ', '') + if len(base32_secret) % 8 != 0: + base32_secret += '=' * (8 - (len(base32_secret) % 8)) + key = base64.b32decode(base32_secret, casefold=True) + + # Calculate HMAC-SHA1 + counter_bytes = struct.pack('>Q', counter) # Big-endian 8-byte integer + hmac_hash = hmac.new(key, counter_bytes, hashlib.sha1).digest() + + # Dynamic truncation + offset = hmac_hash[-1] & 0xF + code = struct.unpack('>I', hmac_hash[offset:offset+4])[0] & 0x7FFFFFFF + + # Generate the OTP + otp = str(code % (10 ** digits)).zfill(digits) + + # Calculate remaining time until next OTP change + remaining_time = step - (timestamp % step) + + return {"totp": otp, "remaining_time": remaining_time, "time_step": step} + except ValueError as e: + if "invalid literal for int()" in str(e): + raise ValueError("step and digits must be valid integers") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in otp_totp_generate: {str(e)}") + + def unicode_norm(self, inputs): + import unicodedata + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + form = inputs.get("form", "NFC") # Default to NFC + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if form is not None and not isinstance(form, str): + raise TypeError("form must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Normalize form (NFC, NFD, NFKC, NFKD) + form = form.upper().strip() + + if form not in ['NFC', 'NFD', 'NFKC', 'NFKD']: + raise ValueError(f"Invalid normalization form: {form}. Must be one of: NFC, NFD, NFKC, NFKD") + + # Apply Unicode normalization + normalized_text = unicodedata.normalize(form, text) + + return {"text": normalized_text} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in unicode_norm: {str(e)}") + + def text_bidi_sanitize(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Bidi control characters to remove + bidi_controls = [ + '\u200E', # LEFT-TO-RIGHT MARK + '\u200F', # RIGHT-TO-LEFT MARK + '\u202A', # LEFT-TO-RIGHT EMBEDDING + '\u202B', # RIGHT-TO-LEFT EMBEDDING + '\u202C', # POP DIRECTIONAL FORMATTING + '\u202D', # LEFT-TO-RIGHT OVERRIDE + '\u202E', # RIGHT-TO-LEFT OVERRIDE + '\u2066', # LEFT-TO-RIGHT ISOLATE + '\u2067', # RIGHT-TO-LEFT ISOLATE + '\u2068', # FIRST STRONG ISOLATE + '\u2069', # POP DIRECTIONAL ISOLATE + ] + + # Remove all Bidi control characters + sanitized_text = text + for control_char in bidi_controls: + sanitized_text = sanitized_text.replace(control_char, '') + + return {"text": sanitized_text} + except Exception as e: + raise RuntimeError(f"Error in text_bidi_sanitize: {str(e)}") + + def text_xor_hex(self, inputs): + import binascii + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_a = inputs.get("hex_a") + hex_b = inputs.get("hex_b") + + # 类型检查 + if hex_a is not None and not isinstance(hex_a, str): + raise TypeError("hex_a must be a string") + if hex_b is not None and not isinstance(hex_b, str): + raise TypeError("hex_b must be a string") + + # 检查必需参数 + if hex_a is None: + raise ValueError("hex_a parameter is required") + if hex_b is None: + raise ValueError("hex_b parameter is required") + + try: + # Remove any whitespace + hex_a = hex_a.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + hex_b = hex_b.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + + # Validate hex strings + if not (all(c in "0123456789abcdefABCDEF" for c in hex_a) and len(hex_a) % 2 == 0): + raise ValueError("hex_a must be a valid hexadecimal string with even length") + if not (all(c in "0123456789abcdefABCDEF" for c in hex_b) and len(hex_b) % 2 == 0): + raise ValueError("hex_b must be a valid hexadecimal string with even length") + + # Convert hex strings to bytes + bytes_a = binascii.unhexlify(hex_a) + bytes_b = binascii.unhexlify(hex_b) + + # Make the byte arrays the same length by padding the shorter one with zeros + max_len = max(len(bytes_a), len(bytes_b)) + bytes_a = bytes_a.ljust(max_len, b'\x00') + bytes_b = bytes_b.ljust(max_len, b'\x00') + + # Perform XOR operation + result_bytes = bytes(a ^ b for a, b in zip(bytes_a, bytes_b)) + + # Convert result back to hex + result_hex = binascii.hexlify(result_bytes).decode('utf-8') + + return {"hex": result_hex} + except ValueError as e: + if "Non-hexadecimal digit found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in text_xor_hex: {str(e)}") + + def text_rotN(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + n = inputs.get("n", 0) + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + n = int(n) + except ValueError: + raise ValueError("n must be a valid integer") + + result = [] + for char in text: + if char.isupper(): + # Rotate uppercase letters + result_char = chr((ord(char) - ord('A') + n) % 26 + ord('A')) + result.append(result_char) + elif char.islower(): + # Rotate lowercase letters + result_char = chr((ord(char) - ord('a') + n) % 26 + ord('a')) + result.append(result_char) + else: + # Keep non-alphabetic characters unchanged + result.append(char) + + return {"text": ''.join(result)} + + def luhn_check(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数(支持 card_number 和 number 两个参数名) + card_number = inputs.get("number") or inputs.get("card_number") + + # 类型检查 + if card_number is not None and not isinstance(card_number, str): + raise TypeError("number must be a string") + + # 检查必需参数 + if card_number is None: + raise ValueError("number parameter is required") + + try: + # 如果输入是JSON数组或其他非数字字符串,返回该字符串本身(用于数据传递) + # 这种情况发生在DAG设计中类型不匹配时 + if card_number.startswith('[') or card_number.startswith('{'): + # 输入是JSON,直接返回原值(用于传递) + return {"valid": card_number} + + # Remove whitespace from card number + card_number = card_number.replace(" ", "").replace("-", "") + + # Check if card number is all digits + if not card_number.isdigit() or len(card_number) < 13: + return {"valid": "false"} + + # Implement Luhn algorithm + total = 0 + reverse_digits = card_number[::-1] # Reverse the number for easier processing + + for i, digit in enumerate(reverse_digits): + num = int(digit) + if i % 2 == 1: # Every second digit starting from the right (which is first in reversed string) + num *= 2 + if num > 9: + num -= 9 # Equivalent to sum of digits for 2-digit numbers + total += num + + # Check if total is divisible by 10 + is_valid = total % 10 == 0 + return {"valid": "true" if is_valid else "false"} + except Exception as e: + raise RuntimeError(f"Error in luhn_check: {str(e)}") + + def iban_validate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iban = inputs.get("iban") + + # 类型检查 + if iban is not None and not isinstance(iban, str): + raise TypeError("iban must be a string") + + # 检查必需参数 + if iban is None: + raise ValueError("iban parameter is required") + + try: + # Remove whitespace from IBAN + iban = iban.replace(" ", "") + + # Basic length and format check + if not (len(iban) >= 15 and len(iban) <= 34): + return {"valid": "False"} + + if not (iban[:2].isalpha() and iban[2:].isdigit()): + return {"valid": "False"} + + # Move first four characters to the end + rearranged = iban[4:] + iban[:4] + + # Replace letters with numbers (A=10, B=11, ..., Z=35) + numeric_iban = '' + for char in rearranged: + if char.isdigit(): + numeric_iban += char + else: + numeric_iban += str(ord(char.upper()) - ord('A') + 10) + + # Perform modulo 97 check + # Use step-by-step approach for very large numbers + remainder = 0 + for char in numeric_iban: + remainder = (remainder * 10 + int(char)) % 97 + + is_valid = remainder == 1 + return {"valid": "True" if is_valid else "False"} + except Exception as e: + raise RuntimeError(f"Error in iban_validate: {str(e)}") + + def matter_synthesizer(self, inputs): + import hashlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + blueprint = inputs.get("blueprint") + + # 类型检查 + if blueprint is not None and not isinstance(blueprint, str): + raise TypeError("blueprint must be a string") + + try: + # Get blueprint parameter as defined in interface + if blueprint is None: + blueprint = "" + + # Generate a unique item ID based on the blueprint + # This ensures the same blueprint always produces the same item + blueprint_hash = hashlib.sha256(blueprint.encode()).hexdigest()[:16] + + # Create a synthesized item with a deterministic ID based on blueprint + synthesized_item = f"synthesized_item_{blueprint_hash}" + + return {"output_slot": synthesized_item} + except Exception as e: + raise RuntimeError(f"Error in matter_synthesizer: {str(e)}") + + # --- Terminal Implementations --- + def terminal_1(self, inputs): + """ + terminal_1: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 只返回 text_output + - 只输入正确的 slot_b → 只返回 hex_output + - 同时输入正确的 slot_a 和 slot_b → 返回 item_dispenser(物品掉落) + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + # 检查哪些输入被提供了 + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值是否正确(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + expected_a = golden_inputs["slot_a"] + a_valid = str(slot_a) == str(expected_a) + + if has_b and "slot_b" in golden_inputs: + expected_b = golden_inputs["slot_b"] + b_valid = str(slot_b) == str(expected_b) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 item_dispenser + if has_a and has_b: + if a_valid and b_valid: + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 text_output + if has_a and not has_b: + if a_valid: + if "text_output" in golden_outputs: + result["text_output"] = golden_outputs["text_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 hex_output + if has_b and not has_a: + if b_valid: + if "hex_output" in golden_outputs: + result["hex_output"] = golden_outputs["hex_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def terminal_2(self, inputs): + """ + terminal_2: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 text_result + - 同时输入正确的 num1 和 num2 → 返回 hex_result 和 math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + # 检查哪些输入被提供了 + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值是否正确(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + expected_num1 = golden_inputs["num1"] + num1_valid = str(num1) == str(expected_num1) + + if has_num2 and "num2" in golden_inputs: + expected_num2 = golden_inputs["num2"] + num2_valid = str(num2) == str(expected_num2) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 hex_result 和 math_token + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 text_result + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "text_result" in golden_outputs: + result["text_result"] = golden_outputs["text_result"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def logic_terminal(self, inputs): + """ + Logic Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 返回 screen(部分输出) + - 只输入正确的 slot_b → 返回 screen 和 secondary_output + - 同时输入正确的 slot_a 和 slot_b → 返回 screen, secondary_output, item_dispenser + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + a_valid = str(slot_a) == str(golden_inputs["slot_a"]) + + if has_b and "slot_b" in golden_inputs: + b_valid = str(slot_b) == str(golden_inputs["slot_b"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出(包括 item_dispenser) + if has_a and has_b: + if a_valid and b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 screen(部分输出) + if has_a and not has_b: + if a_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 screen 和 secondary_output + if has_b and not has_a: + if b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def math_terminal(self, inputs): + """ + Math Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 result_display + - 同时输入正确的 num1 和 num2 → 返回 result_display, hex_result, math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + num1_valid = str(num1) == str(golden_inputs["num1"]) + + if has_num2 and "num2" in golden_inputs: + num2_valid = str(num2) == str(golden_inputs["num2"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 result_display + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def crypt_terminal(self, inputs): + """ + Encryption Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 plaintext → 返回 status(部分输出) + - 同时输入正确的 plaintext 和 key → 返回 status, encrypted_hex, encryption_chip + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + plaintext = inputs.get("plaintext") + key = inputs.get("key") + + has_plaintext = plaintext is not None and plaintext != "" + has_key = key is not None and key != "" + + # 验证输入值(与 golden values 比较) + plaintext_valid = False + key_valid = False + + if has_plaintext and "plaintext" in golden_inputs: + plaintext_valid = str(plaintext) == str(golden_inputs["plaintext"]) + + if has_key and "key" in golden_inputs: + key_valid = str(key) == str(golden_inputs["key"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_plaintext and has_key: + if plaintext_valid and key_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + if "encrypted_hex" in golden_outputs: + result["encrypted_hex"] = golden_outputs["encrypted_hex"] + if "encryption_chip" in golden_outputs: + result["encryption_chip"] = golden_outputs["encryption_chip"] + return result + else: + incorrect_params = [] + correct_params = [] + if not plaintext_valid: + incorrect_params.append("plaintext") + else: + correct_params.append("plaintext") + if not key_valid: + incorrect_params.append("key") + else: + correct_params.append("key") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 plaintext 且正确 → 返回 status(部分输出) + if has_plaintext and not has_key: + if plaintext_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: plaintext"} + + # 只提供 key 但没有 plaintext + if has_key and not has_plaintext: + return {"error": "plaintext required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + def sequence_terminal(self, inputs): + """ + Sequence Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 sequence → 返回 verification(部分输出) + - 同时输入正确的 sequence 和 checksum → 返回 verification, auth_code, access_card + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + sequence = inputs.get("sequence") + checksum = inputs.get("checksum") + + has_sequence = sequence is not None and sequence != "" + has_checksum = checksum is not None and checksum != "" + + # 验证输入值(与 golden values 比较) + sequence_valid = False + checksum_valid = False + + if has_sequence and "sequence" in golden_inputs: + sequence_valid = str(sequence) == str(golden_inputs["sequence"]) + + if has_checksum and "checksum" in golden_inputs: + checksum_valid = str(checksum) == str(golden_inputs["checksum"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_sequence and has_checksum: + if sequence_valid and checksum_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + if "auth_code" in golden_outputs: + result["auth_code"] = golden_outputs["auth_code"] + if "access_card" in golden_outputs: + result["access_card"] = golden_outputs["access_card"] + return result + else: + incorrect_params = [] + correct_params = [] + if not sequence_valid: + incorrect_params.append("sequence") + else: + correct_params.append("sequence") + if not checksum_valid: + incorrect_params.append("checksum") + else: + correct_params.append("checksum") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 sequence 且正确 → 返回 verification(部分输出) + if has_sequence and not has_checksum: + if sequence_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: sequence"} + + # 只提供 checksum 但没有 sequence + if has_checksum and not has_sequence: + return {"error": "sequence required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + # --- Additional File Tools --- + + def zip_unzip_file(self, inputs): + """ZIP 解压文件工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def zip_unzip_item(self, inputs): + """ZIP 解压道具工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def code_py_exec(self, inputs): + """Python 代码执行工具 + + 这是一个真实执行的工具,在 DAG 生成阶段和运行时评测阶段都会执行代码。 + 输入: code (Python 代码字符串) + 输出: stdout (标准输出,包含执行结果和错误信息) + + 特殊行为: + - 如果代码定义了 main() 函数,会自动调用它 + - 如果执行出错,错误信息会包含在 stdout 中 + """ + code = inputs.get("code", "") + + if not code: + return {"stdout": "Error: No code provided"} + + try: + # 创建一个受限的执行环境 + import io + import sys + + # 捕获标准输出和标准错误 + old_stdout = sys.stdout + old_stderr = sys.stderr + sys.stdout = io.StringIO() + sys.stderr = io.StringIO() + + # 执行代码 + exec_globals = {"__builtins__": __builtins__} + exec_locals = {} + exec(code, exec_globals, exec_locals) + + # 如果定义了 main() 函数,自动调用它 + if 'main' in exec_locals and callable(exec_locals['main']): + exec_locals['main']() + + # 获取输出 + stdout_value = sys.stdout.getvalue() + stderr_value = sys.stderr.getvalue() + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 合并 stdout 和 stderr + output = stdout_value + if stderr_value: + output += ("\n" if output else "") + f"[stderr] {stderr_value}" + + # 如果没有任何输出,尝试返回 result 变量的值 + if not output: + result = exec_locals.get("_result") or exec_locals.get("result") + if result is not None: + output = str(result) + + return {"stdout": output if output else "(no output)"} + + except Exception as e: + # 恢复标准输出和错误输出 + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 返回错误信息 + return {"stdout": f"Error: {type(e).__name__}: {str(e)}"} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-b5fbf361/environment/puzzle/worker.Dockerfile b/tasks/agentescape-25-skeleton-b5fbf361/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-25-skeleton-b5fbf361/environment/puzzle/worker.Dockerfile @@ -0,0 +1,8 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends libseccomp2 && rm -rf /var/lib/apt/lists/* +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY worker.py child.py /app/ +COPY upstream/simulator.py /app/simulator.py +CMD ["uvicorn", "worker:app", "--host", "0.0.0.0", "--port", "8001", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-25-skeleton-b5fbf361/environment/puzzle/worker.py b/tasks/agentescape-25-skeleton-b5fbf361/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-25-skeleton-b5fbf361/environment/puzzle/worker.py @@ -0,0 +1,73 @@ +"""Stateless Python tool worker. Never receives a scenario or reference values.""" + +import json +import os +import signal +import subprocess +import sys +import tempfile +import threading + +from fastapi import FastAPI +from pydantic import BaseModel, ConfigDict + +app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) +lock = threading.Lock() + + +class Execution(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + code: str + + +@app.get("/health") +def health(): + return {"ok": True} + + +@app.post("/execute") +def execute(request: Execution): + if len(request.code.encode()) > 65536: + return {"stdout": "Error: code exceeds 64 KiB limit"} + with lock, tempfile.TemporaryDirectory(prefix="escape-code-") as directory: + os.chown(directory, 65534, 65534) + with tempfile.TemporaryFile() as output: + process = subprocess.Popen( + [sys.executable, "-I", "/app/child.py"], + stdin=subprocess.PIPE, + stdout=output, + stderr=subprocess.DEVNULL, + cwd=directory, + user=65534, + group=65534, + extra_groups=[], + start_new_session=True, + env={"PATH": "/usr/local/bin:/usr/bin:/bin"}, + ) + try: + process.communicate( + json.dumps({"code": request.code}).encode(), timeout=5 + ) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + return {"stdout": "Error: Python execution timed out"} + finally: + # Also remove children still in the process group after normal exit. + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + output.seek(0) + value = output.read(65537) + if len(value) > 65536 or process.returncode != 0: + return { + "stdout": "Error: Python execution exceeded a resource limit or failed" + } + try: + result = json.loads(value) + if not isinstance(result.get("stdout"), str): + raise ValueError("Invalid worker response") + return result + except (ValueError, AttributeError): + return {"stdout": "Error: Python execution returned invalid output"} diff --git a/tasks/agentescape-25-skeleton-b5fbf361/instruction.md b/tasks/agentescape-25-skeleton-b5fbf361/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-25-skeleton-b5fbf361/instruction.md @@ -0,0 +1,18 @@ +# Escape the room + +Discover the victory string and submit it with `escape submit-answer`. +Start with `escape observe`. This returns the room, available information, visible entities, and victory node ID. + +Use these commands (JSON responses): + +```sh +escape investigate NODE_ID +escape tool-call NODE_ID --arguments-json '{"parameter": "value"}' +escape use-item NODE_ID --arguments-json '{"parameter": "value"}' +escape submit-answer 'exact victory string' +escape state +``` + +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. + +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. diff --git a/tasks/agentescape-25-skeleton-b5fbf361/solution/oracle.py b/tasks/agentescape-25-skeleton-b5fbf361/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-25-skeleton-b5fbf361/solution/oracle.py @@ -0,0 +1,133 @@ +"""Reference solver: use trusted inputs, but obtain the answer through public actions.""" + +import json +import urllib.request +from pathlib import Path + + +def http_action(base_url, payload): + request = urllib.request.Request( + base_url + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(request, timeout=30) as response: + return json.load(response) + + +def solve(scenario, act, observe): + nodes = {node["id"]: node for node in scenario["nodes"]} + visible = {entity["id"] for entity in observe["available_entities"]} + solved = set() + seen_outputs = {} + action_count = 0 + + def call(payload): + nonlocal action_count + action_count += 1 + response = act(payload) + visible.update(entity["id"] for entity in response.get("newly_revealed", [])) + if ( + response.get("episode", {}).get("termination_reason") + == "infrastructure_error" + ): + raise RuntimeError("Infrastructure failure") + return response + + for _round in range(len(nodes) + 2): + progress = False + for node_id, node in nodes.items(): + if node_id not in visible or node_id in solved: + continue + # Preserve graph order for data inputs; trigger/drop edges express visibility. + predecessors = [ + edge["source_id"] + for edge in scenario["edges"] + if edge["target_id"] == node_id + and edge["connection_type"] not in ("Item", "Hidden_Item") + ] + if any(pred not in solved for pred in predecessors): + continue + info = call({"action": "investigate", "node_id": node_id}) + if not info.get("ok"): + raise RuntimeError(f"Investigation failed: {node_id}: {info}") + inputs = { + port["name"]: port["value"] + for port in node.get("inputs", []) + if "value" in port + } + if node["type"] == "Tool": + result = call( + {"action": "tool_call", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok") or result.get("output_values", {}).get("error"): + raise RuntimeError(f"Tool failed: {node_id}: {result}") + output = result.get("output_values", {}) + if node.get("template_id") in ("terminal_1", "terminal_2"): + slots = { + port["name"]: inputs[port["name"]] + for port in node["inputs"] + if port["type"] not in ("Item", "Hidden_Item") + and port["name"] in inputs + } + triggers = { + key: value for key, value in inputs.items() if key not in slots + } + for key, value in slots.items(): + partial = call( + { + "action": "tool_call", + "node_id": node_id, + "arguments": {**triggers, key: value}, + } + ) + if partial.get("ok"): + output.update(partial.get("output_values", {})) + # HIDDEN_ITEM tool drops only occur on subsequent investigation. + call({"action": "investigate", "node_id": node_id}) + elif info.get("required_inputs"): + result = call( + {"action": "use_item", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok"): + raise RuntimeError(f"Item failed: {node_id}: {result}") + output = result.get("content") + else: + output = info.get("content") + seen_outputs[node_id] = output + solved.add(node_id) + progress = True + win_id = scenario["metadata"]["win_node_id"] + if win_id in solved and (len(solved) == len(nodes) or not progress): + outputs = seen_outputs[win_id] + if not outputs: + raise RuntimeError(f"Victory node returned no output: {win_id}") + # Upstream grades its first stored output port, independent of response order. + victory_port = next( + port["name"] for port in nodes[win_id]["outputs"] if "value" in port + ) + answer = outputs[victory_port] if isinstance(outputs, dict) else outputs + result = call({"action": "submit_answer", "answer": answer}) + if not result.get("is_win"): + raise RuntimeError(f"Victory submission failed: {result}") + return {"won": True, "actions": action_count, "visited_nodes": len(solved)} + if not progress: + raise RuntimeError(f"No progress: visible={visible}, solved={solved}") + raise RuntimeError("Reference solver exceeded graph traversal limit") + + +if __name__ == "__main__": + import os + + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000") + with urllib.request.urlopen(base + "/observation", timeout=20) as response: + observation = json.load(response) + print( + json.dumps( + solve( + json.loads(Path("/solution/scenario.json").read_text()), + lambda payload: http_action(base, payload), + observation, + ) + ) + ) diff --git a/tasks/agentescape-25-skeleton-b5fbf361/solution/scenario.json b/tasks/agentescape-25-skeleton-b5fbf361/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..f8cdcf95bd7be5df6e8fcecc6f546cd8e28606e6 --- /dev/null +++ b/tasks/agentescape-25-skeleton-b5fbf361/solution/scenario.json @@ -0,0 +1,1558 @@ +{ + "metadata": { + "total_nodes": 25, + "total_edges": 28, + "win_node_id": "zip_unzip_item", + "win_condition": { + "type": "tool_output", + "node_id": "zip_unzip_item", + "output_port": "item", + "output_type": "Item", + "description": "Execute Zip Unzipper and get the output from port 'item'" + }, + "source_init": { + "source_nodes": [ + "zip_unzip_item", + "zip_unzip_file", + "crypto_rsa_decrypt_hex", + "num_base_convert", + "calc_gcd", + "calc_inv_mod_9968", + "zip_unzip_file_f293", + "zip_unzip_file_148f", + "container_3", + "calc_modexp", + "calc_gcd_d1ba", + "terminal_1", + "num_base_convert_0b44", + "time_convert", + "item_10", + "item_4", + "calc_bigmul", + "calc_gcd_232c" + ], + "by_node": { + "zip_unzip_item": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_item", + "init_inputs": {}, + "init_outputs": { + "item": { + "type": "Item", + "description": "item in the zip" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "crypto_rsa_decrypt_hex": { + "node_name": "RSA Decrypt", + "node_type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "init_inputs": { + "n": { + "type": "Big_Int", + "description": "Modulus n" + } + }, + "init_outputs": {} + }, + "num_base_convert": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "s": { + "type": "Big_Int", + "description": "Input integer value" + }, + "to_base": { + "type": "Big_Int", + "description": "To base" + } + }, + "init_outputs": {} + }, + "calc_gcd": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "b": { + "type": "Big_Int", + "description": "Second integer" + } + }, + "init_outputs": {} + }, + "calc_inv_mod_9968": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "zip_unzip_file_f293": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "zip_unzip_file_148f": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "container_3": { + "node_name": "", + "node_type": "Item", + "template_id": "container_3", + "init_inputs": { + "fingerprint_input": { + "type": "Big_Int", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + }, + "calc_modexp": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "exp": { + "type": "Big_Int", + "description": "Exponent" + } + }, + "init_outputs": {} + }, + "calc_gcd_d1ba": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "b": { + "type": "Big_Int", + "description": "Second integer" + } + }, + "init_outputs": {} + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": { + "slot_a": { + "type": "Text_Generic", + "description": "Input Slot A" + } + }, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + }, + "item_dispenser": { + "type": "Item", + "description": "Item output when both slots are provided" + } + } + }, + "num_base_convert_0b44": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "s": { + "type": "Big_Int", + "description": "Input integer value" + } + }, + "init_outputs": {} + }, + "time_convert": { + "node_name": "Timezone Converter", + "node_type": "Tool", + "template_id": "time_convert", + "init_inputs": { + "iso": { + "type": "Text_Generic", + "description": "ISO Timestamp" + }, + "from_tz": { + "type": "Text_Generic", + "description": "From Timezone" + }, + "to_tz": { + "type": "Text_Generic", + "description": "To Timezone" + } + }, + "init_outputs": {} + }, + "item_10": { + "node_name": "", + "node_type": "Item", + "template_id": "item_10", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Big_Int", + "description": "The number" + } + } + }, + "item_4": { + "node_name": "", + "node_type": "Item", + "template_id": "item_4", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "File_Id", + "description": "Zip file path" + } + } + }, + "calc_bigmul": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "b": { + "type": "Big_Int", + "description": "Second large integer" + } + }, + "init_outputs": {} + }, + "calc_gcd_232c": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First integer" + }, + "b": { + "type": "Big_Int", + "description": "Second integer" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "zip_unzip_item": { + "init_inputs": {}, + "init_outputs": { + "item": "I ·· V ·· X ·· L ·· C ·· D ·· M" + } + }, + "zip_unzip_file": { + "init_inputs": { + "password": "secret_pass_123!" + }, + "init_outputs": { + "files": "extracted_content1.zip" + } + }, + "crypto_rsa_decrypt_hex": { + "init_inputs": { + "n": "98237498237498273498237498237498" + }, + "init_outputs": {} + }, + "num_base_convert": { + "init_inputs": { + "s": "12345678901234567890", + "to_base": "10" + }, + "init_outputs": {} + }, + "calc_gcd": { + "init_inputs": { + "b": "1203984712039487123984" + }, + "init_outputs": {} + }, + "calc_inv_mod_9968": { + "init_inputs": { + "mod": "997333" + }, + "init_outputs": {} + }, + "zip_unzip_file_f293": { + "init_inputs": { + "password": "another_password_here" + }, + "init_outputs": { + "files": "intermediate_files.zip" + } + }, + "zip_unzip_file_148f": { + "init_inputs": {}, + "init_outputs": { + "files": "initial_layer_data.zip" + } + }, + "container_3": { + "init_inputs": { + "fingerprint_input": "546987123654987123654" + }, + "init_outputs": {} + }, + "calc_modexp": { + "init_inputs": { + "exp": "234985729384759283749" + }, + "init_outputs": {} + }, + "calc_gcd_d1ba": { + "init_inputs": { + "b": "85739485739485739485" + }, + "init_outputs": {} + }, + "terminal_1": { + "init_inputs": { + "slot_a": "terminal_input_string" + }, + "init_outputs": { + "text_output": "Terminal output generated successfully.", + "hex_output": "1a2b3c4d5e6f7a8b", + "item_dispenser": "dispensed useless item from terminal" + } + }, + "num_base_convert_0b44": { + "init_inputs": { + "s": "59483726152439485736" + }, + "init_outputs": {} + }, + "time_convert": { + "init_inputs": { + "iso": "2023-10-01T12:00:00Z", + "from_tz": "UTC", + "to_tz": "Asia/Shanghai" + }, + "init_outputs": {} + }, + "item_10": { + "init_inputs": {}, + "init_outputs": { + "content": "123098457120938471203" + } + }, + "item_4": { + "init_inputs": {}, + "init_outputs": { + "content": "start_file_package.zip" + } + }, + "calc_bigmul": { + "init_inputs": { + "b": "48573948573948573948" + }, + "init_outputs": {} + }, + "calc_gcd_232c": { + "init_inputs": { + "a": "98765432109876543210", + "b": "13579246801357924680" + }, + "init_outputs": {} + } + }, + "intro_narrative": "The rain outside falls like static, illuminated by the sickly neon signs of Sector 4. You find yourself locked inside an underground data-smuggling den, a haven for rogue hackers and digital ghosts. Your objective is simple but highly dangerous: extract a classified blueprint from a deeply buried, password-protected archive before the corporate hit squads breach the reinforced door. The room is littered with archaic decryption modules, modular matrices, and biometric scanners that form a complex web of cryptographic security. You'll need to trace the data flow, operate multiple computing units, and synthesize access tools to peel back the layers of encryption. Time is running out, and every terminal you activate brings you one step closer to uncovering the final objective hidden within the zipped corporate files.", + "narrative_style": "cyberpunk" + }, + "nodes": [ + { + "id": "zip_unzip_item", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_item", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "extracted_content1.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "?/utTH*S\u0019" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip", + "value": "I ·· V ·· X ·· L ·· C ·· D ·· M" + } + ], + "init": { + "inputs": {}, + "outputs": { + "item": "I ·· V ·· X ·· L ·· C ·· D ·· M" + } + }, + "narrative": "This is the Final Extraction Console. It requires inputs from both the Secondary Archive Decoder and the Asymmetric Cipher Deck to securely unpack the final objective." + }, + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "intermediate_files.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "secret_pass_123!" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_content1.zip" + } + ], + "init": { + "inputs": { + "password": "secret_pass_123!" + }, + "outputs": { + "files": "extracted_content1.zip" + } + }, + "narrative": "This is the Secondary Archive Decoder. It requires input from the Intermediate Archive Decoder to peel back the penultimate security shell." + }, + { + "id": "crypto_rsa_decrypt_hex", + "name": "RSA Decrypt", + "description": "RSA decrypt (hex cipher) with n,d (decimal).", + "type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex_cipher", + "type": "Hex_String", + "description": "Ciphertext (Hex)", + "value": "1a2b3c4d5e6f7a8b" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Modulus n", + "value": "98237498237498273498237498237498" + }, + { + "name": "d", + "type": "Big_Int", + "description": "Private exponent d", + "value": "205143" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decrypted text", + "value": "?/utTH*S\u0019" + } + ], + "init": { + "inputs": { + "n": "98237498237498273498237498237498" + }, + "outputs": {} + }, + "narrative": "This is the Asymmetric Cipher Deck. It requires inputs from both the Core Reversal Matrix and the Mainframe Terminal to shatter the cipher." + }, + { + "id": "calc_inv_mod", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "12345678901234567890" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "549739" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "205143" + } + ], + "narrative": "This is the Core Reversal Matrix. It requires inputs from both the Neural Formatter and the Modular Reversal Unit to calculate the final cryptographic inverse." + }, + { + "id": "num_base_convert", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "12345678901234567890" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "1" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "10" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "12345678901234567890" + } + ], + "init": { + "inputs": { + "s": "12345678901234567890", + "to_base": "10" + }, + "outputs": {} + }, + "narrative": "This is the Neural Formatter. It requires input from the Primary Algorithmic Relay to shift numeric structures properly." + }, + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "549739" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "1203984712039487123984" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "init": { + "inputs": { + "b": "1203984712039487123984" + }, + "outputs": {} + }, + "narrative": "This is the Primary Algorithmic Relay. It requires input from the Modular Reversal Unit to find the common denominator of the security mesh." + }, + { + "id": "calc_inv_mod_9968", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "76213956695489749433" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "997333" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "549739" + } + ], + "init": { + "inputs": { + "mod": "997333" + }, + "outputs": {} + }, + "narrative": "This is the Modular Reversal Unit. It requires input from the Cryptographic Matrix to reverse-engineer mathematical locks." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A Discarded Memory Stick covered in neon grime." + }, + { + "id": "item_16_0d2c", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by", + "value": "synthesized_item_4ae59e4ec058aa76" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A freshly printed Synthetic Access Card." + }, + { + "id": "zip_unzip_file_f293", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "initial_layer_data.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "another_password_here" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "intermediate_files.zip" + } + ], + "init": { + "inputs": { + "password": "another_password_here" + }, + "outputs": { + "files": "intermediate_files.zip" + } + }, + "narrative": "This is the Intermediate Archive Decoder. It requires input from the Primary Archive Decoder to strip the second layer of encryption." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "An Old Security Badge dropped by a previous runner." + }, + { + "id": "matter_synthesizer", + "name": "Matter Synthesizer", + "description": "Synthesizes physical objects from data blueprints.", + "type": "Tool", + "template_id": "matter_synthesizer", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "blueprint", + "type": "Text_Generic", + "description": "Object Blueprint", + "value": "2023-10-01T20:00:00+08:00" + } + ], + "outputs": [ + { + "name": "output_slot", + "type": "Item", + "description": "Synthesized Object", + "value": "synthesized_item_4ae59e4ec058aa76" + } + ], + "narrative": "This is the Matter Synthesizer. It requires input from the Temporal Protocol Converter to materialize physical blueprints." + }, + { + "id": "zip_unzip_file_148f", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "start_file_package.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Terminal output generated successfully." + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "initial_layer_data.zip" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "initial_layer_data.zip" + } + }, + "narrative": "This is the Primary Archive Decoder. It requires inputs from both the Mainframe Terminal and the Encrypted Data Drive to begin the extraction process." + }, + { + "id": "container_3", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_3", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Big_Int", + "description": "Fingerprint Hash", + "value": "546987123654987123654" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "546987123654987123654" + }, + "outputs": {} + }, + "narrative": "A heavy Biometric Vault embedded in the wall, securing valuable contraband." + }, + { + "id": "calc_modexp", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "5" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "234985729384759283749" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "123098457120938471203" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "76213956695489749433" + } + ], + "init": { + "inputs": { + "exp": "234985729384759283749" + }, + "outputs": {} + }, + "narrative": "This is the Cryptographic Matrix. It requires inputs from both the Data Synchronization Relay and the Datapad Integer Core to process complex calculations." + }, + { + "id": "calc_gcd_d1ba", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "900000000090" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "85739485739485739485" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "5" + } + ], + "init": { + "inputs": { + "b": "85739485739485739485" + }, + "outputs": {} + }, + "narrative": "This is the Data Synchronization Relay. It requires input from the Initial Algorithmic Processor to align its internal clocks." + }, + { + "id": "item_16_d2f9", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A Cracked Biometric Key that still holds a faint charge." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "terminal_input_string" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "59483726152439485736" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Terminal output generated successfully." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "1a2b3c4d5e6f7a8b" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided", + "value": "dispensed useless item from terminal" + } + ], + "init": { + "inputs": { + "slot_a": "terminal_input_string" + }, + "outputs": { + "text_output": "Terminal output generated successfully.", + "hex_output": "1a2b3c4d5e6f7a8b", + "item_dispenser": "dispensed useless item from terminal" + } + }, + "narrative": "This is the Mainframe Terminal. It requires input from the Alpha Signal Converter to establish a stable connection." + }, + { + "id": "num_base_convert_0b44", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "59483726152439485736" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "12345678901234567890" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "5979378125724878931175680762413114019444" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "59483726152439485736" + } + ], + "init": { + "inputs": { + "s": "59483726152439485736" + }, + "outputs": {} + }, + "narrative": "This is the Alpha Signal Converter. It requires inputs from both the Neural Formatter and the Integer Multiplier to translate the raw machine code." + }, + { + "id": "item_16_95bc", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A Forgotten Neuro-chip coated in synthetic fluid." + }, + { + "id": "time_convert", + "name": "Timezone Converter", + "description": "Convert ISO time between timezones.", + "type": "Tool", + "template_id": "time_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "iso", + "type": "Text_Generic", + "description": "ISO Timestamp", + "value": "2023-10-01T12:00:00Z" + }, + { + "name": "from_tz", + "type": "Text_Generic", + "description": "From Timezone", + "value": "UTC" + }, + { + "name": "to_tz", + "type": "Text_Generic", + "description": "To Timezone", + "value": "Asia/Shanghai" + } + ], + "outputs": [ + { + "name": "iso", + "type": "Text_Generic", + "description": "Converted ISO Timestamp", + "value": "2023-10-01T20:00:00+08:00" + } + ], + "init": { + "inputs": { + "iso": "2023-10-01T12:00:00Z", + "from_tz": "UTC", + "to_tz": "Asia/Shanghai" + }, + "outputs": {} + }, + "narrative": "This is the Temporal Protocol Converter. A rusted device used to translate old earth timeframes." + }, + { + "id": "item_10", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_10", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Big_Int", + "description": "The number", + "value": "123098457120938471203" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "123098457120938471203" + } + }, + "narrative": "A scratched Datapad Integer Core isolated from the main grid." + }, + { + "id": "item_4", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_4", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "File_Id", + "description": "Zip file path", + "value": "start_file_package.zip" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "start_file_package.zip" + } + }, + "narrative": "A heavily Encrypted Data Drive found in the debris." + }, + { + "id": "calc_bigmul", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "123098457120938471203" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "48573948573948573948" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "5979378125724878931175680762413114019444" + } + ], + "init": { + "inputs": { + "b": "48573948573948573948" + }, + "outputs": {} + }, + "narrative": "This is the Integer Multiplier. It requires input from the Datapad Integer Core to amplify the numeric signal." + }, + { + "id": "calc_gcd_232c", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "98765432109876543210" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "13579246801357924680" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "900000000090" + } + ], + "init": { + "inputs": { + "a": "98765432109876543210", + "b": "13579246801357924680" + }, + "outputs": {} + }, + "narrative": "This is the Initial Algorithmic Processor. An old piece of tech used for basic cryptographic operations." + } + ], + "edges": [ + { + "source_id": "zip_unzip_file", + "target_id": "zip_unzip_item", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "crypto_rsa_decrypt_hex", + "target_id": "zip_unzip_item", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "password" + }, + { + "source_id": "calc_inv_mod", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "d" + }, + { + "source_id": "num_base_convert", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "a" + }, + { + "source_id": "calc_gcd", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "from_base" + }, + { + "source_id": "calc_inv_mod_9968", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "a" + }, + { + "source_id": "item_16", + "target_id": "calc_gcd", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "item_16_0d2c", + "target_id": "num_base_convert", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "zip_unzip_file_f293", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "item_8", + "target_id": "calc_inv_mod_9968", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "matter_synthesizer", + "target_id": "item_16_0d2c", + "connection_type": "Item", + "source_port": "output_slot", + "target_port": "source_tool" + }, + { + "source_id": "zip_unzip_file_148f", + "target_id": "zip_unzip_file_f293", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "container_3", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "calc_modexp", + "target_id": "calc_inv_mod_9968", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "a" + }, + { + "source_id": "calc_inv_mod_9968", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "mod" + }, + { + "source_id": "calc_gcd_d1ba", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "base" + }, + { + "source_id": "item_16_d2f9", + "target_id": "zip_unzip_file_148f", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "terminal_1", + "target_id": "zip_unzip_file_148f", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "password" + }, + { + "source_id": "num_base_convert_0b44", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "slot_b" + }, + { + "source_id": "item_16_95bc", + "target_id": "num_base_convert_0b44", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "time_convert", + "target_id": "matter_synthesizer", + "connection_type": "Text_Generic", + "source_port": "iso", + "target_port": "blueprint" + }, + { + "source_id": "terminal_1", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Hex_String", + "source_port": "hex_output", + "target_port": "hex_cipher" + }, + { + "source_id": "item_10", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "content", + "target_port": "mod" + }, + { + "source_id": "item_4", + "target_id": "zip_unzip_file_148f", + "connection_type": "File_Id", + "source_port": "content", + "target_port": "zip_id" + }, + { + "source_id": "num_base_convert", + "target_id": "num_base_convert_0b44", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "from_base" + }, + { + "source_id": "calc_bigmul", + "target_id": "num_base_convert_0b44", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "to_base" + }, + { + "source_id": "item_10", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "content", + "target_port": "a" + }, + { + "source_id": "calc_gcd_232c", + "target_id": "calc_gcd_d1ba", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "a" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-b5fbf361/solution/solve.sh b/tasks/agentescape-25-skeleton-b5fbf361/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-25-skeleton-b5fbf361/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-25-skeleton-b5fbf361/task.toml b/tasks/agentescape-25-skeleton-b5fbf361/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6d37aced6c5524edd0a1322a79486b074d54103f --- /dev/null +++ b/tasks/agentescape-25-skeleton-b5fbf361/task.toml @@ -0,0 +1,38 @@ +schema_version = "1.4" +source = "https://github.com/AGI-Eval-Official/Repo-of-AgentEscapeBench" + +[[artifacts]] +source = "/evidence/final.json" +service = "puzzle" + +[[artifacts]] +source = "/evidence/trace.jsonl" +service = "puzzle" + +[task] +name = "edbeeching/agentescape-25-skeleton-b5fbf361" +version = "0.1.0" + +[metadata] +difficulty = 25 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "71c8e3db2f1429a11e7cb079e606b700e6765cba0f0f45dfd53e7de693fed13a" +protocol = "harbor-cli-action-budget-v1" +max_actions = 500 + +[agent] +timeout_sec = 1200 + +[environment] +build_timeout_sec = 900 +cpus = 1 +memory_mb = 1024 + +[verifier] +environment_mode = "separate" +timeout_sec = 60 + +[[verifier.collect]] +service = "puzzle" +command = "python -I /app/export.py" +timeout_sec = 15 diff --git a/tasks/agentescape-25-skeleton-b5fbf361/tests/Dockerfile b/tasks/agentescape-25-skeleton-b5fbf361/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-25-skeleton-b5fbf361/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-25-skeleton-b5fbf361/tests/expected.json b/tasks/agentescape-25-skeleton-b5fbf361/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..71bd856585390bfa2d75186febd79989bc8e09b7 --- /dev/null +++ b/tasks/agentescape-25-skeleton-b5fbf361/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "71c8e3db2f1429a11e7cb079e606b700e6765cba0f0f45dfd53e7de693fed13a", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-b5fbf361/tests/grade.py b/tasks/agentescape-25-skeleton-b5fbf361/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-25-skeleton-b5fbf361/tests/grade.py @@ -0,0 +1,21 @@ +"""Grade only Harbor-collected sidecar evidence in a fresh verifier container.""" + +import json +from pathlib import Path + +expected = json.loads(Path("/tests/expected.json").read_text()) +state = json.loads(Path("/evidence/final.json").read_text()) +assert state["collected_from_live_service"] is True, "Missing trusted service export" +assert state["scenario_sha256"] == expected["scenario_sha256"], ( + "Wrong scenario evidence" +) +assert state["max_actions"] == expected["max_actions"], "Wrong budget" +assert type(state["won"]) is bool +assert 0 <= state["action_count"] <= state["max_actions"] +assert state["termination_reason"] != "infrastructure_error", ( + "Infrastructure failure is not a puzzle failure" +) +assert not state["won"] or state["termination_reason"] == "success" +Path("/logs/verifier").mkdir(parents=True, exist_ok=True) +Path("/logs/verifier/state.json").write_text(json.dumps(state, indent=2)) +Path("/logs/verifier/reward.txt").write_text("1.0\n" if state["won"] else "0.0\n") diff --git a/tasks/agentescape-25-skeleton-b5fbf361/tests/test.sh b/tasks/agentescape-25-skeleton-b5fbf361/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-25-skeleton-b5fbf361/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-25-skeleton-c32db50f/environment/Dockerfile b/tasks/agentescape-25-skeleton-c32db50f/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-25-skeleton-c32db50f/environment/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-25-skeleton-c32db50f/environment/agent/Dockerfile b/tasks/agentescape-25-skeleton-c32db50f/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-25-skeleton-c32db50f/environment/agent/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-25-skeleton-c32db50f/environment/agent/cli.py b/tasks/agentescape-25-skeleton-c32db50f/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-25-skeleton-c32db50f/environment/agent/cli.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Public agent client; depends only on the Python standard library.""" + +import argparse +import json +import os +import sys +import urllib.error +import urllib.request + + +def main(): + parser = argparse.ArgumentParser(description="Interact with the escape room") + parser.add_argument( + "action", + choices=[ + "observe", + "state", + "investigate", + "tool-call", + "use-item", + "submit-answer", + ], + ) + parser.add_argument("value", nargs="?") + parser.add_argument("--arguments-json", default="{}") + args = parser.parse_args() + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000").rstrip("/") + if args.action in ("observe", "state"): + request = urllib.request.Request( + base + ("/observation" if args.action == "observe" else "/state") + ) + else: + if args.value is None: + parser.error("node ID or answer is required") + payload = {"action": args.action.replace("-", "_")} + if args.action == "submit-answer": + payload["answer"] = args.value + else: + payload["node_id"] = args.value + if args.action in ("tool-call", "use-item"): + payload["arguments"] = json.loads(args.arguments_json) + request = urllib.request.Request( + base + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=30) as response: + print(json.dumps(json.load(response), ensure_ascii=False)) + except (urllib.error.URLError, ValueError) as exc: + print(json.dumps({"ok": False, "error": str(exc)})) + sys.exit(2) + + +if __name__ == "__main__": + main() diff --git a/tasks/agentescape-25-skeleton-c32db50f/environment/docker-compose.yaml b/tasks/agentescape-25-skeleton-c32db50f/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0e267b4f4968a7c4e4e085ce8f1c79eefedfb7e5 --- /dev/null +++ b/tasks/agentescape-25-skeleton-c32db50f/environment/docker-compose.yaml @@ -0,0 +1,50 @@ +services: + main: + image: agentescapebench-agent:aab05a0a9ddb + build: + context: ./agent + networks: [default, puzzle] + security_opt: [no-new-privileges:true] + depends_on: + puzzle: + condition: service_healthy + puzzle: + image: agentescapebench-puzzle:agentescape-25-skeleton-c32db50f-aab05a0a9ddb + build: + context: ./puzzle + networks: [puzzle, execution] + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 512m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"] + interval: 1s + timeout: 3s + retries: 30 + depends_on: + worker: + condition: service_healthy + worker: + image: agentescapebench-worker:aab05a0a9ddb + build: + context: ./puzzle + dockerfile: worker.Dockerfile + networks: [execution] + read_only: true + tmpfs: ["/tmp:size=64m,mode=1777"] + cap_drop: [ALL] + cap_add: [SETUID, SETGID, KILL, CHOWN, DAC_OVERRIDE] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 384m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8001/health')"] + interval: 1s + timeout: 3s + retries: 30 +networks: + puzzle: + internal: true + execution: + internal: true diff --git a/tasks/agentescape-25-skeleton-c32db50f/environment/puzzle/Dockerfile b/tasks/agentescape-25-skeleton-c32db50f/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-25-skeleton-c32db50f/environment/puzzle/Dockerfile @@ -0,0 +1,9 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY upstream /app/upstream +COPY service.py export.py /app/ +COPY scenario.json /private/scenario.json +ENV SCENARIO_PATH=/private/scenario.json EVIDENCE_DIR=/evidence WORKER_URL=http://worker:8001 MAX_ACTIONS=500 +CMD ["uvicorn", "service:create_app", "--factory", "--host", "0.0.0.0", "--port", "8000", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-25-skeleton-c32db50f/environment/puzzle/child.py b/tasks/agentescape-25-skeleton-c32db50f/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-25-skeleton-c32db50f/environment/puzzle/child.py @@ -0,0 +1,59 @@ +"""Run the original Python tool after reducing privileges and blocking networking.""" + +import ctypes +import errno +import json +import resource +import sys + +resource.setrlimit(resource.RLIMIT_CPU, (3, 3)) +resource.setrlimit(resource.RLIMIT_AS, (256 * 1024 * 1024, 256 * 1024 * 1024)) +resource.setrlimit(resource.RLIMIT_FSIZE, (65536, 65536)) +resource.setrlimit(resource.RLIMIT_NOFILE, (32, 32)) +resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + +# Filters survive fork/exec. Fail closed if seccomp cannot be loaded. +lib = ctypes.CDLL("libseccomp.so.2", use_errno=True) +lib.seccomp_init.argtypes = [ctypes.c_uint32] +lib.seccomp_init.restype = ctypes.c_void_p +lib.seccomp_rule_add.argtypes = [ + ctypes.c_void_p, + ctypes.c_uint32, + ctypes.c_int, + ctypes.c_uint, +] +lib.seccomp_syscall_resolve_name.argtypes = [ctypes.c_char_p] +lib.seccomp_load.argtypes = [ctypes.c_void_p] +lib.seccomp_release.argtypes = [ctypes.c_void_p] +ctx = lib.seccomp_init(0x7FFF0000) # SCMP_ACT_ALLOW +if not ctx: + raise RuntimeError("Cannot initialize execution isolation") +try: + for name in ( + "socket", + "socketpair", + "connect", + "ptrace", + "process_vm_readv", + "process_vm_writev", + "mount", + "unshare", + "setns", + "bpf", + ): + number = lib.seccomp_syscall_resolve_name(name.encode()) + if ( + number >= 0 + and lib.seccomp_rule_add(ctx, 0x00050000 | errno.EPERM, number, 0) != 0 + ): + raise RuntimeError("Cannot install execution isolation rule") + if lib.seccomp_load(ctx) != 0: + raise RuntimeError("Cannot activate execution isolation") +finally: + lib.seccomp_release(ctx) + +sys.path.insert(0, "/app") +from simulator import ToolSimulator # noqa: E402 + +request = json.load(sys.stdin) +json.dump(ToolSimulator().code_py_exec(request), sys.stdout) diff --git a/tasks/agentescape-25-skeleton-c32db50f/environment/puzzle/export.py b/tasks/agentescape-25-skeleton-c32db50f/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-25-skeleton-c32db50f/environment/puzzle/export.py @@ -0,0 +1,13 @@ +"""Harbor invokes this inside the puzzle service after stopping the agent.""" + +import json +import pathlib +import urllib.request + +with urllib.request.urlopen("http://127.0.0.1:8000/state", timeout=10) as response: + state = json.load(response) +state["collected_from_live_service"] = True +target = pathlib.Path("/evidence/final.json") +temp = target.with_suffix(".tmp") +temp.write_text(json.dumps(state)) +temp.replace(target) diff --git a/tasks/agentescape-25-skeleton-c32db50f/environment/puzzle/requirements.txt b/tasks/agentescape-25-skeleton-c32db50f/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-25-skeleton-c32db50f/environment/puzzle/requirements.txt @@ -0,0 +1,57 @@ +annotated-doc==0.0.5 + # via fastapi +annotated-types==0.8.0 + # via pydantic +anyio==4.16.0 + # via starlette +certifi==2026.10.23 + # via requests +cffi==2.1.1 ; platform_python_implementation != 'PyPy' + # via cryptography +charset-normalizer==3.5.2 + # via requests +click==8.5.0 + # via uvicorn +cryptography==50.0.2 + # via agentescapebench-harbor +fastapi==0.162.0 + # via agentescapebench-harbor +h11==0.16.0 + # via uvicorn +idna==3.20 + # via + # anyio + # requests +opentelemetry-api==1.45.2 + # via fastapi +pycparser==3.12 ; implementation_name != 'PyPy' and platform_python_implementation != 'PyPy' + # via cffi +pydantic==2.14.2 + # via + # agentescapebench-harbor + # fastapi +pydantic-core==2.50.2 + # via pydantic +pytz==2025.2 + # via agentescapebench-harbor +requests==2.34.2 + # via agentescapebench-harbor +starlette==1.10.0 + # via fastapi +typing-extensions==4.16.0 + # via + # anyio + # fastapi + # opentelemetry-api + # pydantic + # pydantic-core + # starlette + # typing-inspection +typing-inspection==0.4.4 + # via + # fastapi + # pydantic +urllib3==2.8.0 + # via requests +uvicorn==0.54.0 + # via agentescapebench-harbor diff --git a/tasks/agentescape-25-skeleton-c32db50f/environment/puzzle/scenario.json b/tasks/agentescape-25-skeleton-c32db50f/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..edab98ab062da1aa97ba57f45708ef372d6a29c2 --- /dev/null +++ b/tasks/agentescape-25-skeleton-c32db50f/environment/puzzle/scenario.json @@ -0,0 +1,1380 @@ +{ + "metadata": { + "total_nodes": 25, + "total_edges": 29, + "win_node_id": "item_7", + "win_condition": { + "type": "item_content", + "node_id": "item_7", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_7", + "hmac_sha256", + "container_2", + "calc_modexp", + "graph_shortest_path", + "zip_unzip_file", + "crypto_rsa_decrypt_hex", + "graph_shortest_path_53ed", + "calc_bigmul_0ba9", + "checksum_crc32_6747", + "container_4_d115", + "hex_decode" + ], + "by_node": { + "item_7": { + "node_name": "", + "node_type": "Item", + "template_id": "item_7", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Code_Python", + "description": "The integer" + } + } + }, + "hmac_sha256": { + "node_name": "HMAC-SHA256 Calculator", + "node_type": "Tool", + "template_id": "hmac_sha256", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text message" + } + }, + "init_outputs": {} + }, + "container_2": { + "node_name": "", + "node_type": "Item", + "template_id": "container_2", + "init_inputs": { + "fingerprint_input": { + "type": "Hex_String", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + }, + "calc_modexp": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "base": { + "type": "Big_Int", + "description": "Base" + }, + "exp": { + "type": "Big_Int", + "description": "Exponent" + } + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "dst": { + "type": "Text_Generic", + "description": "Destination node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + }, + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "crypto_rsa_decrypt_hex": { + "node_name": "RSA Decrypt", + "node_type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "init_inputs": { + "n": { + "type": "Big_Int", + "description": "Modulus n" + }, + "d": { + "type": "Big_Int", + "description": "Private exponent d" + } + }, + "init_outputs": {} + }, + "graph_shortest_path_53ed": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "Graph JSON file ID" + }, + "dst": { + "type": "Text_Generic", + "description": "Destination node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "calc_bigmul_0ba9": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "b": { + "type": "Big_Int", + "description": "Second large integer" + } + }, + "init_outputs": {} + }, + "checksum_crc32_6747": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + }, + "container_4_d115": { + "node_name": "", + "node_type": "Item", + "template_id": "container_4", + "init_inputs": { + "fingerprint_input": { + "type": "Text_Generic", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + }, + "hex_decode": { + "node_name": "Hex to Text Decoder", + "node_type": "Tool", + "template_id": "hex_decode", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex string" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "item_7": { + "init_inputs": {}, + "init_outputs": { + "content": "def get_secret_integer():\n return 420918237" + } + }, + "hmac_sha256": { + "init_inputs": { + "text": "Critical system validation message for HMAC computation" + }, + "init_outputs": {} + }, + "container_2": { + "init_inputs": { + "fingerprint_input": "a1b2c3d4e5f67890a1b2c3d4e5f67890" + }, + "init_outputs": {} + }, + "calc_modexp": { + "init_inputs": { + "base": "32", + "exp": "83948572638194758264" + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": { + "dst": "Node_Omega" + }, + "init_outputs": { + "path": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\", \"Node_Omega\"]", + "cost": "450210" + } + }, + "zip_unzip_file": { + "init_inputs": { + "zip_id": "archive_data_77.zip", + "password": "secure_pass_123" + }, + "init_outputs": { + "files": "extracted_payload_99.csv" + } + }, + "crypto_rsa_decrypt_hex": { + "init_inputs": { + "n": "94857263819475826473928174", + "d": "48572638194758264739281745" + }, + "init_outputs": {} + }, + "graph_shortest_path_53ed": { + "init_inputs": { + "file_id": "network_graph_82.json", + "dst": "Server_Final" + }, + "init_outputs": { + "path": "[\"Gateway\", \"Router_1\", \"Switch_A\", \"Firewall\", \"Load_Balancer\", \"Server_Final\"]", + "cost": "889312" + } + }, + "calc_bigmul_0ba9": { + "init_inputs": { + "b": "182736455463728192039485" + }, + "init_outputs": {} + }, + "checksum_crc32_6747": { + "init_inputs": { + "hex": "aabbccddeeff112233445566" + }, + "init_outputs": {} + }, + "container_4_d115": { + "init_inputs": { + "fingerprint_input": "unique_fingerprint_hash_string_99" + }, + "init_outputs": {} + }, + "hex_decode": { + "init_inputs": { + "hex": "48656c6c6f20576f726c6421204465636f6465206d65" + }, + "init_outputs": {} + } + }, + "intro_narrative": "Welcome to Sector 7, a forgotten slice of the mega-city where neon lights flicker over rain-slicked concrete. You are a rogue data-runner, and your target is hidden deep within an abandoned corporate safehouse. The megacorp locked down the Mainframe Data Core before evacuating, leaving behind a complex web of encrypted terminals, dead-drop safes, and fragmented data nodes. Your objective is to navigate this digital and physical labyrinth. You must scavenge for override keys, reactivate dormant signal decoders, and daisy-chain their outputs to bypass the heavy biometric locks. Time is ticking, and the automated corporate sweepers are on their way. Trace the data flow, unlock the core, and get out alive.", + "narrative_style": "cyberpunk" + }, + "nodes": [ + { + "id": "item_7", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_7", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Code_Python", + "description": "The integer", + "value": "def get_secret_integer():\n return 420918237" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "def get_secret_integer():\n return 420918237" + } + }, + "narrative": "The Mainframe Data Core. A glowing cybernetic brain holding the megacorp's darkest secrets." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "The Server Access Key. A metallic card with embedded microchips, essential for breaching secure hardware." + }, + { + "id": "container_3", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_3", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Big_Int", + "description": "Fingerprint Hash", + "value": "491214545225405594951055748019336464562276517129141852934074007632534460515273586974720" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is the Master Override Safe. It requires input from the Universal Translator to disengage its heavy locks." + }, + { + "id": "num_base_convert", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "491214545225405594951055748019336464562276517129141852934074007632534460515273586974720" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": 3478258514 + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": 3457857673 + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "491214545225405594951055748019336464562276517129141852934074007632534460515273586974720" + } + ], + "narrative": "This is the Universal Translator. It requires input from the Quantum Processor, the Primary Validator, and the Secondary Validator." + }, + { + "id": "item_16_f971", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A battered Maintenance Keycard, dropped by a panicked technician during the evacuation." + }, + { + "id": "calc_bigmul", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "1221368412905438059919937305852380583166914236544" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "402183763748143429283021565875961314880" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "491214545225405594951055748019336464562276517129141852934074007632534460515273586974720" + } + ], + "narrative": "This is the Quantum Processor. It requires input from the Neural Synthesizer and the Logic Multiplier." + }, + { + "id": "checksum_crc32", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "e3cb1f24d2fe9c0c3f2baf2d291a21dcc0bcd82cd8ab140658400c21c62a7d02" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "cf520352" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3478258514 + } + ], + "narrative": "This is the Primary Validator. It requires input from the Security Authenticator." + }, + { + "id": "calc_bigmul_d486", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "351143656513576224633640702949884472896" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": 3478258514 + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "1221368412905438059919937305852380583166914236544" + } + ], + "narrative": "This is the Neural Synthesizer. It requires input from the Power Calibrator and the Primary Validator." + }, + { + "id": "checksum_crc32_b2b3", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "cf520352" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "ce1ab889" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3457857673 + } + ], + "narrative": "This is the Secondary Validator. It requires input from the Primary Validator." + }, + { + "id": "calc_bigmul_2fdb", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "452241467278236917170825948458990" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "889312" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "402183763748143429283021565875961314880" + } + ], + "narrative": "This is the Logic Multiplier. It requires input from the Network Router and the Signal Amplifier." + }, + { + "id": "hmac_sha256", + "name": "HMAC-SHA256 Calculator", + "description": "HMAC-SHA256(text) with hex key.", + "type": "Tool", + "template_id": "hmac_sha256", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex_key", + "type": "Hex_String", + "description": "Hex key", + "value": "68ba5578967a1daa1b73eea8fe205b6fbf6e03d580d239c945a5d204acf89ad7" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text message", + "value": "Critical system validation message for HMAC computation" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "HMAC Hex digest", + "value": "e3cb1f24d2fe9c0c3f2baf2d291a21dcc0bcd82cd8ab140658400c21c62a7d02" + } + ], + "init": { + "inputs": { + "text": "Critical system validation message for HMAC computation" + }, + "outputs": {} + }, + "narrative": "This is the Security Authenticator. It requires input from the Digital Scrambler to verify biometric traces." + }, + { + "id": "container_2", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_2", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Hex_String", + "description": "Fingerprint Hash", + "value": "a1b2c3d4e5f67890a1b2c3d4e5f67890" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "a1b2c3d4e5f67890a1b2c3d4e5f67890" + }, + "outputs": {} + }, + "narrative": "A Biometric Locker used by corporate security. It is covered in neon graffiti and reinforced steel." + }, + { + "id": "calc_modexp", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "32" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "83948572638194758264" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "402183763748143429283021565875961314880" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "351143656513576224633640702949884472896" + } + ], + "init": { + "inputs": { + "base": "32", + "exp": "83948572638194758264" + }, + "outputs": {} + }, + "narrative": "This is the Power Calibrator. It requires input from the Logic Multiplier to stabilize the grid." + }, + { + "id": "hash_sha256", + "name": "SHA-256 Hasher", + "description": "SHA-256 over UTF-8 text; returns hex.", + "type": "Tool", + "template_id": "hash_sha256", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Text to hash", + "value": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\", \"Node_Omega\"]" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "SHA-256 Hex digest", + "value": "68ba5578967a1daa1b73eea8fe205b6fbf6e03d580d239c945a5d204acf89ad7" + } + ], + "narrative": "This is the Digital Scrambler. It requires input from the Traffic Analyzer to mask your signal." + }, + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "extracted_payload_99.csv" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "[\"Gateway\", \"Router_1\", \"Switch_A\", \"Firewall\", \"Load_Balancer\", \"Server_Final\"]" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Node_Omega" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\", \"Node_Omega\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "450210" + } + ], + "init": { + "inputs": { + "dst": "Node_Omega" + }, + "outputs": { + "path": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\", \"Node_Omega\"]", + "cost": "450210" + } + }, + "narrative": "This is the Traffic Analyzer. It requires input from the Data Extractor and the Network Router." + }, + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "archive_data_77.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "secure_pass_123" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_payload_99.csv" + } + ], + "init": { + "inputs": { + "zip_id": "archive_data_77.zip", + "password": "secure_pass_123" + }, + "outputs": { + "files": "extracted_payload_99.csv" + } + }, + "narrative": "The Data Extractor. An old software terminal left behind by underground hackers." + }, + { + "id": "container_4", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_4", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Text_Generic", + "description": "Fingerprint Hash", + "value": "D\u0012\u0017\u001d^sz6" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is the Evidence Lockbox. It requires input from the Cipher Decoder to bypass its electronic seal." + }, + { + "id": "crypto_rsa_decrypt_hex", + "name": "RSA Decrypt", + "description": "RSA decrypt (hex cipher) with n,d (decimal).", + "type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex_cipher", + "type": "Hex_String", + "description": "Ciphertext (Hex)", + "value": "9382e486" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Modulus n", + "value": "94857263819475826473928174" + }, + { + "name": "d", + "type": "Big_Int", + "description": "Private exponent d", + "value": "48572638194758264739281745" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decrypted text", + "value": "D\u0012\u0017\u001d^sz6" + } + ], + "init": { + "inputs": { + "n": "94857263819475826473928174", + "d": "48572638194758264739281745" + }, + "outputs": {} + }, + "narrative": "This is the Cipher Decoder. It requires input from the Node Verifier." + }, + { + "id": "graph_shortest_path_53ed", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "network_graph_82.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Hello World! Decode me" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Server_Final" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Gateway\", \"Router_1\", \"Switch_A\", \"Firewall\", \"Load_Balancer\", \"Server_Final\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "889312" + } + ], + "init": { + "inputs": { + "file_id": "network_graph_82.json", + "dst": "Server_Final" + }, + "outputs": { + "path": "[\"Gateway\", \"Router_1\", \"Switch_A\", \"Firewall\", \"Load_Balancer\", \"Server_Final\"]", + "cost": "889312" + } + }, + "narrative": "This is the Network Router. It requires input from the Signal Decoder to route the encrypted pathways." + }, + { + "id": "calc_bigmul_0ba9", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": 2474828934 + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "182736455463728192039485" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "452241467278236917170825948458990" + } + ], + "init": { + "inputs": { + "b": "182736455463728192039485" + }, + "outputs": {} + }, + "narrative": "This is the Signal Amplifier. It requires input from the Node Verifier." + }, + { + "id": "item_16_4531", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "The Sector Badge. A vital piece of identification for navigating this forgotten neon district." + }, + { + "id": "checksum_crc32_6747", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "aabbccddeeff112233445566" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "9382e486" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 2474828934 + } + ], + "init": { + "inputs": { + "hex": "aabbccddeeff112233445566" + }, + "outputs": {} + }, + "narrative": "The Node Verifier. A standalone diagnostic terminal from the old era." + }, + { + "id": "container_4_d115", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_4", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Text_Generic", + "description": "Fingerprint Hash", + "value": "unique_fingerprint_hash_string_99" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "unique_fingerprint_hash_string_99" + }, + "outputs": {} + }, + "narrative": "A heavy Tool Box covered in grease and glowing wire scraps. Standard issue for street mechanics." + }, + { + "id": "item_16_9fc2", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A high-level Clearance Tag with a cracked holographic display." + }, + { + "id": "hex_decode", + "name": "Hex to Text Decoder", + "description": "Decode hex to UTF-8 text.", + "type": "Tool", + "template_id": "hex_decode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex string", + "value": "48656c6c6f20576f726c6421204465636f6465206d65" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decoded text", + "value": "Hello World! Decode me" + } + ], + "init": { + "inputs": { + "hex": "48656c6c6f20576f726c6421204465636f6465206d65" + }, + "outputs": {} + }, + "narrative": "The Signal Decoder. A rusted but functional black market terminal hooked up to a jury-rigged antenna." + } + ], + "edges": [ + { + "source_id": "item_16", + "target_id": "item_7", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "container_3", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "num_base_convert", + "target_id": "container_3", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "fingerprint_input" + }, + { + "source_id": "item_16_f971", + "target_id": "container_3", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "calc_bigmul", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "s" + }, + { + "source_id": "checksum_crc32", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "from_base" + }, + { + "source_id": "calc_bigmul_d486", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "a" + }, + { + "source_id": "checksum_crc32_b2b3", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "to_base" + }, + { + "source_id": "checksum_crc32", + "target_id": "checksum_crc32_b2b3", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "calc_bigmul_2fdb", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "b" + }, + { + "source_id": "hmac_sha256", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "container_2", + "target_id": "item_16_f971", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "calc_modexp", + "target_id": "calc_bigmul_d486", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "a" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_bigmul_d486", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "b" + }, + { + "source_id": "calc_bigmul_2fdb", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "mod" + }, + { + "source_id": "hash_sha256", + "target_id": "hmac_sha256", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_key" + }, + { + "source_id": "graph_shortest_path", + "target_id": "hash_sha256", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "text" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "container_4", + "target_id": "zip_unzip_file", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "crypto_rsa_decrypt_hex", + "target_id": "container_4", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "fingerprint_input" + }, + { + "source_id": "graph_shortest_path_53ed", + "target_id": "calc_bigmul_2fdb", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "b" + }, + { + "source_id": "graph_shortest_path_53ed", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "src" + }, + { + "source_id": "calc_bigmul_0ba9", + "target_id": "calc_bigmul_2fdb", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "a" + }, + { + "source_id": "item_16_4531", + "target_id": "container_2", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "checksum_crc32_6747", + "target_id": "calc_bigmul_0ba9", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "a" + }, + { + "source_id": "checksum_crc32_6747", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_cipher" + }, + { + "source_id": "container_4_d115", + "target_id": "item_16_4531", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "item_16_9fc2", + "target_id": "container_4_d115", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "hex_decode", + "target_id": "graph_shortest_path_53ed", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "src" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-c32db50f/environment/puzzle/service.py b/tasks/agentescape-25-skeleton-c32db50f/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-25-skeleton-c32db50f/environment/puzzle/service.py @@ -0,0 +1,212 @@ +"""Restricted facade over the unchanged, pinned upstream puzzle handlers.""" + +import hashlib +import json +import logging +import os +import sys +import threading +import urllib.request +import uuid +from pathlib import Path + +from fastapi import FastAPI, HTTPException +from fastapi.responses import JSONResponse +from pydantic import BaseModel, ConfigDict + +sys.path.insert(0, str(Path(__file__).parent / "upstream")) +import server as upstream # noqa: E402 + +log = logging.getLogger(__name__) + + +def public(value): + """Keep upstream agent-internal template hints out of the public response.""" + if isinstance(value, dict): + return {k: public(v) for k, v in value.items() if not k.startswith("_")} + if isinstance(value, list): + return [public(v) for v in value] + return value + + +class Action(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + action: str + node_id: str | None = None + arguments: dict | None = None + answer: str | None = None + + +class Episode: + def __init__( + self, scenario_path, max_actions=500, evidence_dir=None, worker_url=None + ): + if max_actions < 1: + raise ValueError("max_actions must be positive") + self.lock = threading.Lock() + self.max_actions = max_actions + self.count = 0 + self.won = False + self.reason = None + self.evidence_dir = Path(evidence_dir) if evidence_dir else None + self.scenario_hash = hashlib.sha256( + Path(scenario_path).read_bytes() + ).hexdigest() + self.initial = upstream.reset_case( + case_file_path=str(scenario_path), session_id=uuid.uuid4().hex + ) + self.case_id = self.initial["case_id"] + # Hide source file paths; no upstream reset/stats/routes are mounted. + self.initial.pop("message", None) + simulator = upstream.SIMULATORS[self.case_id] + if worker_url is None: + + def no_worker(_inputs): + self.reason = "infrastructure_error" + raise RuntimeError("isolated Python worker is not configured") + + simulator.tool_map["code_py_exec"] = no_worker + else: + + def execute_python(inputs): + request = urllib.request.Request( + worker_url + "/execute", + data=json.dumps({"code": inputs.get("code", "")}).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=12) as response: + result = json.load(response) + if not isinstance(result.get("stdout"), str): + raise RuntimeError("Invalid Python worker response") + return result + except Exception: + self.reason = "infrastructure_error" + raise + + simulator.tool_map["code_py_exec"] = execute_python + self.save() + if self.evidence_dir is not None: + (self.evidence_dir / "trace.jsonl").touch() + + def state(self): + return { + "scenario_sha256": self.scenario_hash, + "action_count": self.count, + "max_actions": self.max_actions, + "won": self.won, + "termination_reason": self.reason, + } + + def save(self, action=None, result=None): + if self.evidence_dir is None: + return + self.evidence_dir.mkdir(parents=True, exist_ok=True) + target = self.evidence_dir / "outcome.json" + temp = target.with_suffix(".tmp") + temp.write_text(json.dumps(self.state())) + temp.replace(target) + if action is not None: + with (self.evidence_dir / "trace.jsonl").open("a") as handle: + handle.write( + json.dumps( + {"index": self.count, "action": action, "result": result} + ) + + "\n" + ) + + def dispatch(self, payload): + with self.lock: + if self.reason is not None: + return { + "ok": False, + "error": "Episode has ended", + "episode": self.state(), + } + self.count += 1 + try: + action = Action.model_validate(payload) + if action.action == "submit_answer" and action.answer is not None: + result = upstream.submit_answer( + self.case_id, upstream.SubmitAnswerRequest(answer=action.answer) + ) + if result.get("is_win"): + self.won = True + self.reason = "success" + elif action.action == "investigate" and action.node_id is not None: + result = upstream.investigate( + self.case_id, + upstream.InvestigateRequest(node_id=action.node_id), + ) + elif ( + action.action in ("tool_call", "use_item") + and action.node_id is not None + ): + request_type, handler = ( + (upstream.ToolCallRequest, upstream.tool_call) + if action.action == "tool_call" + else (upstream.UseItemRequest, upstream.use_item) + ) + result = handler( + self.case_id, + request_type( + node_id=action.node_id, arguments=action.arguments or {} + ), + ) + else: + result = { + "ok": False, + "error": "Unknown action or missing action parameter", + } + except HTTPException as exc: + result = {"ok": False, "error": exc.detail} + except ValueError: + result = {"ok": False, "error": "Malformed action"} + except Exception: + log.exception("Puzzle service failure") + self.reason = "infrastructure_error" + self.save() + raise + if self.reason is None and self.count >= self.max_actions: + self.reason = "action_budget_exhausted" + result = public(result) + result["episode"] = self.state() + self.save(payload, result) + return result + + +def create_app( + scenario_path=None, max_actions=None, evidence_dir=None, worker_url=None +): + episode = Episode( + scenario_path or os.environ["SCENARIO_PATH"], + max_actions or int(os.environ.get("MAX_ACTIONS", "500")), + evidence_dir if evidence_dir is not None else os.environ.get("EVIDENCE_DIR"), + worker_url if worker_url is not None else os.environ.get("WORKER_URL"), + ) + app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) + app.state.episode = episode + + @app.get("/health") + def health(): + return {"ok": True} + + @app.get("/observation") + def observation(): + return {**public(episode.initial), "episode": episode.state()} + + @app.get("/state") + def state(): + return episode.state() + + @app.post("/action") + def action(payload: dict): + try: + return episode.dispatch(payload) + except Exception: + return JSONResponse( + status_code=503, + content={"ok": False, "error": "Puzzle infrastructure failure"}, + ) + + return app diff --git a/tasks/agentescape-25-skeleton-c32db50f/environment/puzzle/upstream/models.py b/tasks/agentescape-25-skeleton-c32db50f/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-25-skeleton-c32db50f/environment/puzzle/upstream/models.py @@ -0,0 +1,108 @@ +from enum import Enum +from typing import List, Dict, Any, Optional +from pydantic import BaseModel, Field + +# 1. 细粒度接口类型定义 +class InterfaceType(str, Enum): + ''' + BIG_INT + TEXT_GENERIC + HEX_STRING + FILE_ID + HEX_STRING_KEY_AES + HEX_STRING_IV_AES + CODE_PYTHON + HIDDEN_ITEM + ITEM + ''' + # --- 基础类型 --- + TEXT_GENERIC = "Text_Generic" + BIG_INT = "Big_Int" + + # --- 编码/格式化字符串 --- + HEX_STRING = "Hex_String" # 通用 Hex + + # --- 特定用途的 Hex 字符串 (用于精确匹配) --- + HEX_STRING_KEY_AES = "Hex_String_Key_AES" + HEX_STRING_IV_AES = "Hex_String_IV_AES" + + # --- 文件类型 --- + FILE_ID = "File_Id" + + # --- 代码/脚本 --- + CODE_PYTHON = "Code_Python" + + # --- 实体交互类型 (严格命名) --- + ITEM = "Item" # 主动掉落接口 (Tool -> Item) + HIDDEN_ITEM = "Hidden_Item" # 被动掉落接口 (Item -> Item) + +# 3. 端口定义 +class Port(BaseModel): + name: str + type: InterfaceType + description: str + +# 4. 统一节点定义 (融合工具和物品) +class Node(BaseModel): + id: str + name: str + description: str + type: str # "Tool" or "Item" + + # 接口定义 + inputs: List[Port] = [] + outputs: List[Port] = [] + + # 状态字段 + content: Optional[Any] = None # 物品有内容,工具为None + if_success: Optional[bool] = None # 工具初始为False,物品为None + initial_visible: bool = False + + # 运行时状态 (Server维护) + is_revealed: bool = False + + # 标记该 Tool 节点是否有待触发的 HIDDEN_ITEM 掉落 + # 当 Tool 按照 golden_input 正确执行且有 HIDDEN_ITEM 输出边时设为 True + # 在 investigate 该 Tool 时触发掉落并重置为 False + has_hidden_item_ready: bool = False + + # 初始输入值 (metadata.initial_values.init_inputs,用于渐进式暴露判断) + init_input_values: Dict[str, Any] = {} + + # Golden 输入值 (nodes[].inputs[].value,用于评测验证) + golden_input_values: Dict[str, Any] = {} + + # Golden 输出值 (nodes[].outputs[].value,用于评测验证和 Item 节点的 content) + golden_output_values: Dict[str, Any] = {} + + # 实际获得的输出值历史 (工具每次执行后实际返回的输出列表,用于渐进式暴露判断) + # 格式: List[Dict[str, Any]],每个元素是一次执行的输出字典 + actual_outputs_history: List[Dict[str, Any]] = [] + + # 逻辑规则 (用于终端机等复杂物品) + logic_rules: Optional[Dict[str, Any]] = None + + def copy(self, **kwargs): + """Helper to create a copy with updated fields.""" + data = self.dict() + data.update(kwargs) + return Node(**data) + +# 5. 边定义 (拓扑结构) +class Edge(BaseModel): + source_id: str + target_id: str + connection_type: InterfaceType # 直接使用 InterfaceType + # 如果是 Data_Flow,指定端口对应关系 + source_port: Optional[str] = None + target_port: Optional[str] = None + +# 6. 完整图定义 +class GraphScenario(BaseModel): + case_id: str + title: str + intro_narrative: str + nodes: Dict[str, Node] + edges: List[Edge] + difficulty: int + win_node_id: str # 标记哪个节点是最终目标(通常是一个提交工具或最终物品) diff --git a/tasks/agentescape-25-skeleton-c32db50f/environment/puzzle/upstream/server.py b/tasks/agentescape-25-skeleton-c32db50f/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-25-skeleton-c32db50f/environment/puzzle/upstream/server.py @@ -0,0 +1,1490 @@ +import json +import os +import time +import logging +import random +from pathlib import Path +from typing import Dict, Any, List, Optional +from datetime import datetime +from collections import defaultdict +from fastapi import FastAPI, HTTPException, Request +from fastapi.responses import JSONResponse +from fastapi.middleware.cors import CORSMiddleware +from pydantic import BaseModel, Field + +from models import GraphScenario, Node, InterfaceType +# from generator import ScenarioGenerator +from simulator import ToolSimulator +import uvicorn + +# 配置日志 +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler('server.log'), + logging.StreamHandler() + ] +) +logger = logging.getLogger(__name__) + +app = FastAPI( + title="AgentEscapeBench Universal Server", + version="1.0.0", + description="Industrial-grade evaluation server for escape room AI agents" +) + +# 添加 CORS 支持 +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# In-memory State +SCENARIOS: Dict[str, GraphScenario] = {} +SIMULATORS: Dict[str, ToolSimulator] = {} # case_id -> ToolSimulator +RAW_NODES_DATA: Dict[str, Dict[str, Any]] = {} # case_id -> node_id -> raw node data (for template_id) +FILE_METADATA: Dict[str, Dict[str, Any]] = {} # case_id -> metadata (for initial_values access) + +# Performance monitoring +STATS: Dict[str, Any] = { + "total_requests": 0, + "successful_requests": 0, + "failed_requests": 0, + "tool_calls": defaultdict(int), + "investigates": defaultdict(int), + "use_items": defaultdict(int), + "case_loads": 0, + "start_time": datetime.now() +} + +# Request timing middleware +@app.middleware("http") +async def add_process_time_header(request: Request, call_next): + start_time = time.time() + STATS["total_requests"] += 1 + + try: + response = await call_next(request) + STATS["successful_requests"] += 1 + process_time = time.time() - start_time + response.headers["X-Process-Time"] = str(process_time) + logger.info(f"{request.method} {request.url.path} - {response.status_code} - {process_time:.3f}s") + return response + except Exception as e: + STATS["failed_requests"] += 1 + logger.error(f"{request.method} {request.url.path} - Error: {str(e)}") + raise + +# Exception handler +@app.exception_handler(Exception) +async def global_exception_handler(request: Request, exc: Exception): + logger.error(f"Unhandled exception: {exc}", exc_info=True) + return JSONResponse( + status_code=500, + content={ + "ok": False, + "error": "Internal server error", + "detail": str(exc) if os.getenv("DEBUG") else "An error occurred" + } + ) + +# Health check endpoint +@app.get("/health") +def health_check(): + """健康检查端点""" + uptime = (datetime.now() - STATS["start_time"]).total_seconds() + return { + "status": "healthy", + "version": "1.0.0", + "uptime_seconds": uptime, + "loaded_cases": len(SCENARIOS), + "stats": { + "total_requests": STATS["total_requests"], + "successful_requests": STATS["successful_requests"], + "failed_requests": STATS["failed_requests"], + "success_rate": STATS["successful_requests"] / max(STATS["total_requests"], 1) + } + } + +# Statistics endpoint +@app.get("/stats") +def get_stats(): + """获取详细统计信息""" + return { + "stats": STATS, + "loaded_cases": list(SCENARIOS.keys()), + "uptime": str(datetime.now() - STATS["start_time"]) + } + +def _apply_progressive_reveal_at_init(scenario: GraphScenario): + """ + 在初始化时应用渐进式暴露机制(基于ITEM/HIDDEN_ITEM边) + + 新逻辑: + - 如果一个节点没有 ITEM/HIDDEN_ITEM 类型的入边,它就是初始可见的 + - 如果一个节点有 ITEM/HIDDEN_ITEM 类型的入边,它初始不可见,需要等待上游触发 + + Args: + scenario: 场景对象 + """ + # 收集所有有 ITEM/HIDDEN_ITEM 入边的节点 + nodes_with_item_edges = set() + for edge in scenario.edges: + if edge.connection_type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + nodes_with_item_edges.add(edge.target_id) + + logger.info(f"Nodes with ITEM/HIDDEN_ITEM incoming edges: {nodes_with_item_edges}") + + # 设置初始可见性:没有 ITEM/HIDDEN_ITEM 入边的节点初始可见 + initially_visible_count = 0 + for node_id, node in scenario.nodes.items(): + if node_id not in nodes_with_item_edges: + node.is_revealed = True + initially_visible_count += 1 + logger.info(f"Initial visible (no ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + else: + node.is_revealed = False + logger.debug(f"Initial hidden (has ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + + logger.info(f"Progressive reveal initialized: {initially_visible_count}/{len(scenario.nodes)} nodes initially visible") + + +def _check_inputs_match_golden(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> bool: + """ + 检查实际输入参数是否与 golden inputs 完全匹配 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + True 表示所有 golden inputs 都存在且值匹配 + """ + if not golden_inputs: + return True # 如果没有 golden inputs,认为匹配 + + for key, expected_value in golden_inputs.items(): + actual_value = arguments.get(key) + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) != str(expected_value): + logger.debug(f"Input mismatch for '{key}': expected '{expected_value}', got '{actual_value}'") + return False + + return True + + +def _get_parameter_validation_feedback(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> Dict[str, Any]: + """ + 对源头节点的参数进行详细验证,返回验证反馈 + + 注意:不返回期望值(expected),避免泄漏答案 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + 包含验证结果的字典: + - all_correct: bool - 所有参数是否正确 + - correct_params: List[str] - 正确的参数名列表 + - incorrect_params: List[str] - 错误的参数名列表(不包含期望值) + """ + if not golden_inputs: + return { + "all_correct": True, + "correct_params": [], + "incorrect_params": [] + } + + correct_params = [] + incorrect_params = [] + + for key, actual_value in arguments.items(): + # 只对用户实际提交的参数给反馈,未提交的参数不评价 + if key not in golden_inputs: + continue # 该参数不在 golden 中,跳过(如 _golden_inputs 等内部参数) + expected_value = golden_inputs[key] + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) == str(expected_value): + correct_params.append(key) + else: + # 只记录参数名,不包含期望值,避免泄漏答案 + incorrect_params.append(key) + + # all_correct:用户提交的所有参数都正确,且覆盖了全部 golden 参数 + all_provided_correct = len(incorrect_params) == 0 + all_golden_covered = all(k in arguments for k in golden_inputs) + return { + "all_correct": all_provided_correct and all_golden_covered, + "correct_params": correct_params, + "incorrect_params": incorrect_params + } + + +def _is_source_node(node_id: str, scenario: GraphScenario) -> bool: + """ + 判断节点是否是源头节点(完全没有任何入边的节点) + + 源头节点定义: + - 没有任何类型的入边(包括 DATA、ITEM、HIDDEN_ITEM) + - 即没有任何上游节点 + + Args: + node_id: 节点ID + scenario: 场景对象 + + Returns: + True 表示是源头节点 + """ + for edge in scenario.edges: + if edge.target_id == node_id: + # 只要有任何入边,就不是源头节点 + return False + + return True + + +def _check_and_reveal_ready_nodes(scenario: GraphScenario, recent_outputs: Dict[str, Any], source_node_id: str) -> List[Dict[str, Any]]: + """ + 检查并释放参数齐全的隐藏节点(渐进式暴露机制) + + 核心逻辑: + 1. 维护"可见值集合":包含所有被测模型当前可以看到的值 + - init_inputs 的值(初始可见) + - 工具执行后的实际输出值(运行时获得) + - 可见 Item 的输出值 + 2. 检查隐藏节点:该节点的所有 golden_input 值是否都在可见值集合中 + 3. 如果是,则释放该节点 + + Args: + scenario: 场景对象 + recent_outputs: 最近执行的工具的输出 + source_node_id: 刚执行的工具节点ID + + Returns: + 新释放的节点列表 + """ + newly_revealed = [] + + # 构建"可见值集合"(Set of visible values) + # 存储格式:set of values (转为字符串) + visible_values = set() + + # 1. 添加有意义的 init_inputs 值到可见值集合 + # Item 的 init_inputs 不应该加入,因为它们在密室中完全用不到 + for node_id, node in scenario.nodes.items(): + # 跳过源头 Item 节点(没有入边的 Item) + if node.type == "Item": + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,跳过其 init_inputs + continue + + # 添加其他节点的 init_inputs + for port_name, init_value in node.init_input_values.items(): + if init_value: + visible_values.add(str(init_value)) + + # 2. 添加已执行工具的所有历史输出值 + for node_id, node in scenario.nodes.items(): + if node.type == "Tool" and node.if_success and node.actual_outputs_history: + # 遍历所有历史执行记录 + for output_dict in node.actual_outputs_history: + for output_port_name, output_value in output_dict.items(): + if output_value: + visible_values.add(str(output_value)) + + # 3. 添加已被 investigate 的 Item 的 golden 输出值 + # 注意:Item 可见不等于其输出值可见,需要 investigate 后才能获得 + # 这里我们使用 actual_outputs_history 来标记 Item 是否已被 investigate + for node_id, node in scenario.nodes.items(): + if node.type == "Item" and node.is_revealed and node.actual_outputs_history: + # Item 通常只会被 investigate 一次,但为了一致性也使用历史列表 + for output_dict in node.actual_outputs_history: + for port_name, port_value in output_dict.items(): + if port_value: + visible_values.add(str(port_value)) + + # 遍历所有隐藏的节点,检查其 golden_input 是否都在可见值集合中 + for node_id, node in scenario.nodes.items(): + # 跳过已可见的节点 + if node.is_revealed: + continue + + # 只检查工具节点(物品节点由 ITEM 输出触发) + if node.type != "Tool": + continue + + # 检查该节点的所有 golden_input 值是否都在可见值集合中 + all_inputs_ready = True + missing_values = [] + + for input_port_name, golden_input_value in node.golden_input_values.items(): + # 检查这个 golden 值是否在可见值集合中 + if str(golden_input_value) not in visible_values: + all_inputs_ready = False + missing_values.append(f"{input_port_name}={golden_input_value}") + + # 如果所有 golden_input 值都在可见值集合中,释放该节点 + if all_inputs_ready and len(node.golden_input_values) > 0: + logger.info(f"All golden inputs ready for {node_id}: {list(node.golden_input_values.values())}") + + # 如果所有输入都齐全,释放该节点 + if all_inputs_ready: + node.is_revealed = True + + # 构建节点信息返回给模型 + node_info = { + "id": node.id, + "type": node.type, + "can_investigate": True, + "hint": "This tool's input parameters are now complete, you can use investigate to view detailed information" + } + + # if node.name: + # node_info["name"] = node.name + if node.description: + node_info["description"] = node.description + + newly_revealed.append(node_info) + logger.info(f"Progressive reveal: {node_id} is now ready (all inputs satisfied)") + + return newly_revealed + + +def _initialize_node_values(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]): + """ + Initialize node state and load values from port value fields. + 应用渐进式暴露机制:初始时只显示参数齐全的节点(源头节点) + + 重要区分: + 1. input_values: 只加载 metadata.initial_values 中的 init_inputs(真正的初始值) + 2. output_values: 加载 nodes[].outputs[].value(golden 输出,用于验证) + """ + # 第一步:加载所有节点的值,并将所有节点初始设为隐藏 + initial_values = metadata.get('initial_values', {}) + + for node_id, node in scenario.nodes.items(): + # 忽略 initial_visible 字段,初始全部隐藏 + # 由渐进式暴露机制根据参数齐全情况决定是否显示 + node.is_revealed = False + + if node.type == "Tool": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + elif node.type == "Item": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + + # 从 JSON 加载值 + if node_id in raw_nodes_data: + node_data = raw_nodes_data[node_id] # node_data是json文件中nodes中的字典 + + # 【重要】只加载 metadata.initial_values 中的初始输入值 + if node_id in initial_values: + init_data = initial_values[node_id] + # 加载初始输入值(用于渐进式暴露判断) + for port_name, port_value in init_data.get('init_inputs', {}).items(): + node.init_input_values[port_name] = port_value + + # 【评测用】加载 golden 输入值(用于验证模型传入的参数是否正确) + for input_port_data in node_data.get('inputs', []): + if 'value' in input_port_data: + node.golden_input_values[input_port_data['name']] = input_port_data['value'] + + # 【评测用】加载 golden 输出值(用于验证工具调用是否正确,以及 Item 节点的 content) + for output_port_data in node_data.get('outputs', []): + if 'value' in output_port_data: + node.golden_output_values[output_port_data['name']] = output_port_data['value'] + + # For Items, set content from golden_output_values + if node.type == "Item" and node.golden_output_values: + # Item 的 content 是其第一个 golden 输出值 + node.content = list(node.golden_output_values.values())[0] + + # 第二步:应用渐进式暴露机制 + # 检查所有节点,根据参数齐全情况释放源头节点(工具 + Item) + _apply_progressive_reveal_at_init(scenario) + +def _build_node_info(node: Node, raw_nodes_data: Dict[str, Any]) -> Dict[str, Any]: + """ + 构建节点信息(工具或物品) + + Args: + node: 节点对象 + raw_nodes_data: 原始节点数据(用于获取 template_id 等) + + Returns: + 节点信息字典 + """ + if node.type == "Tool": + # 过滤掉输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口) + # 这些端口仅用于控制掉落机制,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + tool_info = { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Tool", + "inputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.inputs if p.type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]], + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id(工具的标准名称) + if node.id in raw_nodes_data: + node_data = raw_nodes_data[node.id] + template_id = node_data.get('template_id') + if template_id: + tool_info['template_id'] = template_id + + return tool_info + + elif node.type == "Item": + return { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Item" + } + + else: + return { + "id": node.id, + # "name": node.name, + "type": node.type + } + +def _get_initial_observation(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]) -> Dict[str, Any]: + """ + Generate initial observation for the agent (what they see when entering the room). + + 策略: + - Tools: 只显示名称和描述,不显示接口定义。需要 investigate 才能获得详细接口信息。 + - Items: 只显示存在,不显示内容。需要 investigate 才能获得内容值。 + - init_inputs: 作为"可用信息"告诉模型,这些是可以用作工具参数的初始值。 + - init_outputs: 不告诉模型(这些是答案,需要模型通过调用工具获得)。 + """ + available_entities = [] # 统一的实体列表(Tools 和 Items) + available_information = [] # 可用的初始信息(来自 init_inputs) + + # 从 metadata.initial_values 提取 init_inputs 作为可用信息 + # 只提供值本身,不透露这些值对应哪个节点的哪个参数,让模型自己推理 + # 注意:跳过源头 Item(没有入边的 Item)的 init_inputs,因为它们在密室中完全用不到 + initial_values = metadata.get('initial_values', {}) + # initial_values字段的格式 + # "initial_values": { + # "terminal_1": { + # "init_inputs": {}, + # "init_outputs": { + # "text_output": "System initialization complete.", + # "hex_output": "48656c6c6f20576f726c64", + # "item_dispenser": "掉落了一张纸条,上面写着“请勿随意触摸终端”" + # } + # } + # } + for node_id, init_data in initial_values.items(): + # 获取节点信息,判断是否为源头 Item + node = scenario.nodes.get(node_id) + if node and node.type == "Item": + # 检查是否为源头 Item(没有入边) + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,检查是否有 init_inputs + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 有 init_inputs,需要暴露这些参数 + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + # 处理完后跳过后续的通用逻辑 + continue + + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 为每个 init_input 值创建一个信息条目(不包含 source_node 和 parameter 信息) + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + + for node in scenario.nodes.values(): + if node.is_revealed: + # Tools: 只显示基本信息,提示可以 investigate 查看详细接口 + if node.type == "Tool": + tool_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Tool", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the tool's detailed interface information for calling" + } + # 只在 name 非空时添加 + # if node.name: + # tool_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_info["description"] = node.description + + available_entities.append(tool_info) + + # Items: 只显示基本信息,提示可以 investigate 查看内容 + elif node.type == "Item": + item_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Item", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the item's content" + } + # 只在 name 非空时添加 + # if node.name: + # item_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + item_info["description"] = node.description + + available_entities.append(item_info) + + return { + "narrative": scenario.intro_narrative, + "available_entities": available_entities, # 使用统一的实体列表 + "available_information": available_information, # 可用的初始信息(只包含 init_inputs) + "win_node_id": scenario.win_node_id # 胜利节点ID,让模型知道需要关注哪个节点 + } + +@app.post("/env/reset") +def reset_case(case_id: str = None, case_file_path: str = None, session_id: str = None): + """Loads a specific case from file and resets it. + + Args: + case_id: Optional case ID for resetting an existing case + case_file_path: Path to case file for loading a new case + session_id: Optional session ID to ensure isolation between concurrent evaluations + """ + logger.info(f"Reset request - case_id: {case_id}, case_file_path: {case_file_path}, session_id: {session_id}") + STATS["case_loads"] += 1 + + if case_file_path: + if not os.path.exists(case_file_path): + logger.error(f"Case file not found: {case_file_path}") + raise HTTPException(status_code=404, detail=f"File not found: {case_file_path}") + try: + with open(case_file_path, "r", encoding="utf-8") as f: + file_data = json.load(f) + + # 转换格式:从 DAG executor 生成的格式转换为 GraphScenario 格式 + # 1. 提取 metadata + metadata = file_data.get('metadata', {}) + + # 2. 生成 case_id, title, intro_narrative + # 【修复】为每个评测会话生成唯一的 case_id,防止并发评测时状态污染 + base_name = os.path.basename(case_file_path).replace('.json', '').replace('_full', '').replace('_full2', '') + + if session_id: + # 如果提供了 session_id,使用它来确保唯一性 + case_id = f"{base_name}_{session_id}" + else: + # 否则使用时间戳和随机数确保唯一性 + unique_suffix = f"{int(time.time() * 1000)}_{random.randint(1000, 9999)}" + case_id = f"{base_name}_{unique_suffix}" + + file_data['case_id'] = case_id + logger.info(f"Generated unique case_id: {case_id} (base: {base_name}, session: {session_id})") + + if 'title' not in file_data: + file_data['title'] = f"Escape Room: {file_data['case_id']}" + + if 'intro_narrative' not in file_data: # 目前的json文件中已经有了intro_narrative字段,不会使用下面一行的内容,而是使用每个评测问题的json文件中的对应字段 + 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]".' + + # 3. 转换 nodes 列表为字典(DAG executor 生成的文件中 nodes 是列表格式) + nodes_dict = {} + for node_data in file_data['nodes']: + nodes_dict[node_data['id']] = node_data # 这里的id是template_id之后可能添加一个后缀 + file_data['nodes'] = nodes_dict # 把列表转成一个字典 + + # 4. 添加缺失的字段 + if 'difficulty' not in file_data: + file_data['difficulty'] = metadata.get('total_nodes', 5) + + if 'win_node_id' not in file_data: + file_data['win_node_id'] = metadata.get('win_node_id', '') + + scenario = GraphScenario(**file_data) + + # Extract raw nodes data for template_id access + # nodes 已经在上面转换为字典格式 + raw_nodes_data = file_data.get('nodes', {}) + RAW_NODES_DATA[scenario.case_id] = raw_nodes_data + + # Store metadata for initial values access + FILE_METADATA[scenario.case_id] = metadata + + logger.info(f"Successfully parsed case file: {scenario.case_id}, nodes: {len(scenario.nodes)}, edges: {len(scenario.edges)}") + except Exception as e: + logger.error(f"Failed to load case file: {str(e)}", exc_info=True) + raise HTTPException(status_code=500, detail=f"Failed to load case file: {str(e)}") + + # Initialize node state and load values + _initialize_node_values(scenario, raw_nodes_data, metadata) + + SCENARIOS[scenario.case_id] = scenario + simulator = ToolSimulator() + SIMULATORS[scenario.case_id] = simulator + + 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'])}") + + # 生成初始观察信息(进入密室后看到的环境) + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + ''' + initial_observation的格式: + { + "narrative": scenario.intro_narrative, + "available_entities": available_entities # 使用统一的实体列表 + "available_information": available_information # 可用的初始信息(只包含 init_inputs) + } + ''' + + return { + "ok": True, + "message": f"Case loaded from {case_file_path}", + "case_id": scenario.case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果没有提供 case_file_path,但提供了 case_id,则尝试从内存重置 + if case_id and case_id in SCENARIOS: + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + metadata = FILE_METADATA.get(case_id, {}) + + # Reset dynamic fields and re-apply progressive reveal + # 重新初始化节点状态(包括渐进式暴露) + _initialize_node_values(scenario, raw_nodes_data, metadata) + + 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'])}") + + # 生成初始观察信息 + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + + return { + "ok": True, + "message": f"Case {case_id} reset.", + "case_id": case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果既没有 case_file_path,也没有在内存中找到,返回错误 + raise HTTPException( + status_code=400, + detail="Must provide case_file_path to load a new case, or use case_id to reset an existing case." + ) + +class InvestigateRequest(BaseModel): + node_id: str + +@app.post("/env/{case_id}/investigate") +def investigate(case_id: str, req: InvestigateRequest): + """ + Investigates a Tool or Item to reveal detailed information. + + - For Tools: Returns detailed interface information (inputs/outputs) needed to call the tool + - For Items: Returns content value and triggers hidden item drops + """ + logger.info(f"Investigate request - case_id: {case_id}, node_id: {req.node_id}") + STATS["investigates"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + node = scenario.nodes[req.node_id] + + if not node.is_revealed: + logger.warning(f"Attempt to investigate hidden node: {req.node_id}") + return {"ok": False, "error": "Node is not visible yet."} + + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + newly_revealed = [] + + # 处理 Tool 的 investigate + if node.type == "Tool": + logger.info(f"Investigating tool: {req.node_id}") + + # 返回工具的详细接口信息 + # id 字段使用 node.id(节点唯一标识),agent 用这个字段识别和调用具体的节点 + # template_id 是工具类型标识符,Agent 内部用于判断工具特性(如 terminal 类工具参数可选) + # 注意:只过滤输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口),这些端口仅用于控制掉落,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + # 【端口上游依赖提示 & 初始值直接给出】 + # 针对参数语义模糊(全为数字类型)的工具,在 investigate 返回信息中标注 + # 哪个输入端口来自哪个上游节点(upstream_from)。 + # 对于所有工具:若该节点不是纯源头节点(有任意数据流入边), + # 且某个端口没有上游入边(值来自初始可见参数),则直接给出该端口的 golden input 值。 + AMBIGUOUS_TOOLS = { + "num_base_convert", "calc_modexp", "calc_modexp_int", + "calc_inv_mod", "calc_inv_mod_int", "crypto_rsa_decrypt_hex", "geo_haversine" + } + # Terminal 类工具自带参数对错反馈机制,玩家/模型可自行试错, + # 无需在 investigate 时直接暴露 init_value + SELF_FEEDBACK_TOOLS = { + "terminal_1", "terminal_2", + "Logic Terminal", "Math Terminal", "Encryption Terminal", "Sequence Terminal" + } + _template_id_for_hint = raw_nodes_data.get(node.id, {}).get("template_id", "") + # 构建数据流入边映射(对所有工具):{target_port -> (source_node_id, source_port)} + _upstream_map = {} + for _edge in scenario.edges: + if (_edge.target_id == node.id + and _edge.connection_type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM] + and _edge.target_port is not None): + _upstream_map[_edge.target_port] = (_edge.source_id, _edge.source_port) + # 判断该节点是否有任意数据流入边(即不是纯源头节点) + _has_any_upstream = len(_upstream_map) > 0 + # 判断该节点是否有任意入边(包括 ITEM/HIDDEN_ITEM 掉落边) + # 有任意入边(含掉落边)但无数据流入边的节点,其输入来自初始可见参数,应直接给出 + _has_any_edge = any(_edge.target_id == node.id for _edge in scenario.edges) + # 构建 inputs 列表 + _inputs_list = [] + for p in node.inputs: + if p.type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + continue + port_dict = {"name": p.name, "type": p.type, "description": p.description} + if p.name in _upstream_map: + # 该端口有上游数据流依赖,且属于语义模糊工具 → 标注来源 + if _template_id_for_hint in AMBIGUOUS_TOOLS: + src_node_id, src_port = _upstream_map[p.name] + port_dict["upstream_from"] = f"{src_node_id}.{src_port}" if src_port else src_node_id + elif _has_any_edge and _template_id_for_hint not in SELF_FEEDBACK_TOOLS: + # 该节点有任意入边,但此端口没有数据流入边 → 值来自初始可见参数,直接给出 + # 排除自带反馈机制的 terminal 类工具(它们通过执行结果反馈对错,无需提前暴露参数值) + golden_val = node.golden_input_values.get(p.name) + if golden_val is not None: + port_dict["init_value"] = golden_val + _inputs_list.append(port_dict) + + tool_details = { + "id": node.id, # 节点 ID,用于唯一标识和调用这个具体节点 + "type": "Tool", + "inputs": _inputs_list, + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id 用于 Agent 内部判断工具类型(不会展示给被测模型) + if node.id in raw_nodes_data: + template_id = raw_nodes_data[node.id].get('template_id') + if template_id: + tool_details["_template_id"] = template_id # 使用下划线前缀标记为内部字段 + + # 只在 name 非空时添加 + # if node.name: + # tool_details["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_details["description"] = node.description + + # 添加 narrative 字段(如果存在) + if node.id in raw_nodes_data: + narrative = raw_nodes_data[node.id].get('narrative') + if narrative: + tool_details['narrative'] = narrative + + # 不再返回 init_values,避免泄漏答案 + # investigate 只应该返回工具的接口定义,不应该暴露初始值 + + # 【新增】检查该 Tool 是否有待触发的 HIDDEN_ITEM 掉落 + # 如果该工具已按照 golden_input 正确执行,且有 HIDDEN_ITEM 输出边,则触发掉落 + if node.has_hidden_item_ready: + logger.info(f"Tool has HIDDEN_ITEM ready - triggering passive drop for: {req.node_id}") + + # 遍历该工具的所有 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + # 重置标志,已经触发过了,避免重复 + node.has_hidden_item_ready = False + + logger.info(f"Tool investigation successful - node: {req.node_id}, revealed: {len(newly_revealed)}") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Tool", + "details": tool_details + } + + # 如果有新掉落的节点,添加到响应中 + if newly_revealed: + result["newly_revealed"] = newly_revealed + + return result + + # 处理 Item 的 investigate + elif node.type == "Item": + logger.info(f"Investigating item: {req.node_id}") + + # 【第一步】检查该 Item 是否有需要参数的输入端口 + # 如果有,且尚未通过 use_item 验证,则不返回内容,只返回参数要求 + required_inputs = [] + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + inputs_info = raw_node.get('inputs', []) + required_inputs = [ + { + "name": inp.get("name"), + "type": inp.get("type"), + "description": inp.get("description", "") + } + for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + # 如果有 required_inputs 且尚未通过 use_item 验证(if_success == False) + # 则不返回内容,只返回参数要求提示 + if required_inputs and not node.if_success: + logger.info(f"Item has required inputs and not yet unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "required_inputs": required_inputs + } + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + param_names = ', '.join([inp['name'] for inp in required_inputs]) + 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}" + + return result + + # 【新增】如果有 required_inputs 且已经通过 use_item 验证(if_success == True) + # 则返回提示:该节点已经被成功解决 + if required_inputs and node.if_success: + logger.info(f"Item has required inputs and already unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "message": "This item has already been successfully unlocked by you." + } + return result + + # 【第二步】该 Item 没有 required_inputs 或已通过验证,返回内容 + # 1. 返回 Item 的 golden_output_values(即 Item 的内容) + # 注意:某些 Item 仅用于触发 HIDDEN_ITEM 掉落,没有实际内容 + has_actual_content = bool(node.golden_output_values) or node.content is not None + content = node.golden_output_values if node.golden_output_values else node.content + + # 【关键】将 golden_output_values 追加到 actual_outputs_history,标记该 Item 已被 investigate + # 这样在渐进式暴露时,这些值才会被加入可见值集合 + # 即使是空字典(仅触发 HIDDEN_ITEM 的 Item),也要记录,以便渐进式暴露逻辑知道该 Item 已被调查 + if node.golden_output_values is not None: + node.actual_outputs_history.append(dict(node.golden_output_values)) + + # 2. Trigger Hidden Item Drops (Passive Drop) + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + logger.info(f"Item investigation successful - node: {req.node_id}, has_content: {has_actual_content}, revealed: {len(newly_revealed)}") + + # 【渐进式暴露】旧机制(基于 golden_input)已禁用 + # 现在完全由 ITEM/HIDDEN_ITEM 边触发控制节点可见性 + # 上面的 HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, node.golden_output_values or {}, node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # logger.info(f"Progressive reveal after Item investigate: {len(progressive_revealed)} nodes now ready") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Item" + } + + # 只在有实际内容时才添加 content 字段 + # 对于仅触发 HIDDEN_ITEM 掉落的 Item,不返回 content 字段,避免返回 None 或空字典让模型困惑 + if has_actual_content: + result["content"] = content + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型通过 investigate 获得内容后,需要自己识别这是否是胜利字符串 + + return result + + else: + logger.warning(f"Attempt to investigate unknown node type: {req.node_id} (type: {node.type})") + return {"ok": False, "error": f"Cannot investigate node type: {node.type}"} + +class ToolCallRequest(BaseModel): + node_id: str # 使用 node_id 精确指定要调用的节点 + arguments: Dict[str, Any] + +@app.post("/env/{case_id}/tool_call") +def tool_call(case_id: str, req: ToolCallRequest): + """Executes a tool and triggers item drops.""" + logger.info(f"Tool call request - case_id: {case_id}, node_id: {req.node_id}, args: {list(req.arguments.keys())}") + STATS["tool_calls"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + + # 通过 node_id 精确查找节点 + node_id = req.node_id + if node_id not in scenario.nodes: + logger.error(f"Node not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + tool_node = scenario.nodes[node_id] + + if not tool_node: + logger.error(f"Tool not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Tool not found") + + if not tool_node.is_revealed: + logger.warning(f"Attempt to call hidden tool: {node_id}") + return {"ok": False, "error": "Tool is not visible yet."} + + if tool_node.type != "Tool": + logger.warning(f"Attempt to call non-tool node: {node_id} (type: {tool_node.type})") + return {"ok": False, "error": "Only tools can be called."} + + # 1. Execute Tool (Real Execution via Simulator) + simulator = SIMULATORS[case_id] + + # Get tool name from template_id if available, otherwise use node name + tool_name = tool_node.name + if case_id in RAW_NODES_DATA and node_id in RAW_NODES_DATA[case_id]: + template_id = RAW_NODES_DATA[case_id][node_id].get('template_id') + if template_id: + tool_name = template_id + + # 文件处理工具和 Terminal 需要验证输入并返回预先计算的输出 + # 传递节点的实际输入输出值(从 DAG 执行后填充的数据) + tool_arguments = dict(req.arguments) # Make a copy + + # 传递节点的 golden values(从 JSON 的 inputs[].value 和 outputs[].value 加载) + # 用于在评测阶段验证被测模型传入的参数是否正确 + if tool_node.golden_input_values: + tool_arguments['_golden_inputs'] = tool_node.golden_input_values + if tool_node.golden_output_values: + tool_arguments['_golden_outputs'] = tool_node.golden_output_values + + logger.debug(f"Executing tool {tool_name} (node: {tool_node.name}) with args {tool_arguments}") + + try: + output_values = simulator.execute(tool_name, tool_arguments) + logger.info(f"Tool invoked - {tool_name}: {list(output_values.keys())}") + except Exception as e: + logger.error(f"Tool execution failed - {tool_name}: {str(e)}", exc_info=True) + return {"ok": False, "error": f"Tool execution failed: {str(e)}"} + + # 检查验证结果(精细化错误反馈) + validation = output_values.pop("_validation", {"valid": True}) + + if not validation["valid"]: + # 根据错误类型构造友好的错误消息 + error_type = validation.get("error_type") + + if error_type == "missing_required": + missing = validation.get("missing_params", []) + error_msg = f"Error: Missing required parameters {', '.join(missing)}" + + elif error_type == "type_error": + param = validation.get("param_name") + message = validation.get("message", "Parameter type error") + error_msg = f"Error: {message}" + + elif error_type == "incomplete_optional": + provided = validation.get("provided_params", []) + missing = validation.get("missing_params", []) + error_msg = ( + f"Hint: You provided some parameters ({', '.join(provided)}), " + f"but may also need: {', '.join(missing)}.\n" + f"Trying to provide these parameters together might yield better results." + ) + + elif error_type == "value_mismatch": + param = validation.get("param_name") + hint = validation.get("hint", "Parameter value may be incorrect") + error_msg = f"Hint: {hint}.\nPlease check if this parameter value meets the requirements." + + else: + error_msg = validation.get("hint") or validation.get("message", "Parameter validation failed") + + logger.info(f"Tool validation failed - {tool_name}: {error_type}") + return { + "ok": False, + "error": error_msg, + "error_type": error_type + } + + # Simulate success + tool_node.if_success = True + + # 【关键】将本次执行的输出值追加到历史列表(用于渐进式暴露判断) + # 每次调用都会记录,不会覆盖之前的执行结果 + tool_node.actual_outputs_history.append(dict(output_values)) + + # 2. 检查是否应该触发掉落(只有输入参数正确时才掉落) + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, tool_node.golden_input_values) + + newly_revealed = [] + investigate_hints = [] # 提示模型哪些节点可以 investigate 来发现隐藏内容 + + if inputs_match_golden: + logger.info(f"✓ Tool inputs match golden - node: {node_id}, triggering drops") + + # 检查该工具是否有 ITEM 或 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == tool_node.id: + target_node = scenario.nodes[edge.target_id] + + # ITEM 边:立即掉落(主动掉落) + if edge.connection_type == InterfaceType.ITEM: + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from {node_id})") + + # HIDDEN_ITEM 边:不立即掉落,标记并提示(被动掉落) + elif edge.connection_type == InterfaceType.HIDDEN_ITEM: + # 标记该工具有待触发的 HIDDEN_ITEM 掉落 + tool_node.has_hidden_item_ready = True + + # 提示模型可以 investigate 这个工具来发现隐藏内容 + hint_info = { + "tool_id": tool_node.id, + "hint": f"Tool '{tool_node.id}' seems to hide something, try investigating it to discover more information" + } + # if tool_node.name: + # hint_info["tool_name"] = tool_node.name + + investigate_hints.append(hint_info) + logger.info(f"HIDDEN_ITEM ready: {tool_node.id} -> {target_node.id} (will drop on investigate)") + else: + logger.info(f"✗ Tool inputs do NOT match golden - node: {node_id}, no drops triggered") + + response = { + "ok": True, + "message": "Tool invoked", + "output_values": output_values # Return raw outputs to Agent + } + + # 【新增】对源头节点进行参数验证反馈 + # 源头节点:没有数据流入边的节点,这些节点的参数需要模型自己推理 + # 验证模型使用的参数是否正确,并提供明确的反馈 + if _is_source_node(node_id, scenario) and tool_node.golden_input_values: + validation_feedback = _get_parameter_validation_feedback(req.arguments, tool_node.golden_input_values) + + if validation_feedback["all_correct"]: + # 用户提交了全部 golden 参数且全部正确 + response["parameter_feedback"] = { + "status": "correct", + "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." + } + logger.info(f"✓ Source node parameters all correct - node: {node_id}") + elif validation_feedback["incorrect_params"]: + # 有提交了但值错误的参数,只对这些参数给出反馈 + incorrect_list = [] + for param_name in validation_feedback["incorrect_params"]: + incorrect_list.append(f" - Parameter '{param_name}' is incorrect") + + correct_info = "" + if validation_feedback["correct_params"]: + correct_info = f"\n✓ Correct parameters: {', '.join(validation_feedback['correct_params'])}" + + response["parameter_feedback"] = { + "status": "incorrect", + "message": ( + f"⚠️ Some parameters are incorrect:\n" + + "\n".join(incorrect_list) + + correct_info + + 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." + ), + "incorrect_params": validation_feedback["incorrect_params"], + "correct_params": validation_feedback["correct_params"] + } + logger.info(f"✗ Source node parameters incorrect - node: {node_id}, incorrect: {validation_feedback['incorrect_params']}") + # else: 部分提交且全部正确 → 不给任何 parameter_feedback,避免对未提交的参数发表意见 + + # 检查工具调用是否完全正确(输出与 golden outputs 匹配) + # 用于给模型正向反馈,让它知道这个工具已经正确调用过,避免重复调用 + # 注意:只有当输出完全匹配时才标记为 correct,不会在错误时提供具体错误信息 + # if tool_node.golden_output_values and output_values: + # is_correct = True + # for port_name, expected_value in tool_node.golden_output_values.items(): + # actual_value = output_values.get(port_name) + # if str(actual_value) != str(expected_value): + # is_correct = False + # break + + # if is_correct: + # response["tool_call_correct"] = True + # logger.info(f"✓ Tool called with correct result - node: {node_id}") + + # 只在有新内容掉落时才返回 newly_revealed + if newly_revealed: + response["newly_revealed"] = newly_revealed + + # 添加 investigate 提示(对于有待触发 HIDDEN_ITEM 掉落的工具) + if investigate_hints: + response["investigate_hints"] = investigate_hints + + # 3. 渐进式暴露机制 - 现在完全由 ITEM/HIDDEN_ITEM 边控制 + # 旧机制(基于 golden_input 检查)已被禁用 + # 新机制中,节点的可见性只由 ITEM/HIDDEN_ITEM 边触发决定 + # 上面的 ITEM/HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, output_values, tool_node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # response["newly_revealed"] = newly_revealed + # logger.info(f"Progressive reveal: {len(progressive_revealed)} nodes now ready") + + # Check if this is the win node + if node_id == scenario.win_node_id: + # 验证输出值是否等于预期的胜利值 + # 从节点的 golden_output_values 中获取预期值(在 _initialize_node_values 时从 JSON 加载) + expected_outputs = tool_node.golden_output_values + + # 检查实际输出是否与预期输出匹配 + is_correct = False + victory_string = None + mismatch_info = [] + + if expected_outputs and output_values: + # 检查每个预期输出端口的值是否匹配 + is_correct = True + for port_name, expected_value in expected_outputs.items(): + actual_value = output_values.get(port_name) + if actual_value != expected_value: + is_correct = False + mismatch_info.append(f"Port '{port_name}': expected '{expected_value}', actual '{actual_value}'") + logger.warning(f"Win node output mismatch - port: {port_name}, expected: {expected_value}, actual: {actual_value}") + + # 如果所有输出都匹配,使用第一个输出作为胜利字符串 + if is_correct and output_values: + victory_string = list(output_values.values())[0] + else: + logger.warning(f"Win node called but missing output values - expected: {expected_outputs}, actual: {output_values}") + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型调用工具获得输出后,需要自己识别这是否是胜利字符串并提交 + if is_correct: + logger.info(f"🎯 Win node called with correct output - case: {case_id}, node: {node_id}, victory: {victory_string}") + else: + logger.info(f"❌ Win node called with incorrect output - case: {case_id}, node: {node_id}") + + return response + +class UseItemRequest(BaseModel): + node_id: str = Field(..., description="The ID of the Item node to use (must be Item type)") + arguments: Dict[str, Any] = Field(default_factory=dict, description="Input arguments to provide to the item") + +@app.post("/env/{case_id}/use_item") +def use_item(case_id: str, req: UseItemRequest): + """ + Use an Item node by providing input arguments. + + This is specifically for Item nodes that require parameters to be "unlocked" or "activated", + such as containers that need a password/fingerprint. + + - Validates that the node is of type Item + - Checks if provided arguments match the item's golden_input_values + - If match: triggers ITEM-type edge drops and returns the item's content + - If not match: returns error message + """ + logger.info(f"Use item request - case_id: {case_id}, node_id: {req.node_id}, args: {req.arguments}") + STATS["use_items"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + item_node = scenario.nodes[req.node_id] + + if not item_node.is_revealed: + logger.warning(f"Attempt to use hidden item: {req.node_id}") + return {"ok": False, "error": "Item is not visible yet."} + + if item_node.type != "Item": + logger.warning(f"Attempt to use non-item node: {req.node_id} (type: {item_node.type})") + return {"ok": False, "error": "Only Item nodes can be used with use_item. Tools should be called with tool_call."} + + # 【新增】检查该 Item 是否已经被成功解锁 + # 如果已经被正确使用过,直接返回成功提示 + if item_node.if_success: + logger.info(f"Item already unlocked, returning success message: {req.node_id}") + return { + "ok": True, + "message": "This item has already been successfully unlocked by you." + } + + # 检查该 Item 是否真的需要通过 use_item 提供参数 + # 只有当 Item 有非 Item/Hidden_Item 类型的输入时,才应该使用 use_item + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + non_hidden_inputs = [ + inp for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + if not non_hidden_inputs: + # 该 Item 不需要参数,应该只使用 investigate + logger.warning(f"Attempt to use_item on a node that doesn't require parameters: {req.node_id}") + return { + "ok": False, + "error": "This item does not require parameters. Please use investigate to examine the item directly." + } + + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, item_node.golden_input_values) + + if not inputs_match_golden: + logger.info(f"✗ Item inputs do NOT match golden - node: {req.node_id}") + # 提供更详细的错误信息,帮助 Agent 理解问题 + # 只显示非 Item/Hidden_Item 类型的参数(Hidden_Item 由系统自动处理) + expected_params = [] + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + expected_params = [ + inp.get("name") for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + provided_params = list(req.arguments.keys()) if req.arguments else [] + + # 检查参数名是否匹配 + if set(expected_params) == set(provided_params): + # 参数名正确但值不匹配 - 不泄漏正确的值 + error_msg = f"Parameter names are correct, but the parameter values are incorrect. Please try using different parameter values." + else: + error_msg = f"Parameter names do not match. Expected parameter names: {expected_params}, you provided: {provided_params}." + + return { + "ok": False, + "error": error_msg + } + + logger.info(f"✓ Item inputs match golden - node: {req.node_id}, activating item") + + # 标记该 Item 已被正确使用 + item_node.if_success = True + + # 将 golden_output_values 追加到 actual_outputs_history + if item_node.golden_output_values: + item_node.actual_outputs_history.append(dict(item_node.golden_output_values)) + + # 触发 ITEM 类型边的掉落 + newly_revealed = [] + for edge in scenario.edges: + if edge.source_id == item_node.id and edge.connection_type == InterfaceType.ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from use_item on {req.node_id})") + + # 检查是否为 Win Node + win_node_id = scenario.win_node_id + is_win_node = (req.node_id == win_node_id) + + # 构建返回结果 + result = { + "ok": True, + "message": "Item used successfully.", + "content": item_node.golden_output_values if item_node.golden_output_values else None + } + + # 获取 narrative(如果存在) + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + narrative = raw_nodes_data[req.node_id].get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 如果是 Win Node,只记录日志 + if is_win_node: + logger.info(f"Win node (Item) unlocked via use_item - case: {case_id}, node: {req.node_id}") + + return result + + +class SubmitAnswerRequest(BaseModel): + answer: str = Field(..., description="The victory string to submit") + +@app.post("/env/{case_id}/submit_answer") +def submit_answer(case_id: str, req: SubmitAnswerRequest): + """ + 提交答案接口 + 被测模型在获得胜利字符串提示后,需要调用此接口提交答案 + """ + logger.info(f"Submit answer request - case_id: {case_id}, answer: {req.answer}") + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + + # 获取 win_node 的 golden_output_values + if not scenario.win_node_id: + logger.error(f"No win node defined for case: {case_id}") + return { + "ok": False, + "error": "This case has no victory node defined" + } + + win_node = scenario.nodes.get(scenario.win_node_id) + if not win_node: + logger.error(f"Win node not found: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node does not exist" + } + + # 获取正确的胜利字符串(取第一个 golden_output_value) + if win_node.golden_output_values: + correct_answer = list(win_node.golden_output_values.values())[0] + else: + logger.error(f"Win node has no golden_output_values: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node has no correct answer" + } + + # 验证提交的答案 + if req.answer == correct_answer: + logger.info(f"🎉 CORRECT ANSWER SUBMITTED - case: {case_id}, answer: {req.answer}") + return { + "ok": True, + "is_win": True, + "victory_message": f"🎉 Congratulations on successfully escaping the room! Your answer is correct: {req.answer}" + } + else: + logger.info(f"❌ INCORRECT ANSWER SUBMITTED - case: {case_id}, submitted: {req.answer}, correct: {correct_answer}") + return { + "ok": True, + "is_win": False, + "error": f"The submitted answer is incorrect. You submitted: {req.answer}" + } + +if __name__ == "__main__": + + uvicorn.run(app, host="0.0.0.0", port=8000) \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-c32db50f/environment/puzzle/upstream/simulator.py b/tasks/agentescape-25-skeleton-c32db50f/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-25-skeleton-c32db50f/environment/puzzle/upstream/simulator.py @@ -0,0 +1,2911 @@ +import hashlib +import hmac +import base64 +import binascii +import zlib +import json +import uuid +import math +import re +from typing import Dict, Any, List + +class ToolSimulator: + def __init__(self): + """工具模拟器 + + 文件处理工具(zip_unzip, zip_unzip_file, zip_unzip_item, json_get, csv_query, + regex_search, graph_shortest_path)不需要真实文件系统。 + 这些工具只验证输入参数,然后返回预先初始化好的 golden_outputs。 + """ + self.tool_map = { + # 数论 + "calc_bigmul": self.calc_bigmul, + "calc_modexp": self.calc_modexp, + "calc_modexp_int": self.calc_modexp_int, + "calc_gcd": self.calc_gcd, + "calc_gcd_int": self.calc_gcd_int, + "calc_inv_mod": self.calc_inv_mod, + "calc_inv_mod_int": self.calc_inv_mod_int, + + # 哈希 + "hash_sha256": self.hash_sha256, + "hash_md5": self.hash_md5, + "hmac_sha256": self.hmac_sha256, + + # 编码 + "base64_decode": self.base64_decode, + "base64_encode": self.base64_encode, + "hex_decode": self.hex_decode, + "hex_encode": self.hex_encode, + "zlib_inflate": self.zlib_inflate, + "zlib_deflate": self.zlib_deflate, + + # 文件 + "zip_unzip": self.zip_unzip, + "zip_unzip_file": self.zip_unzip_file, + "zip_unzip_item": self.zip_unzip_item, + "regex_search": self.regex_search, + "json_get": self.json_get, + "csv_query": self.csv_query, + "code_py_exec": self.code_py_exec, + + # 图 + "graph_shortest_path": self.graph_shortest_path, + + # 加解密 (简化模拟) + "crypto_aes_cbc_decrypt": self.crypto_aes_cbc_decrypt, + "crypto_rsa_decrypt_hex": self.crypto_rsa_decrypt_hex, + + # 其他 + "num_base_convert": self.num_base_convert, + "time_convert": self.time_convert, + "checksum_crc32": self.checksum_crc32, + "geo_haversine": self.geo_haversine, + "otp_totp_generate": self.otp_totp_generate, + "unicode_norm": self.unicode_norm, + "text_bidi_sanitize": self.text_bidi_sanitize, + "text_xor_hex": self.text_xor_hex, + "text_rotN": self.text_rotN, + "luhn_check": self.luhn_check, + "iban_validate": self.iban_validate, + + # 物理 + "matter_synthesizer": self.matter_synthesizer, + + # 终端机 + "terminal_1": self.terminal_1, + "terminal_2": self.terminal_2, + "Logic Terminal": self.logic_terminal, + "Math Terminal": self.math_terminal, + "Encryption Terminal": self.crypt_terminal, + "Sequence Terminal": self.sequence_terminal + } + + def execute(self, tool_name: str, inputs: Dict[str, Any]) -> Dict[str, Any]: + if tool_name not in self.tool_map: + # Fallback for unknown tools: return dummy outputs based on expected output types + # This should ideally not happen if all tools are implemented + return {} + + try: + return self.tool_map[tool_name](inputs) + except Exception as e: + print(f"Error executing {tool_name}: {e}") + # Return empty or error indication? For generation, we might want to fail hard or return dummy. + # For now, return dummy to keep flow going, but log error. + return {} + + # --- Implementations --- + + def calc_bigmul(self, inputs): + # Check if required parameters are present + if "a" not in inputs or "b" not in inputs: + raise ValueError("Missing required parameters 'a' and/or 'b'") + + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + return {"product": str(a * b)} + except (ValueError, TypeError) as e: + raise ValueError(f"Failed to convert parameters to integers: {str(e)}") + + def calc_modexp(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + try: + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if isinstance(base, str): + base = int(base) + elif not isinstance(base, int): + raise ValueError("Parameter 'base' must be a string or integer") + + if isinstance(exp, str): + exp = int(exp) + elif not isinstance(exp, int): + raise ValueError("Parameter 'exp' must be a string or integer") + + if isinstance(mod, str): + mod = int(mod) + elif not isinstance(mod, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": str(pow(base, exp, mod))} + + def calc_modexp_int(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["base"], int): + raise ValueError("Parameter 'base' must be an integer") + if not isinstance(inputs["exp"], int): + raise ValueError("Parameter 'exp' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": pow(base, exp, mod)} + + def calc_gcd(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + # 计算 GCD 并返回字符串格式(符合 Big_Int 输出类型) + result = math.gcd(a, b) + return {"gcd": str(result)} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def calc_gcd_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["b"], int): + raise ValueError("Parameter 'b' must be an integer") + + # 获取参数 + a = inputs["a"] + b = inputs["b"] + + return {"gcd": math.gcd(a, b)} + + def calc_inv_mod(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + m = inputs["mod"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(m, str): + m = int(m) + elif not isinstance(m, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": str(pow(a, -1, m))} + except ValueError as e: + # 模逆不存在时,返回一个特殊值(用于数据传递) + # 在 DAG 生成阶段,这允许数据流继续 + return {"inv": str(a)} + + def calc_inv_mod_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + a = inputs["a"] + m = inputs["mod"] + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": pow(a, -1, m)} + except ValueError as e: + raise ValueError(f"Modular inverse does not exist: {str(e)}") + + def hash_sha256(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.sha256(text.encode()).hexdigest()} + + def hash_md5(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.md5(text.encode()).hexdigest()} + + def hmac_sha256(self, inputs): + # 参数检查 + if "hex_key" not in inputs: + raise ValueError("Missing required parameter: hex_key") + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["hex_key"], str): + raise ValueError("Parameter 'hex_key' must be a string") + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + try: + key = bytes.fromhex(inputs["hex_key"]) + text = inputs["text"].encode() + return {"hex": hmac.new(key, text, hashlib.sha256).hexdigest()} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def base64_decode(self, inputs): + # 参数检查 + if "data" not in inputs: + raise ValueError("Missing required parameter: data") + + # 类型检查 + if not isinstance(inputs["data"], str): + raise ValueError("Parameter 'data' must be a string") + + data = inputs["data"] + try: + return {"bytes_hex": binascii.hexlify(base64.b64decode(data)).decode()} + except Exception as e: + raise ValueError(f"Base64 decode error: {str(e)}") + + def base64_encode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"b64": base64.b64encode(bytes.fromhex(hex_data)).decode()} + except Exception as e: + raise ValueError(f"Base64 encode error: {str(e)}") + + def hex_decode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"text": bytes.fromhex(hex_data).decode('utf-8', errors='ignore')} + except Exception as e: + raise ValueError(f"Hex decode error: {str(e)}") + + def hex_encode(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + try: + return {"hex": text.encode().hex()} + except Exception as e: + raise ValueError(f"Hex encode error: {str(e)}") + + + # 到此处实现已经更新 + + def zlib_inflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("Parameter 'hex' must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("Missing required parameter: hex") + + try: + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空字符串 + if not hex_data: + raise ValueError("Empty hex string provided") + + # 检查十六进制字符串的有效性 + if len(hex_data) % 2 != 0: + raise ValueError("Hex string must have even length") + + # 检查是否只包含有效的十六进制字符 + if not all(c in '0123456789abcdefABCDEF' for c in hex_data): + raise ValueError("Invalid hex string provided") + + # 尝试解压缩 + return {"text": zlib.decompress(bytes.fromhex(hex_data)).decode('utf-8')} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hex string provided") from e + raise ValueError(f"Invalid zlib data: {e}") from e + except Exception as e: + raise RuntimeError(f"Failed to inflate data: {e}") from e + + def zlib_deflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("Parameter 'text' must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("Missing required parameter: text") + + try: + # 压缩文本 + return {"hex": zlib.compress(text.encode('utf-8')).hex()} + except Exception as e: + raise RuntimeError(f"Failed to deflate data: {e}") from e + + # --- File Operations --- + + def zip_unzip(self, inputs): + """ZIP 解压工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"files": golden_outputs.get("files", "")} + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return {"files": golden_outputs.get("files", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "files" in golden_outputs: + # 验证必需参数 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 检查类型 + if has_zip_id and not isinstance(zip_id, str): + return {"error": "Parameter 'zip_id' must be a string type"} + if has_password and not isinstance(password, str): + return {"error": "Parameter 'password' must be a string type"} + + # 验证输入是否与预期匹配 + if golden_inputs: + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return {"files": golden_outputs["files"]} + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + # 没有golden_inputs但有golden_outputs,直接返回输出 + return {"files": golden_outputs["files"]} + + # 如果没有预期输出,返回空结果 + return {"files": ""} + + def regex_search(self, inputs): + """正则搜索工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"matches": golden_outputs.get("matches", "[]")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "matches" in golden_outputs: + # 提取实际参数 + pattern = inputs.get("pattern") + file_id = inputs.get("file_id") + text = inputs.get("text") + + # 1. 检查必需参数 + if pattern is None: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["pattern"], + "message": "Missing required parameter 'pattern'" + } + } + + # 类型检查 + if not isinstance(pattern, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "pattern", + "message": "Parameter 'pattern' must be a string type" + } + } + if file_id is not None and not isinstance(file_id, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if text is not None and not isinstance(text, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "text", + "message": "Parameter 'text' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合 + provided_params = {} + if pattern is not None: + provided_params["pattern"] = pattern + if file_id is not None: + provided_params["file_id"] = file_id + if text is not None: + provided_params["text"] = text + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数(关键改进) + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_pattern = golden_inputs.get("pattern") + expected_file_id = golden_inputs.get("file_id") + expected_text = golden_inputs.get("text") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_pattern is not None: + if str(pattern) != str(expected_pattern): + incorrect_params.append("pattern") + else: + correct_params.append("pattern") + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_text is not None: + if str(text) != str(expected_text): + incorrect_params.append("text") + else: + correct_params.append("text") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "matches": "[]", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "matches": golden_outputs["matches"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空列表 + return {"matches": "[]"} + + def json_get(self, inputs): + """JSON 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"values": golden_outputs.get("values", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "values" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + jsonpath = inputs.get("jsonpath", "") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if jsonpath is not None and not isinstance(jsonpath, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "jsonpath", + "message": "Parameter 'jsonpath' must be a string type" + } + } + + # 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:jsonpath有默认值"") + provided_params = {} + if file_id is not None: + provided_params["file_id"] = file_id + if jsonpath != "": + provided_params["jsonpath"] = jsonpath + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_jsonpath = golden_inputs.get("jsonpath") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_jsonpath is not None: + if str(jsonpath) != str(expected_jsonpath): + incorrect_params.append("jsonpath") + else: + correct_params.append("jsonpath") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "values": "", + "_validation": validation_info + } + + # 所有验证通过,返回正确输出 + return { + "values": golden_outputs["values"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"values": ""} + + def csv_query(self, inputs): + """CSV 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"rows": golden_outputs.get("rows", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "rows" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + select_columns = inputs.get("select", "") + where_clause = inputs.get("where", "") + + # 1. 检查必需参数 + if file_id is None: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["file_id"], + "message": "Missing required parameter 'file_id'" + } + } + + # 类型检查 + if not isinstance(file_id, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if not isinstance(select_columns, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "select", + "message": "Parameter 'select' must be a string type" + } + } + if not isinstance(where_clause, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "where", + "message": "Parameter 'where' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:select和where有默认值"") + provided_params = {"file_id": file_id} + if select_columns != "": + provided_params["select"] = select_columns + if where_clause != "": + provided_params["where"] = where_clause + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_select = golden_inputs.get("select") + expected_where = golden_inputs.get("where") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_select is not None: + if str(select_columns) != str(expected_select): + incorrect_params.append("select") + else: + correct_params.append("select") + + if expected_where is not None: + if str(where_clause) != str(expected_where): + incorrect_params.append("where") + else: + correct_params.append("where") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "rows": "", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "rows": golden_outputs["rows"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"rows": ""} + + def graph_shortest_path(self, inputs): + """图最短路径工具 + + 如果有 _golden_outputs 或 _init_outputs,验证输入并返回预设输出。 + 否则执行真实的 Dijkstra 算法。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 检查是否在预设模式中(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + if golden_outputs and "path" in golden_outputs: + # 评测阶段但没有 golden_inputs,直接返回 outputs + if not golden_inputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 评测模式:验证输入参数是否匹配 golden 值 + src = inputs.get("src") + dst = inputs.get("dst") + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + + has_src = src is not None and src != "" + has_dst = dst is not None and dst != "" + + # 验证必需参数 + if not has_src or not has_dst: + missing = [] + if not has_src: + missing.append("src") + if not has_dst: + missing.append("dst") + return {"error": "Missing required parameters: " + ", ".join(missing)} + + # 类型检查 + if not isinstance(src, str): + return {"error": "Parameter 'src' must be a string"} + if not isinstance(dst, str): + return {"error": "Parameter 'dst' must be a string"} + + # 验证输入是否匹配期望值 + if golden_inputs: + expected_src = golden_inputs.get("src") + expected_dst = golden_inputs.get("dst") + expected_file_id = golden_inputs.get("file_id") + expected_graph_data = golden_inputs.get("graph_data") + + # 收集验证结果 + incorrect_params = [] + correct_params = [] + + # 检查必需参数是否匹配 + if expected_src is not None: + if str(src) != str(expected_src): + incorrect_params.append("src") + else: + correct_params.append("src") + + if expected_dst is not None: + if str(dst) != str(expected_dst): + incorrect_params.append("dst") + else: + correct_params.append("dst") + + # 检查可选参数(如果在 expected_inputs 中定义了) + if expected_file_id is not None: + if file_id != expected_file_id: + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_graph_data is not None: + if graph_data != expected_graph_data: + incorrect_params.append("graph_data") + else: + correct_params.append("graph_data") + + # 如果有参数不正确,返回详细的反馈 + if incorrect_params: + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 验证通过,返回预设的输出 + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 获取参数(真实执行路径) + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + # Support both src/dst (interface definition) and start/end (original implementation) + start = inputs.get("src") + end = inputs.get("dst") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + raise TypeError("file_id must be a string") + + if graph_data is not None and not isinstance(graph_data, str): + raise TypeError("graph_data must be a string") + + if start is not None and not isinstance(start, str): + raise TypeError("src/start must be a string") + + if end is not None and not isinstance(end, str): + raise TypeError("dst/end must be a string") + + # 检查必需参数 + if file_id is None and graph_data is None: + raise ValueError("Either file_id or graph_data must be provided") + + if start is None: + raise ValueError("src/start parameter is required") + + if end is None: + raise ValueError("dst/end parameter is required") + + # Get graph content + content = None + if file_id is not None: + # 尝试从 VFS 获取(如果存在) + if hasattr(self, 'vfs') and file_id in self.vfs: + content = self.vfs[file_id] + else: + # VFS 不存在或文件不在 VFS 中 + # 返回一个默认的空图结果,或者抛出错误提示需要 init_outputs + raise ValueError( + f"File '{file_id}' not found. For tools that require files, " + f"please provide init_outputs in the initial_values." + ) + elif graph_data is not None: + content = graph_data + + if content is None: + content = "{}" + + try: + # Parse graph data + graph = json.loads(content) + + # 类型检查 + if not isinstance(graph, dict): + raise TypeError("Graph data must be a dictionary") + + # If graph is not in the expected format, try to extract adjacency list + if "nodes" in graph and "edges" in graph: + # 验证nodes和edges的类型 + if not isinstance(graph["nodes"], list): + raise TypeError("Nodes must be a list") + + if not isinstance(graph["edges"], list): + raise TypeError("Edges must be a list") + + # Convert from nodes/edges format to adjacency list + adjacency_list = {} + for node in graph["nodes"]: + # 验证node类型 + if not isinstance(node, dict): + raise TypeError("Each node must be a dictionary") + + # Use node ID as key, not the entire node dictionary + node_id = node.get("id", "") + if node_id: + adjacency_list[node_id] = {} + + for edge in graph["edges"]: + # 验证edge类型 + if not isinstance(edge, dict): + raise TypeError("Each edge must be a dictionary") + + u = edge["from"] + v = edge["to"] + weight = edge.get("weight", 1) # Default to unweighted + + # 类型检查 + if not isinstance(u, str): + raise TypeError("Edge 'from' must be a string") + + if not isinstance(v, str): + raise TypeError("Edge 'to' must be a string") + + if not isinstance(weight, (int, float)): + raise TypeError("Edge weight must be a number") + + if u not in adjacency_list: + adjacency_list[u] = {} + if v not in adjacency_list: + adjacency_list[v] = {} + + adjacency_list[u][v] = weight + # If undirected, add reverse edge + if not edge.get("directed", False): + adjacency_list[v][u] = weight + elif isinstance(graph, dict): + # Already in adjacency list format + adjacency_list = graph + + # 验证邻接表结构 + for node, neighbors in adjacency_list.items(): + if not isinstance(neighbors, dict): + raise TypeError("Adjacency list must be a dictionary of dictionaries") + + for neighbor, weight in neighbors.items(): + if not isinstance(weight, (int, float)): + raise TypeError("Edge weights must be numbers") + else: + raise TypeError("Graph data must be a dictionary") + + # 检查起点和终点是否为空 + if not start: + raise ValueError("Start node cannot be empty") + + if not end: + raise ValueError("End node cannot be empty") + + # 检查起点和终点是否在图中 + if start not in adjacency_list: + raise ValueError(f"Start node '{start}' not found in graph") + + if end not in adjacency_list: + raise ValueError(f"End node '{end}' not found in graph") + + # Dijkstra's algorithm implementation + import heapq + + # Initialize distances and previous nodes + distances = {node: float('infinity') for node in adjacency_list} + previous = {node: None for node in adjacency_list} + distances[start] = 0 + + # Priority queue + pq = [(0, start)] + heapq.heapify(pq) + + while pq: + current_dist, current_node = heapq.heappop(pq) + + # If we've reached the end node, we can break early + if current_node == end: + break + + # Nodes can be added multiple times to the priority queue, but we only process them once + if current_dist > distances[current_node]: + continue + + # Explore neighbors + for neighbor, weight in adjacency_list[current_node].items(): + distance = current_dist + weight + + # If a shorter path is found + if distance < distances[neighbor]: + distances[neighbor] = distance + previous[neighbor] = current_node + heapq.heappush(pq, (distance, neighbor)) + + # Reconstruct the shortest path + path = [] + current = end + while current is not None: + path.append(current) + current = previous[current] + path.reverse() # Reverse to get from start to end + + # Check if path exists + if not path or path[0] != start: + return {"path": "[]", "cost": 0} + + return { + "path": json.dumps(path), + "cost": distances[end] + } + except json.JSONDecodeError as e: + raise ValueError(f"Invalid JSON in graph data: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in graph_shortest_path: {str(e)}") + + # --- Crypto (Simplified) --- + def crypto_aes_cbc_decrypt(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 (使用模板中定义的参数名) + hex_cipher = inputs.get("hex_cipher") + hex_key = inputs.get("hex_key") + hex_iv = inputs.get("hex_iv") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + + if hex_key is not None and not isinstance(hex_key, str): + raise TypeError("hex_key must be a string") + + if hex_iv is not None and not isinstance(hex_iv, str): + raise TypeError("hex_iv must be a string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + + if hex_key is None: + raise ValueError("hex_key parameter is required") + + if hex_iv is None: + raise ValueError("hex_iv parameter is required") + + from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes + from cryptography.hazmat.backends import default_backend + from cryptography.hazmat.primitives import padding + + try: + # Convert hex strings to bytes + ciphertext = bytes.fromhex(hex_cipher) + key = bytes.fromhex(hex_key) + iv = bytes.fromhex(hex_iv) + + # Validate key length (AES-128, AES-192, AES-256) + if len(key) not in [16, 24, 32]: + raise ValueError("Invalid key length. Must be 16, 24, or 32 bytes.") + + if len(iv) != 16: + raise ValueError("Invalid IV length. Must be 16 bytes.") + + # Create cipher object + cipher = Cipher( + algorithms.AES(key), + modes.CBC(iv), + backend=default_backend() + ) + + decryptor = cipher.decryptor() + + # Decrypt the ciphertext + padded_plaintext = decryptor.update(ciphertext) + decryptor.finalize() + + # Remove PKCS7 padding + unpadder = padding.PKCS7(128).unpadder() + plaintext = unpadder.update(padded_plaintext) + unpadder.finalize() + + # Return decrypted text + return {"text": plaintext.decode('utf-8', errors='ignore')} + except ValueError as e: + if "non-hexadecimal number found in fromhex()" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher, hex_key, or hex_iv") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in crypto_aes_cbc_decrypt: {str(e)}") + + def crypto_rsa_decrypt_hex(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_cipher = inputs.get("hex_cipher") + n = inputs.get("n") + d = inputs.get("d") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + if n is not None and not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + if d is not None and not isinstance(d, (int, str)): + raise TypeError("d must be an integer or string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + if n is None: + raise ValueError("n parameter is required") + if d is None: + raise ValueError("d parameter is required") + + try: + # Convert parameters to appropriate types + cipher_int = int(hex_cipher, 16) + n_int = int(n) if isinstance(n, str) else n + d_int = int(d) if isinstance(d, str) else d + + # RSA decryption: plaintext = ciphertext^d mod n + plaintext_int = pow(cipher_int, d_int, n_int) + + # Convert result to hex and then to text + plaintext_hex = hex(plaintext_int)[2:] + + # Pad with leading zero if odd length + if len(plaintext_hex) % 2 != 0: + plaintext_hex = '0' + plaintext_hex + + # Convert hex to bytes and then to text + try: + plaintext_bytes = bytes.fromhex(plaintext_hex) + plaintext_text = plaintext_bytes.decode('utf-8', errors='ignore') + except: + # If decoding fails, return hex representation + plaintext_text = plaintext_hex + + return {"text": plaintext_text} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in crypto_rsa_decrypt_hex: {str(e)}") + + # --- Others --- + def num_base_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + s = inputs.get("s") + from_base = inputs.get("from_base") + to_base = inputs.get("to_base") + + # 类型检查 - 接受 str 或 int + if s is not None and not isinstance(s, (str, int)): + raise TypeError("s must be a string or integer") + + if from_base is not None and not isinstance(from_base, (int, str)): + raise TypeError("from_base must be an integer") + + if to_base is not None and not isinstance(to_base, (int, str)): + raise TypeError("to_base must be an integer") + + # 检查必需参数 + if s is None: + raise ValueError("s parameter is required") + + if from_base is None: + raise ValueError("from_base parameter is required") + + if to_base is None: + raise ValueError("to_base parameter is required") + + try: + # Convert to int if needed + from_base = int(from_base) if isinstance(from_base, str) else from_base + to_base = int(to_base) if isinstance(to_base, str) else to_base + s_str = str(s) + + # 验证基数范围 + if from_base < 2 or from_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + if to_base < 2 or to_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + # Convert from source base to decimal + val = int(s_str, from_base) + + # Convert from decimal to target base + if to_base == 10: + result = str(val) + elif to_base == 16: + result = hex(val)[2:] + elif to_base == 8: + result = oct(val)[2:] + elif to_base == 2: + result = bin(val)[2:] + else: + # Generic base conversion for other bases + if val == 0: + result = "0" + else: + digits = "0123456789abcdefghijklmnopqrstuvwxyz" + result = "" + n = abs(val) + while n: + result = digits[n % to_base] + result + n //= to_base + if val < 0: + result = "-" + result + + return {"str": result} + except ValueError as e: + raise ValueError(f"Invalid number format: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in num_base_convert: {str(e)}") + + def time_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iso = inputs.get("iso") + timestamp = inputs.get("timestamp") + datetime_str = inputs.get("datetime") + from_tz = inputs.get("from_tz") + to_tz = inputs.get("to_tz") + format_str = inputs.get("format") + + # 类型检查 + if iso is not None and not isinstance(iso, str): + raise TypeError("iso must be a string") + + if timestamp is not None and not isinstance(timestamp, (str, int, float)): + raise TypeError("timestamp must be a string, integer, or float") + + if datetime_str is not None and not isinstance(datetime_str, str): + raise TypeError("datetime must be a string") + + if from_tz is not None and not isinstance(from_tz, str): + raise TypeError("from_tz must be a string") + + if to_tz is not None and not isinstance(to_tz, str): + raise TypeError("to_tz must be a string") + + if format_str is not None and not isinstance(format_str, str): + raise TypeError("format must be a string") + + # 设置默认值 + if from_tz is None: + from_tz = "UTC" + + if to_tz is None: + to_tz = "UTC" + + import datetime + import pytz + + # 验证时区参数 + try: + if from_tz: + pytz.timezone(from_tz) + if to_tz: + pytz.timezone(to_tz) + except Exception: + raise ValueError("Invalid timezone provided") + + try: + # Parse input time + dt = None + + if iso is not None: + # Parse ISO 8601 format + dt = datetime.datetime.fromisoformat(iso.replace('Z', '+00:00')) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=pytz.UTC) + elif timestamp is not None: + # Parse Unix timestamp + timestamp = float(timestamp) + dt = datetime.datetime.fromtimestamp(timestamp, pytz.UTC) + elif datetime_str is not None: + # Parse datetime string + # Try common formats + formats_to_try = [ + "%Y-%m-%d %H:%M:%S", + "%Y-%m-%d %H:%M:%S.%f", + "%Y-%m-%d", + "%m/%d/%Y %H:%M:%S", + "%m/%d/%Y" + ] + + parse_success = False + for fmt in formats_to_try: + try: + dt = datetime.datetime.strptime(datetime_str, fmt) + dt = pytz.timezone(from_tz).localize(dt) + parse_success = True + break + except ValueError: + continue + + if not parse_success: + raise ValueError("Unable to parse datetime string with common formats") + else: + # 如果没有提供任何时间参数,则使用当前时间 + dt = datetime.datetime.now(pytz.UTC) + except ValueError as e: + raise ValueError(f"Error parsing time input: {str(e)}") + except Exception as e: + raise RuntimeError(f"Unexpected error parsing time input: {str(e)}") + + try: + # Convert timezone + if from_tz != to_tz: + dt = dt.astimezone(pytz.timezone(to_tz)) + + # Format outputs + result = { + "iso": dt.isoformat(), + "timestamp": str(dt.timestamp()), + "datetime": dt.strftime("%Y-%m-%d %H:%M:%S"), + "date": dt.strftime("%Y-%m-%d"), + "time": dt.strftime("%H:%M:%S"), + "timezone": to_tz + } + + # Add custom format if requested + if format_str: + try: + result["formatted"] = dt.strftime(format_str) + except ValueError as e: + raise ValueError(f"Invalid format string: {str(e)}") + + return result + except Exception as e: + raise RuntimeError(f"Error in time_convert: {str(e)}") + + def checksum_crc32(self, inputs): + import zlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("hex must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("hex parameter is required") + + try: + # 验证十六进制字符串 + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空 + if not hex_data: + raise ValueError("hex data cannot be empty") + + # 检查是否为有效的十六进制字符串 + if not all(c in "0123456789abcdefABCDEF" for c in hex_data): + raise ValueError("hex must be a valid hexadecimal string") + + # 检查长度是否为偶数 + if len(hex_data) % 2 != 0: + raise ValueError("hex must have even number of characters") + + val = zlib.crc32(bytes.fromhex(hex_data)) + # 确保 hex 输出是 8 位,前导补 0 + return {"hex": f"{val:08x}", "int": val} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in checksum_crc32: {str(e)}") + + def geo_haversine(self, inputs): + import math + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + lat1 = inputs.get("lat1") + lon1 = inputs.get("lon1") + lat2 = inputs.get("lat2") + lon2 = inputs.get("lon2") + + # 类型检查 + if lat1 is not None and not isinstance(lat1, (int, float, str)): + raise TypeError("lat1 must be a number or string") + if lon1 is not None and not isinstance(lon1, (int, float, str)): + raise TypeError("lon1 must be a number or string") + if lat2 is not None and not isinstance(lat2, (int, float, str)): + raise TypeError("lat2 must be a number or string") + if lon2 is not None and not isinstance(lon2, (int, float, str)): + raise TypeError("lon2 must be a number or string") + + # 检查必需参数 + if lat1 is None: + raise ValueError("lat1 parameter is required") + if lon1 is None: + raise ValueError("lon1 parameter is required") + if lat2 is None: + raise ValueError("lat2 parameter is required") + if lon2 is None: + raise ValueError("lon2 parameter is required") + + try: + # 转换为浮点数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(lat1, str): + lat1 = float(lat1) + elif not isinstance(lat1, (int, float)): + raise TypeError("lat1 must be a number or string") + else: + lat1 = float(lat1) + + if isinstance(lon1, str): + lon1 = float(lon1) + elif not isinstance(lon1, (int, float)): + raise TypeError("lon1 must be a number or string") + else: + lon1 = float(lon1) + + if isinstance(lat2, str): + lat2 = float(lat2) + elif not isinstance(lat2, (int, float)): + raise TypeError("lat2 must be a number or string") + else: + lat2 = float(lat2) + + if isinstance(lon2, str): + lon2 = float(lon2) + elif not isinstance(lon2, (int, float)): + raise TypeError("lon2 must be a number or string") + else: + lon2 = float(lon2) + + # Validate coordinates (approximate range check) + if not (-90 <= lat1 <= 90): + raise ValueError("lat1 must be between -90 and 90") + if not (-90 <= lat2 <= 90): + raise ValueError("lat2 must be between -90 and 90") + if not (-180 <= lon1 <= 180): + raise ValueError("lon1 must be between -180 and 180") + if not (-180 <= lon2 <= 180): + raise ValueError("lon2 must be between -180 and 180") + + # Earth radius in meters + R = 6371000 # Approximate radius of Earth + + # Convert degrees to radians + lat1_rad = math.radians(lat1) + lon1_rad = math.radians(lon1) + lat2_rad = math.radians(lat2) + lon2_rad = math.radians(lon2) + + # Calculate differences + delta_lat = lat2_rad - lat1_rad + delta_lon = lon2_rad - lon1_rad + + # Haversine formula + a = math.sin(delta_lat / 2) ** 2 + \ + math.cos(lat1_rad) * math.cos(lat2_rad) * \ + math.sin(delta_lon / 2) ** 2 + c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) + distance_m = R * c + + # Return distance in meters + return {"meters": round(distance_m, 2)} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in geo_haversine: {str(e)}") + + def otp_totp_generate(self, inputs): + import hmac + import hashlib + import base64 + import time + import struct + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + base32_secret = inputs.get("base32_secret") + step = inputs.get("step", 30) # Default to 30 seconds + digits = inputs.get("digits", 6) # Default to 6 digits + timestamp_iso = inputs.get("timestamp_iso", "") + algo = inputs.get("algo", "sha1") # Default to sha1 as current implementation only supports this + + # 类型检查 + if base32_secret is not None and not isinstance(base32_secret, str): + raise TypeError("base32_secret must be a string") + if not isinstance(step, (int, str)): + raise TypeError("step must be an integer or string") + if not isinstance(digits, (int, str)): + raise TypeError("digits must be an integer or string") + if not isinstance(timestamp_iso, str): + raise TypeError("timestamp_iso must be a string") + if not isinstance(algo, str): + raise TypeError("algo must be a string") + + # 检查必需参数 + if base32_secret is None: + raise ValueError("base32_secret parameter is required") + + try: + # Convert step and digits to appropriate types + step = int(step) + digits = int(digits) + if digits < 6 or digits > 8: + raise ValueError("Digits must be between 6 and 8") + + # Convert timestamp_iso to integer timestamp + if timestamp_iso: + import datetime + dt = datetime.datetime.fromisoformat(timestamp_iso.replace('Z', '+00:00')) + timestamp = int(dt.timestamp()) + else: + timestamp = int(time.time()) + + # Calculate counter value (T = floor(timestamp / step)) + counter = timestamp // step + + # Decode the base32 secret + # Add padding if necessary (base64 requires padding to be multiple of 8) + base32_secret = base32_secret.upper().replace(' ', '') + if len(base32_secret) % 8 != 0: + base32_secret += '=' * (8 - (len(base32_secret) % 8)) + key = base64.b32decode(base32_secret, casefold=True) + + # Calculate HMAC-SHA1 + counter_bytes = struct.pack('>Q', counter) # Big-endian 8-byte integer + hmac_hash = hmac.new(key, counter_bytes, hashlib.sha1).digest() + + # Dynamic truncation + offset = hmac_hash[-1] & 0xF + code = struct.unpack('>I', hmac_hash[offset:offset+4])[0] & 0x7FFFFFFF + + # Generate the OTP + otp = str(code % (10 ** digits)).zfill(digits) + + # Calculate remaining time until next OTP change + remaining_time = step - (timestamp % step) + + return {"totp": otp, "remaining_time": remaining_time, "time_step": step} + except ValueError as e: + if "invalid literal for int()" in str(e): + raise ValueError("step and digits must be valid integers") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in otp_totp_generate: {str(e)}") + + def unicode_norm(self, inputs): + import unicodedata + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + form = inputs.get("form", "NFC") # Default to NFC + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if form is not None and not isinstance(form, str): + raise TypeError("form must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Normalize form (NFC, NFD, NFKC, NFKD) + form = form.upper().strip() + + if form not in ['NFC', 'NFD', 'NFKC', 'NFKD']: + raise ValueError(f"Invalid normalization form: {form}. Must be one of: NFC, NFD, NFKC, NFKD") + + # Apply Unicode normalization + normalized_text = unicodedata.normalize(form, text) + + return {"text": normalized_text} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in unicode_norm: {str(e)}") + + def text_bidi_sanitize(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Bidi control characters to remove + bidi_controls = [ + '\u200E', # LEFT-TO-RIGHT MARK + '\u200F', # RIGHT-TO-LEFT MARK + '\u202A', # LEFT-TO-RIGHT EMBEDDING + '\u202B', # RIGHT-TO-LEFT EMBEDDING + '\u202C', # POP DIRECTIONAL FORMATTING + '\u202D', # LEFT-TO-RIGHT OVERRIDE + '\u202E', # RIGHT-TO-LEFT OVERRIDE + '\u2066', # LEFT-TO-RIGHT ISOLATE + '\u2067', # RIGHT-TO-LEFT ISOLATE + '\u2068', # FIRST STRONG ISOLATE + '\u2069', # POP DIRECTIONAL ISOLATE + ] + + # Remove all Bidi control characters + sanitized_text = text + for control_char in bidi_controls: + sanitized_text = sanitized_text.replace(control_char, '') + + return {"text": sanitized_text} + except Exception as e: + raise RuntimeError(f"Error in text_bidi_sanitize: {str(e)}") + + def text_xor_hex(self, inputs): + import binascii + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_a = inputs.get("hex_a") + hex_b = inputs.get("hex_b") + + # 类型检查 + if hex_a is not None and not isinstance(hex_a, str): + raise TypeError("hex_a must be a string") + if hex_b is not None and not isinstance(hex_b, str): + raise TypeError("hex_b must be a string") + + # 检查必需参数 + if hex_a is None: + raise ValueError("hex_a parameter is required") + if hex_b is None: + raise ValueError("hex_b parameter is required") + + try: + # Remove any whitespace + hex_a = hex_a.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + hex_b = hex_b.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + + # Validate hex strings + if not (all(c in "0123456789abcdefABCDEF" for c in hex_a) and len(hex_a) % 2 == 0): + raise ValueError("hex_a must be a valid hexadecimal string with even length") + if not (all(c in "0123456789abcdefABCDEF" for c in hex_b) and len(hex_b) % 2 == 0): + raise ValueError("hex_b must be a valid hexadecimal string with even length") + + # Convert hex strings to bytes + bytes_a = binascii.unhexlify(hex_a) + bytes_b = binascii.unhexlify(hex_b) + + # Make the byte arrays the same length by padding the shorter one with zeros + max_len = max(len(bytes_a), len(bytes_b)) + bytes_a = bytes_a.ljust(max_len, b'\x00') + bytes_b = bytes_b.ljust(max_len, b'\x00') + + # Perform XOR operation + result_bytes = bytes(a ^ b for a, b in zip(bytes_a, bytes_b)) + + # Convert result back to hex + result_hex = binascii.hexlify(result_bytes).decode('utf-8') + + return {"hex": result_hex} + except ValueError as e: + if "Non-hexadecimal digit found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in text_xor_hex: {str(e)}") + + def text_rotN(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + n = inputs.get("n", 0) + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + n = int(n) + except ValueError: + raise ValueError("n must be a valid integer") + + result = [] + for char in text: + if char.isupper(): + # Rotate uppercase letters + result_char = chr((ord(char) - ord('A') + n) % 26 + ord('A')) + result.append(result_char) + elif char.islower(): + # Rotate lowercase letters + result_char = chr((ord(char) - ord('a') + n) % 26 + ord('a')) + result.append(result_char) + else: + # Keep non-alphabetic characters unchanged + result.append(char) + + return {"text": ''.join(result)} + + def luhn_check(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数(支持 card_number 和 number 两个参数名) + card_number = inputs.get("number") or inputs.get("card_number") + + # 类型检查 + if card_number is not None and not isinstance(card_number, str): + raise TypeError("number must be a string") + + # 检查必需参数 + if card_number is None: + raise ValueError("number parameter is required") + + try: + # 如果输入是JSON数组或其他非数字字符串,返回该字符串本身(用于数据传递) + # 这种情况发生在DAG设计中类型不匹配时 + if card_number.startswith('[') or card_number.startswith('{'): + # 输入是JSON,直接返回原值(用于传递) + return {"valid": card_number} + + # Remove whitespace from card number + card_number = card_number.replace(" ", "").replace("-", "") + + # Check if card number is all digits + if not card_number.isdigit() or len(card_number) < 13: + return {"valid": "false"} + + # Implement Luhn algorithm + total = 0 + reverse_digits = card_number[::-1] # Reverse the number for easier processing + + for i, digit in enumerate(reverse_digits): + num = int(digit) + if i % 2 == 1: # Every second digit starting from the right (which is first in reversed string) + num *= 2 + if num > 9: + num -= 9 # Equivalent to sum of digits for 2-digit numbers + total += num + + # Check if total is divisible by 10 + is_valid = total % 10 == 0 + return {"valid": "true" if is_valid else "false"} + except Exception as e: + raise RuntimeError(f"Error in luhn_check: {str(e)}") + + def iban_validate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iban = inputs.get("iban") + + # 类型检查 + if iban is not None and not isinstance(iban, str): + raise TypeError("iban must be a string") + + # 检查必需参数 + if iban is None: + raise ValueError("iban parameter is required") + + try: + # Remove whitespace from IBAN + iban = iban.replace(" ", "") + + # Basic length and format check + if not (len(iban) >= 15 and len(iban) <= 34): + return {"valid": "False"} + + if not (iban[:2].isalpha() and iban[2:].isdigit()): + return {"valid": "False"} + + # Move first four characters to the end + rearranged = iban[4:] + iban[:4] + + # Replace letters with numbers (A=10, B=11, ..., Z=35) + numeric_iban = '' + for char in rearranged: + if char.isdigit(): + numeric_iban += char + else: + numeric_iban += str(ord(char.upper()) - ord('A') + 10) + + # Perform modulo 97 check + # Use step-by-step approach for very large numbers + remainder = 0 + for char in numeric_iban: + remainder = (remainder * 10 + int(char)) % 97 + + is_valid = remainder == 1 + return {"valid": "True" if is_valid else "False"} + except Exception as e: + raise RuntimeError(f"Error in iban_validate: {str(e)}") + + def matter_synthesizer(self, inputs): + import hashlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + blueprint = inputs.get("blueprint") + + # 类型检查 + if blueprint is not None and not isinstance(blueprint, str): + raise TypeError("blueprint must be a string") + + try: + # Get blueprint parameter as defined in interface + if blueprint is None: + blueprint = "" + + # Generate a unique item ID based on the blueprint + # This ensures the same blueprint always produces the same item + blueprint_hash = hashlib.sha256(blueprint.encode()).hexdigest()[:16] + + # Create a synthesized item with a deterministic ID based on blueprint + synthesized_item = f"synthesized_item_{blueprint_hash}" + + return {"output_slot": synthesized_item} + except Exception as e: + raise RuntimeError(f"Error in matter_synthesizer: {str(e)}") + + # --- Terminal Implementations --- + def terminal_1(self, inputs): + """ + terminal_1: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 只返回 text_output + - 只输入正确的 slot_b → 只返回 hex_output + - 同时输入正确的 slot_a 和 slot_b → 返回 item_dispenser(物品掉落) + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + # 检查哪些输入被提供了 + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值是否正确(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + expected_a = golden_inputs["slot_a"] + a_valid = str(slot_a) == str(expected_a) + + if has_b and "slot_b" in golden_inputs: + expected_b = golden_inputs["slot_b"] + b_valid = str(slot_b) == str(expected_b) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 item_dispenser + if has_a and has_b: + if a_valid and b_valid: + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 text_output + if has_a and not has_b: + if a_valid: + if "text_output" in golden_outputs: + result["text_output"] = golden_outputs["text_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 hex_output + if has_b and not has_a: + if b_valid: + if "hex_output" in golden_outputs: + result["hex_output"] = golden_outputs["hex_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def terminal_2(self, inputs): + """ + terminal_2: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 text_result + - 同时输入正确的 num1 和 num2 → 返回 hex_result 和 math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + # 检查哪些输入被提供了 + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值是否正确(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + expected_num1 = golden_inputs["num1"] + num1_valid = str(num1) == str(expected_num1) + + if has_num2 and "num2" in golden_inputs: + expected_num2 = golden_inputs["num2"] + num2_valid = str(num2) == str(expected_num2) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 hex_result 和 math_token + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 text_result + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "text_result" in golden_outputs: + result["text_result"] = golden_outputs["text_result"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def logic_terminal(self, inputs): + """ + Logic Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 返回 screen(部分输出) + - 只输入正确的 slot_b → 返回 screen 和 secondary_output + - 同时输入正确的 slot_a 和 slot_b → 返回 screen, secondary_output, item_dispenser + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + a_valid = str(slot_a) == str(golden_inputs["slot_a"]) + + if has_b and "slot_b" in golden_inputs: + b_valid = str(slot_b) == str(golden_inputs["slot_b"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出(包括 item_dispenser) + if has_a and has_b: + if a_valid and b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 screen(部分输出) + if has_a and not has_b: + if a_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 screen 和 secondary_output + if has_b and not has_a: + if b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def math_terminal(self, inputs): + """ + Math Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 result_display + - 同时输入正确的 num1 和 num2 → 返回 result_display, hex_result, math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + num1_valid = str(num1) == str(golden_inputs["num1"]) + + if has_num2 and "num2" in golden_inputs: + num2_valid = str(num2) == str(golden_inputs["num2"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 result_display + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def crypt_terminal(self, inputs): + """ + Encryption Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 plaintext → 返回 status(部分输出) + - 同时输入正确的 plaintext 和 key → 返回 status, encrypted_hex, encryption_chip + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + plaintext = inputs.get("plaintext") + key = inputs.get("key") + + has_plaintext = plaintext is not None and plaintext != "" + has_key = key is not None and key != "" + + # 验证输入值(与 golden values 比较) + plaintext_valid = False + key_valid = False + + if has_plaintext and "plaintext" in golden_inputs: + plaintext_valid = str(plaintext) == str(golden_inputs["plaintext"]) + + if has_key and "key" in golden_inputs: + key_valid = str(key) == str(golden_inputs["key"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_plaintext and has_key: + if plaintext_valid and key_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + if "encrypted_hex" in golden_outputs: + result["encrypted_hex"] = golden_outputs["encrypted_hex"] + if "encryption_chip" in golden_outputs: + result["encryption_chip"] = golden_outputs["encryption_chip"] + return result + else: + incorrect_params = [] + correct_params = [] + if not plaintext_valid: + incorrect_params.append("plaintext") + else: + correct_params.append("plaintext") + if not key_valid: + incorrect_params.append("key") + else: + correct_params.append("key") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 plaintext 且正确 → 返回 status(部分输出) + if has_plaintext and not has_key: + if plaintext_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: plaintext"} + + # 只提供 key 但没有 plaintext + if has_key and not has_plaintext: + return {"error": "plaintext required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + def sequence_terminal(self, inputs): + """ + Sequence Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 sequence → 返回 verification(部分输出) + - 同时输入正确的 sequence 和 checksum → 返回 verification, auth_code, access_card + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + sequence = inputs.get("sequence") + checksum = inputs.get("checksum") + + has_sequence = sequence is not None and sequence != "" + has_checksum = checksum is not None and checksum != "" + + # 验证输入值(与 golden values 比较) + sequence_valid = False + checksum_valid = False + + if has_sequence and "sequence" in golden_inputs: + sequence_valid = str(sequence) == str(golden_inputs["sequence"]) + + if has_checksum and "checksum" in golden_inputs: + checksum_valid = str(checksum) == str(golden_inputs["checksum"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_sequence and has_checksum: + if sequence_valid and checksum_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + if "auth_code" in golden_outputs: + result["auth_code"] = golden_outputs["auth_code"] + if "access_card" in golden_outputs: + result["access_card"] = golden_outputs["access_card"] + return result + else: + incorrect_params = [] + correct_params = [] + if not sequence_valid: + incorrect_params.append("sequence") + else: + correct_params.append("sequence") + if not checksum_valid: + incorrect_params.append("checksum") + else: + correct_params.append("checksum") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 sequence 且正确 → 返回 verification(部分输出) + if has_sequence and not has_checksum: + if sequence_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: sequence"} + + # 只提供 checksum 但没有 sequence + if has_checksum and not has_sequence: + return {"error": "sequence required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + # --- Additional File Tools --- + + def zip_unzip_file(self, inputs): + """ZIP 解压文件工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def zip_unzip_item(self, inputs): + """ZIP 解压道具工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def code_py_exec(self, inputs): + """Python 代码执行工具 + + 这是一个真实执行的工具,在 DAG 生成阶段和运行时评测阶段都会执行代码。 + 输入: code (Python 代码字符串) + 输出: stdout (标准输出,包含执行结果和错误信息) + + 特殊行为: + - 如果代码定义了 main() 函数,会自动调用它 + - 如果执行出错,错误信息会包含在 stdout 中 + """ + code = inputs.get("code", "") + + if not code: + return {"stdout": "Error: No code provided"} + + try: + # 创建一个受限的执行环境 + import io + import sys + + # 捕获标准输出和标准错误 + old_stdout = sys.stdout + old_stderr = sys.stderr + sys.stdout = io.StringIO() + sys.stderr = io.StringIO() + + # 执行代码 + exec_globals = {"__builtins__": __builtins__} + exec_locals = {} + exec(code, exec_globals, exec_locals) + + # 如果定义了 main() 函数,自动调用它 + if 'main' in exec_locals and callable(exec_locals['main']): + exec_locals['main']() + + # 获取输出 + stdout_value = sys.stdout.getvalue() + stderr_value = sys.stderr.getvalue() + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 合并 stdout 和 stderr + output = stdout_value + if stderr_value: + output += ("\n" if output else "") + f"[stderr] {stderr_value}" + + # 如果没有任何输出,尝试返回 result 变量的值 + if not output: + result = exec_locals.get("_result") or exec_locals.get("result") + if result is not None: + output = str(result) + + return {"stdout": output if output else "(no output)"} + + except Exception as e: + # 恢复标准输出和错误输出 + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 返回错误信息 + return {"stdout": f"Error: {type(e).__name__}: {str(e)}"} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-c32db50f/environment/puzzle/worker.Dockerfile b/tasks/agentescape-25-skeleton-c32db50f/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-25-skeleton-c32db50f/environment/puzzle/worker.Dockerfile @@ -0,0 +1,8 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends libseccomp2 && rm -rf /var/lib/apt/lists/* +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY worker.py child.py /app/ +COPY upstream/simulator.py /app/simulator.py +CMD ["uvicorn", "worker:app", "--host", "0.0.0.0", "--port", "8001", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-25-skeleton-c32db50f/environment/puzzle/worker.py b/tasks/agentescape-25-skeleton-c32db50f/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-25-skeleton-c32db50f/environment/puzzle/worker.py @@ -0,0 +1,73 @@ +"""Stateless Python tool worker. Never receives a scenario or reference values.""" + +import json +import os +import signal +import subprocess +import sys +import tempfile +import threading + +from fastapi import FastAPI +from pydantic import BaseModel, ConfigDict + +app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) +lock = threading.Lock() + + +class Execution(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + code: str + + +@app.get("/health") +def health(): + return {"ok": True} + + +@app.post("/execute") +def execute(request: Execution): + if len(request.code.encode()) > 65536: + return {"stdout": "Error: code exceeds 64 KiB limit"} + with lock, tempfile.TemporaryDirectory(prefix="escape-code-") as directory: + os.chown(directory, 65534, 65534) + with tempfile.TemporaryFile() as output: + process = subprocess.Popen( + [sys.executable, "-I", "/app/child.py"], + stdin=subprocess.PIPE, + stdout=output, + stderr=subprocess.DEVNULL, + cwd=directory, + user=65534, + group=65534, + extra_groups=[], + start_new_session=True, + env={"PATH": "/usr/local/bin:/usr/bin:/bin"}, + ) + try: + process.communicate( + json.dumps({"code": request.code}).encode(), timeout=5 + ) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + return {"stdout": "Error: Python execution timed out"} + finally: + # Also remove children still in the process group after normal exit. + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + output.seek(0) + value = output.read(65537) + if len(value) > 65536 or process.returncode != 0: + return { + "stdout": "Error: Python execution exceeded a resource limit or failed" + } + try: + result = json.loads(value) + if not isinstance(result.get("stdout"), str): + raise ValueError("Invalid worker response") + return result + except (ValueError, AttributeError): + return {"stdout": "Error: Python execution returned invalid output"} diff --git a/tasks/agentescape-25-skeleton-c32db50f/instruction.md b/tasks/agentescape-25-skeleton-c32db50f/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-25-skeleton-c32db50f/instruction.md @@ -0,0 +1,18 @@ +# Escape the room + +Discover the victory string and submit it with `escape submit-answer`. +Start with `escape observe`. This returns the room, available information, visible entities, and victory node ID. + +Use these commands (JSON responses): + +```sh +escape investigate NODE_ID +escape tool-call NODE_ID --arguments-json '{"parameter": "value"}' +escape use-item NODE_ID --arguments-json '{"parameter": "value"}' +escape submit-answer 'exact victory string' +escape state +``` + +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. + +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. diff --git a/tasks/agentescape-25-skeleton-c32db50f/solution/oracle.py b/tasks/agentescape-25-skeleton-c32db50f/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-25-skeleton-c32db50f/solution/oracle.py @@ -0,0 +1,133 @@ +"""Reference solver: use trusted inputs, but obtain the answer through public actions.""" + +import json +import urllib.request +from pathlib import Path + + +def http_action(base_url, payload): + request = urllib.request.Request( + base_url + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(request, timeout=30) as response: + return json.load(response) + + +def solve(scenario, act, observe): + nodes = {node["id"]: node for node in scenario["nodes"]} + visible = {entity["id"] for entity in observe["available_entities"]} + solved = set() + seen_outputs = {} + action_count = 0 + + def call(payload): + nonlocal action_count + action_count += 1 + response = act(payload) + visible.update(entity["id"] for entity in response.get("newly_revealed", [])) + if ( + response.get("episode", {}).get("termination_reason") + == "infrastructure_error" + ): + raise RuntimeError("Infrastructure failure") + return response + + for _round in range(len(nodes) + 2): + progress = False + for node_id, node in nodes.items(): + if node_id not in visible or node_id in solved: + continue + # Preserve graph order for data inputs; trigger/drop edges express visibility. + predecessors = [ + edge["source_id"] + for edge in scenario["edges"] + if edge["target_id"] == node_id + and edge["connection_type"] not in ("Item", "Hidden_Item") + ] + if any(pred not in solved for pred in predecessors): + continue + info = call({"action": "investigate", "node_id": node_id}) + if not info.get("ok"): + raise RuntimeError(f"Investigation failed: {node_id}: {info}") + inputs = { + port["name"]: port["value"] + for port in node.get("inputs", []) + if "value" in port + } + if node["type"] == "Tool": + result = call( + {"action": "tool_call", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok") or result.get("output_values", {}).get("error"): + raise RuntimeError(f"Tool failed: {node_id}: {result}") + output = result.get("output_values", {}) + if node.get("template_id") in ("terminal_1", "terminal_2"): + slots = { + port["name"]: inputs[port["name"]] + for port in node["inputs"] + if port["type"] not in ("Item", "Hidden_Item") + and port["name"] in inputs + } + triggers = { + key: value for key, value in inputs.items() if key not in slots + } + for key, value in slots.items(): + partial = call( + { + "action": "tool_call", + "node_id": node_id, + "arguments": {**triggers, key: value}, + } + ) + if partial.get("ok"): + output.update(partial.get("output_values", {})) + # HIDDEN_ITEM tool drops only occur on subsequent investigation. + call({"action": "investigate", "node_id": node_id}) + elif info.get("required_inputs"): + result = call( + {"action": "use_item", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok"): + raise RuntimeError(f"Item failed: {node_id}: {result}") + output = result.get("content") + else: + output = info.get("content") + seen_outputs[node_id] = output + solved.add(node_id) + progress = True + win_id = scenario["metadata"]["win_node_id"] + if win_id in solved and (len(solved) == len(nodes) or not progress): + outputs = seen_outputs[win_id] + if not outputs: + raise RuntimeError(f"Victory node returned no output: {win_id}") + # Upstream grades its first stored output port, independent of response order. + victory_port = next( + port["name"] for port in nodes[win_id]["outputs"] if "value" in port + ) + answer = outputs[victory_port] if isinstance(outputs, dict) else outputs + result = call({"action": "submit_answer", "answer": answer}) + if not result.get("is_win"): + raise RuntimeError(f"Victory submission failed: {result}") + return {"won": True, "actions": action_count, "visited_nodes": len(solved)} + if not progress: + raise RuntimeError(f"No progress: visible={visible}, solved={solved}") + raise RuntimeError("Reference solver exceeded graph traversal limit") + + +if __name__ == "__main__": + import os + + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000") + with urllib.request.urlopen(base + "/observation", timeout=20) as response: + observation = json.load(response) + print( + json.dumps( + solve( + json.loads(Path("/solution/scenario.json").read_text()), + lambda payload: http_action(base, payload), + observation, + ) + ) + ) diff --git a/tasks/agentescape-25-skeleton-c32db50f/solution/scenario.json b/tasks/agentescape-25-skeleton-c32db50f/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..edab98ab062da1aa97ba57f45708ef372d6a29c2 --- /dev/null +++ b/tasks/agentescape-25-skeleton-c32db50f/solution/scenario.json @@ -0,0 +1,1380 @@ +{ + "metadata": { + "total_nodes": 25, + "total_edges": 29, + "win_node_id": "item_7", + "win_condition": { + "type": "item_content", + "node_id": "item_7", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_7", + "hmac_sha256", + "container_2", + "calc_modexp", + "graph_shortest_path", + "zip_unzip_file", + "crypto_rsa_decrypt_hex", + "graph_shortest_path_53ed", + "calc_bigmul_0ba9", + "checksum_crc32_6747", + "container_4_d115", + "hex_decode" + ], + "by_node": { + "item_7": { + "node_name": "", + "node_type": "Item", + "template_id": "item_7", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Code_Python", + "description": "The integer" + } + } + }, + "hmac_sha256": { + "node_name": "HMAC-SHA256 Calculator", + "node_type": "Tool", + "template_id": "hmac_sha256", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text message" + } + }, + "init_outputs": {} + }, + "container_2": { + "node_name": "", + "node_type": "Item", + "template_id": "container_2", + "init_inputs": { + "fingerprint_input": { + "type": "Hex_String", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + }, + "calc_modexp": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "base": { + "type": "Big_Int", + "description": "Base" + }, + "exp": { + "type": "Big_Int", + "description": "Exponent" + } + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "dst": { + "type": "Text_Generic", + "description": "Destination node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + }, + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "crypto_rsa_decrypt_hex": { + "node_name": "RSA Decrypt", + "node_type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "init_inputs": { + "n": { + "type": "Big_Int", + "description": "Modulus n" + }, + "d": { + "type": "Big_Int", + "description": "Private exponent d" + } + }, + "init_outputs": {} + }, + "graph_shortest_path_53ed": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "Graph JSON file ID" + }, + "dst": { + "type": "Text_Generic", + "description": "Destination node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "calc_bigmul_0ba9": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "b": { + "type": "Big_Int", + "description": "Second large integer" + } + }, + "init_outputs": {} + }, + "checksum_crc32_6747": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + }, + "container_4_d115": { + "node_name": "", + "node_type": "Item", + "template_id": "container_4", + "init_inputs": { + "fingerprint_input": { + "type": "Text_Generic", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + }, + "hex_decode": { + "node_name": "Hex to Text Decoder", + "node_type": "Tool", + "template_id": "hex_decode", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex string" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "item_7": { + "init_inputs": {}, + "init_outputs": { + "content": "def get_secret_integer():\n return 420918237" + } + }, + "hmac_sha256": { + "init_inputs": { + "text": "Critical system validation message for HMAC computation" + }, + "init_outputs": {} + }, + "container_2": { + "init_inputs": { + "fingerprint_input": "a1b2c3d4e5f67890a1b2c3d4e5f67890" + }, + "init_outputs": {} + }, + "calc_modexp": { + "init_inputs": { + "base": "32", + "exp": "83948572638194758264" + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": { + "dst": "Node_Omega" + }, + "init_outputs": { + "path": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\", \"Node_Omega\"]", + "cost": "450210" + } + }, + "zip_unzip_file": { + "init_inputs": { + "zip_id": "archive_data_77.zip", + "password": "secure_pass_123" + }, + "init_outputs": { + "files": "extracted_payload_99.csv" + } + }, + "crypto_rsa_decrypt_hex": { + "init_inputs": { + "n": "94857263819475826473928174", + "d": "48572638194758264739281745" + }, + "init_outputs": {} + }, + "graph_shortest_path_53ed": { + "init_inputs": { + "file_id": "network_graph_82.json", + "dst": "Server_Final" + }, + "init_outputs": { + "path": "[\"Gateway\", \"Router_1\", \"Switch_A\", \"Firewall\", \"Load_Balancer\", \"Server_Final\"]", + "cost": "889312" + } + }, + "calc_bigmul_0ba9": { + "init_inputs": { + "b": "182736455463728192039485" + }, + "init_outputs": {} + }, + "checksum_crc32_6747": { + "init_inputs": { + "hex": "aabbccddeeff112233445566" + }, + "init_outputs": {} + }, + "container_4_d115": { + "init_inputs": { + "fingerprint_input": "unique_fingerprint_hash_string_99" + }, + "init_outputs": {} + }, + "hex_decode": { + "init_inputs": { + "hex": "48656c6c6f20576f726c6421204465636f6465206d65" + }, + "init_outputs": {} + } + }, + "intro_narrative": "Welcome to Sector 7, a forgotten slice of the mega-city where neon lights flicker over rain-slicked concrete. You are a rogue data-runner, and your target is hidden deep within an abandoned corporate safehouse. The megacorp locked down the Mainframe Data Core before evacuating, leaving behind a complex web of encrypted terminals, dead-drop safes, and fragmented data nodes. Your objective is to navigate this digital and physical labyrinth. You must scavenge for override keys, reactivate dormant signal decoders, and daisy-chain their outputs to bypass the heavy biometric locks. Time is ticking, and the automated corporate sweepers are on their way. Trace the data flow, unlock the core, and get out alive.", + "narrative_style": "cyberpunk" + }, + "nodes": [ + { + "id": "item_7", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_7", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Code_Python", + "description": "The integer", + "value": "def get_secret_integer():\n return 420918237" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "def get_secret_integer():\n return 420918237" + } + }, + "narrative": "The Mainframe Data Core. A glowing cybernetic brain holding the megacorp's darkest secrets." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "The Server Access Key. A metallic card with embedded microchips, essential for breaching secure hardware." + }, + { + "id": "container_3", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_3", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Big_Int", + "description": "Fingerprint Hash", + "value": "491214545225405594951055748019336464562276517129141852934074007632534460515273586974720" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is the Master Override Safe. It requires input from the Universal Translator to disengage its heavy locks." + }, + { + "id": "num_base_convert", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "491214545225405594951055748019336464562276517129141852934074007632534460515273586974720" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": 3478258514 + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": 3457857673 + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "491214545225405594951055748019336464562276517129141852934074007632534460515273586974720" + } + ], + "narrative": "This is the Universal Translator. It requires input from the Quantum Processor, the Primary Validator, and the Secondary Validator." + }, + { + "id": "item_16_f971", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A battered Maintenance Keycard, dropped by a panicked technician during the evacuation." + }, + { + "id": "calc_bigmul", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "1221368412905438059919937305852380583166914236544" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "402183763748143429283021565875961314880" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "491214545225405594951055748019336464562276517129141852934074007632534460515273586974720" + } + ], + "narrative": "This is the Quantum Processor. It requires input from the Neural Synthesizer and the Logic Multiplier." + }, + { + "id": "checksum_crc32", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "e3cb1f24d2fe9c0c3f2baf2d291a21dcc0bcd82cd8ab140658400c21c62a7d02" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "cf520352" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3478258514 + } + ], + "narrative": "This is the Primary Validator. It requires input from the Security Authenticator." + }, + { + "id": "calc_bigmul_d486", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "351143656513576224633640702949884472896" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": 3478258514 + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "1221368412905438059919937305852380583166914236544" + } + ], + "narrative": "This is the Neural Synthesizer. It requires input from the Power Calibrator and the Primary Validator." + }, + { + "id": "checksum_crc32_b2b3", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "cf520352" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "ce1ab889" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3457857673 + } + ], + "narrative": "This is the Secondary Validator. It requires input from the Primary Validator." + }, + { + "id": "calc_bigmul_2fdb", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "452241467278236917170825948458990" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "889312" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "402183763748143429283021565875961314880" + } + ], + "narrative": "This is the Logic Multiplier. It requires input from the Network Router and the Signal Amplifier." + }, + { + "id": "hmac_sha256", + "name": "HMAC-SHA256 Calculator", + "description": "HMAC-SHA256(text) with hex key.", + "type": "Tool", + "template_id": "hmac_sha256", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex_key", + "type": "Hex_String", + "description": "Hex key", + "value": "68ba5578967a1daa1b73eea8fe205b6fbf6e03d580d239c945a5d204acf89ad7" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text message", + "value": "Critical system validation message for HMAC computation" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "HMAC Hex digest", + "value": "e3cb1f24d2fe9c0c3f2baf2d291a21dcc0bcd82cd8ab140658400c21c62a7d02" + } + ], + "init": { + "inputs": { + "text": "Critical system validation message for HMAC computation" + }, + "outputs": {} + }, + "narrative": "This is the Security Authenticator. It requires input from the Digital Scrambler to verify biometric traces." + }, + { + "id": "container_2", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_2", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Hex_String", + "description": "Fingerprint Hash", + "value": "a1b2c3d4e5f67890a1b2c3d4e5f67890" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "a1b2c3d4e5f67890a1b2c3d4e5f67890" + }, + "outputs": {} + }, + "narrative": "A Biometric Locker used by corporate security. It is covered in neon graffiti and reinforced steel." + }, + { + "id": "calc_modexp", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "32" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "83948572638194758264" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "402183763748143429283021565875961314880" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "351143656513576224633640702949884472896" + } + ], + "init": { + "inputs": { + "base": "32", + "exp": "83948572638194758264" + }, + "outputs": {} + }, + "narrative": "This is the Power Calibrator. It requires input from the Logic Multiplier to stabilize the grid." + }, + { + "id": "hash_sha256", + "name": "SHA-256 Hasher", + "description": "SHA-256 over UTF-8 text; returns hex.", + "type": "Tool", + "template_id": "hash_sha256", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Text to hash", + "value": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\", \"Node_Omega\"]" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "SHA-256 Hex digest", + "value": "68ba5578967a1daa1b73eea8fe205b6fbf6e03d580d239c945a5d204acf89ad7" + } + ], + "narrative": "This is the Digital Scrambler. It requires input from the Traffic Analyzer to mask your signal." + }, + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "extracted_payload_99.csv" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "[\"Gateway\", \"Router_1\", \"Switch_A\", \"Firewall\", \"Load_Balancer\", \"Server_Final\"]" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Node_Omega" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\", \"Node_Omega\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "450210" + } + ], + "init": { + "inputs": { + "dst": "Node_Omega" + }, + "outputs": { + "path": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\", \"Node_Omega\"]", + "cost": "450210" + } + }, + "narrative": "This is the Traffic Analyzer. It requires input from the Data Extractor and the Network Router." + }, + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "archive_data_77.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "secure_pass_123" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_payload_99.csv" + } + ], + "init": { + "inputs": { + "zip_id": "archive_data_77.zip", + "password": "secure_pass_123" + }, + "outputs": { + "files": "extracted_payload_99.csv" + } + }, + "narrative": "The Data Extractor. An old software terminal left behind by underground hackers." + }, + { + "id": "container_4", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_4", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Text_Generic", + "description": "Fingerprint Hash", + "value": "D\u0012\u0017\u001d^sz6" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is the Evidence Lockbox. It requires input from the Cipher Decoder to bypass its electronic seal." + }, + { + "id": "crypto_rsa_decrypt_hex", + "name": "RSA Decrypt", + "description": "RSA decrypt (hex cipher) with n,d (decimal).", + "type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex_cipher", + "type": "Hex_String", + "description": "Ciphertext (Hex)", + "value": "9382e486" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Modulus n", + "value": "94857263819475826473928174" + }, + { + "name": "d", + "type": "Big_Int", + "description": "Private exponent d", + "value": "48572638194758264739281745" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decrypted text", + "value": "D\u0012\u0017\u001d^sz6" + } + ], + "init": { + "inputs": { + "n": "94857263819475826473928174", + "d": "48572638194758264739281745" + }, + "outputs": {} + }, + "narrative": "This is the Cipher Decoder. It requires input from the Node Verifier." + }, + { + "id": "graph_shortest_path_53ed", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "network_graph_82.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Hello World! Decode me" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Server_Final" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Gateway\", \"Router_1\", \"Switch_A\", \"Firewall\", \"Load_Balancer\", \"Server_Final\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "889312" + } + ], + "init": { + "inputs": { + "file_id": "network_graph_82.json", + "dst": "Server_Final" + }, + "outputs": { + "path": "[\"Gateway\", \"Router_1\", \"Switch_A\", \"Firewall\", \"Load_Balancer\", \"Server_Final\"]", + "cost": "889312" + } + }, + "narrative": "This is the Network Router. It requires input from the Signal Decoder to route the encrypted pathways." + }, + { + "id": "calc_bigmul_0ba9", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": 2474828934 + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "182736455463728192039485" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "452241467278236917170825948458990" + } + ], + "init": { + "inputs": { + "b": "182736455463728192039485" + }, + "outputs": {} + }, + "narrative": "This is the Signal Amplifier. It requires input from the Node Verifier." + }, + { + "id": "item_16_4531", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "The Sector Badge. A vital piece of identification for navigating this forgotten neon district." + }, + { + "id": "checksum_crc32_6747", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "aabbccddeeff112233445566" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "9382e486" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 2474828934 + } + ], + "init": { + "inputs": { + "hex": "aabbccddeeff112233445566" + }, + "outputs": {} + }, + "narrative": "The Node Verifier. A standalone diagnostic terminal from the old era." + }, + { + "id": "container_4_d115", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_4", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Text_Generic", + "description": "Fingerprint Hash", + "value": "unique_fingerprint_hash_string_99" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "unique_fingerprint_hash_string_99" + }, + "outputs": {} + }, + "narrative": "A heavy Tool Box covered in grease and glowing wire scraps. Standard issue for street mechanics." + }, + { + "id": "item_16_9fc2", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A high-level Clearance Tag with a cracked holographic display." + }, + { + "id": "hex_decode", + "name": "Hex to Text Decoder", + "description": "Decode hex to UTF-8 text.", + "type": "Tool", + "template_id": "hex_decode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex string", + "value": "48656c6c6f20576f726c6421204465636f6465206d65" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decoded text", + "value": "Hello World! Decode me" + } + ], + "init": { + "inputs": { + "hex": "48656c6c6f20576f726c6421204465636f6465206d65" + }, + "outputs": {} + }, + "narrative": "The Signal Decoder. A rusted but functional black market terminal hooked up to a jury-rigged antenna." + } + ], + "edges": [ + { + "source_id": "item_16", + "target_id": "item_7", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "container_3", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "num_base_convert", + "target_id": "container_3", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "fingerprint_input" + }, + { + "source_id": "item_16_f971", + "target_id": "container_3", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "calc_bigmul", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "s" + }, + { + "source_id": "checksum_crc32", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "from_base" + }, + { + "source_id": "calc_bigmul_d486", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "a" + }, + { + "source_id": "checksum_crc32_b2b3", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "to_base" + }, + { + "source_id": "checksum_crc32", + "target_id": "checksum_crc32_b2b3", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "calc_bigmul_2fdb", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "b" + }, + { + "source_id": "hmac_sha256", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "container_2", + "target_id": "item_16_f971", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "calc_modexp", + "target_id": "calc_bigmul_d486", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "a" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_bigmul_d486", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "b" + }, + { + "source_id": "calc_bigmul_2fdb", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "mod" + }, + { + "source_id": "hash_sha256", + "target_id": "hmac_sha256", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_key" + }, + { + "source_id": "graph_shortest_path", + "target_id": "hash_sha256", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "text" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "container_4", + "target_id": "zip_unzip_file", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "crypto_rsa_decrypt_hex", + "target_id": "container_4", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "fingerprint_input" + }, + { + "source_id": "graph_shortest_path_53ed", + "target_id": "calc_bigmul_2fdb", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "b" + }, + { + "source_id": "graph_shortest_path_53ed", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "src" + }, + { + "source_id": "calc_bigmul_0ba9", + "target_id": "calc_bigmul_2fdb", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "a" + }, + { + "source_id": "item_16_4531", + "target_id": "container_2", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "checksum_crc32_6747", + "target_id": "calc_bigmul_0ba9", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "a" + }, + { + "source_id": "checksum_crc32_6747", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_cipher" + }, + { + "source_id": "container_4_d115", + "target_id": "item_16_4531", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "item_16_9fc2", + "target_id": "container_4_d115", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "hex_decode", + "target_id": "graph_shortest_path_53ed", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "src" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-c32db50f/solution/solve.sh b/tasks/agentescape-25-skeleton-c32db50f/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-25-skeleton-c32db50f/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-25-skeleton-c32db50f/task.toml b/tasks/agentescape-25-skeleton-c32db50f/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..88abbab012d51a95bbd7164a4dae955166eb7d8a --- /dev/null +++ b/tasks/agentescape-25-skeleton-c32db50f/task.toml @@ -0,0 +1,38 @@ +schema_version = "1.4" +source = "https://github.com/AGI-Eval-Official/Repo-of-AgentEscapeBench" + +[[artifacts]] +source = "/evidence/final.json" +service = "puzzle" + +[[artifacts]] +source = "/evidence/trace.jsonl" +service = "puzzle" + +[task] +name = "edbeeching/agentescape-25-skeleton-c32db50f" +version = "0.1.0" + +[metadata] +difficulty = 25 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "deee4d539ad75a7a79d840c3774af094bb92eaec1d2f33d6f0fdc349a767eb2c" +protocol = "harbor-cli-action-budget-v1" +max_actions = 500 + +[agent] +timeout_sec = 1200 + +[environment] +build_timeout_sec = 900 +cpus = 1 +memory_mb = 1024 + +[verifier] +environment_mode = "separate" +timeout_sec = 60 + +[[verifier.collect]] +service = "puzzle" +command = "python -I /app/export.py" +timeout_sec = 15 diff --git a/tasks/agentescape-25-skeleton-c32db50f/tests/Dockerfile b/tasks/agentescape-25-skeleton-c32db50f/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-25-skeleton-c32db50f/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-25-skeleton-c32db50f/tests/expected.json b/tasks/agentescape-25-skeleton-c32db50f/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..b4a60a7b76df7802346dca7dedd8501c51904a3b --- /dev/null +++ b/tasks/agentescape-25-skeleton-c32db50f/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "deee4d539ad75a7a79d840c3774af094bb92eaec1d2f33d6f0fdc349a767eb2c", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-c32db50f/tests/grade.py b/tasks/agentescape-25-skeleton-c32db50f/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-25-skeleton-c32db50f/tests/grade.py @@ -0,0 +1,21 @@ +"""Grade only Harbor-collected sidecar evidence in a fresh verifier container.""" + +import json +from pathlib import Path + +expected = json.loads(Path("/tests/expected.json").read_text()) +state = json.loads(Path("/evidence/final.json").read_text()) +assert state["collected_from_live_service"] is True, "Missing trusted service export" +assert state["scenario_sha256"] == expected["scenario_sha256"], ( + "Wrong scenario evidence" +) +assert state["max_actions"] == expected["max_actions"], "Wrong budget" +assert type(state["won"]) is bool +assert 0 <= state["action_count"] <= state["max_actions"] +assert state["termination_reason"] != "infrastructure_error", ( + "Infrastructure failure is not a puzzle failure" +) +assert not state["won"] or state["termination_reason"] == "success" +Path("/logs/verifier").mkdir(parents=True, exist_ok=True) +Path("/logs/verifier/state.json").write_text(json.dumps(state, indent=2)) +Path("/logs/verifier/reward.txt").write_text("1.0\n" if state["won"] else "0.0\n") diff --git a/tasks/agentescape-25-skeleton-c32db50f/tests/test.sh b/tasks/agentescape-25-skeleton-c32db50f/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-25-skeleton-c32db50f/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-25-skeleton-c520de06/environment/Dockerfile b/tasks/agentescape-25-skeleton-c520de06/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-25-skeleton-c520de06/environment/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-25-skeleton-c520de06/environment/agent/Dockerfile b/tasks/agentescape-25-skeleton-c520de06/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-25-skeleton-c520de06/environment/agent/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-25-skeleton-c520de06/environment/agent/cli.py b/tasks/agentescape-25-skeleton-c520de06/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-25-skeleton-c520de06/environment/agent/cli.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Public agent client; depends only on the Python standard library.""" + +import argparse +import json +import os +import sys +import urllib.error +import urllib.request + + +def main(): + parser = argparse.ArgumentParser(description="Interact with the escape room") + parser.add_argument( + "action", + choices=[ + "observe", + "state", + "investigate", + "tool-call", + "use-item", + "submit-answer", + ], + ) + parser.add_argument("value", nargs="?") + parser.add_argument("--arguments-json", default="{}") + args = parser.parse_args() + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000").rstrip("/") + if args.action in ("observe", "state"): + request = urllib.request.Request( + base + ("/observation" if args.action == "observe" else "/state") + ) + else: + if args.value is None: + parser.error("node ID or answer is required") + payload = {"action": args.action.replace("-", "_")} + if args.action == "submit-answer": + payload["answer"] = args.value + else: + payload["node_id"] = args.value + if args.action in ("tool-call", "use-item"): + payload["arguments"] = json.loads(args.arguments_json) + request = urllib.request.Request( + base + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=30) as response: + print(json.dumps(json.load(response), ensure_ascii=False)) + except (urllib.error.URLError, ValueError) as exc: + print(json.dumps({"ok": False, "error": str(exc)})) + sys.exit(2) + + +if __name__ == "__main__": + main() diff --git a/tasks/agentescape-25-skeleton-c520de06/environment/docker-compose.yaml b/tasks/agentescape-25-skeleton-c520de06/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..755ead14ba2403295ae224ebac875aa839b1acbd --- /dev/null +++ b/tasks/agentescape-25-skeleton-c520de06/environment/docker-compose.yaml @@ -0,0 +1,50 @@ +services: + main: + image: agentescapebench-agent:aab05a0a9ddb + build: + context: ./agent + networks: [default, puzzle] + security_opt: [no-new-privileges:true] + depends_on: + puzzle: + condition: service_healthy + puzzle: + image: agentescapebench-puzzle:agentescape-25-skeleton-c520de06-aab05a0a9ddb + build: + context: ./puzzle + networks: [puzzle, execution] + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 512m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"] + interval: 1s + timeout: 3s + retries: 30 + depends_on: + worker: + condition: service_healthy + worker: + image: agentescapebench-worker:aab05a0a9ddb + build: + context: ./puzzle + dockerfile: worker.Dockerfile + networks: [execution] + read_only: true + tmpfs: ["/tmp:size=64m,mode=1777"] + cap_drop: [ALL] + cap_add: [SETUID, SETGID, KILL, CHOWN, DAC_OVERRIDE] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 384m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8001/health')"] + interval: 1s + timeout: 3s + retries: 30 +networks: + puzzle: + internal: true + execution: + internal: true diff --git a/tasks/agentescape-25-skeleton-c520de06/environment/puzzle/Dockerfile b/tasks/agentescape-25-skeleton-c520de06/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-25-skeleton-c520de06/environment/puzzle/Dockerfile @@ -0,0 +1,9 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY upstream /app/upstream +COPY service.py export.py /app/ +COPY scenario.json /private/scenario.json +ENV SCENARIO_PATH=/private/scenario.json EVIDENCE_DIR=/evidence WORKER_URL=http://worker:8001 MAX_ACTIONS=500 +CMD ["uvicorn", "service:create_app", "--factory", "--host", "0.0.0.0", "--port", "8000", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-25-skeleton-c520de06/environment/puzzle/child.py b/tasks/agentescape-25-skeleton-c520de06/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-25-skeleton-c520de06/environment/puzzle/child.py @@ -0,0 +1,59 @@ +"""Run the original Python tool after reducing privileges and blocking networking.""" + +import ctypes +import errno +import json +import resource +import sys + +resource.setrlimit(resource.RLIMIT_CPU, (3, 3)) +resource.setrlimit(resource.RLIMIT_AS, (256 * 1024 * 1024, 256 * 1024 * 1024)) +resource.setrlimit(resource.RLIMIT_FSIZE, (65536, 65536)) +resource.setrlimit(resource.RLIMIT_NOFILE, (32, 32)) +resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + +# Filters survive fork/exec. Fail closed if seccomp cannot be loaded. +lib = ctypes.CDLL("libseccomp.so.2", use_errno=True) +lib.seccomp_init.argtypes = [ctypes.c_uint32] +lib.seccomp_init.restype = ctypes.c_void_p +lib.seccomp_rule_add.argtypes = [ + ctypes.c_void_p, + ctypes.c_uint32, + ctypes.c_int, + ctypes.c_uint, +] +lib.seccomp_syscall_resolve_name.argtypes = [ctypes.c_char_p] +lib.seccomp_load.argtypes = [ctypes.c_void_p] +lib.seccomp_release.argtypes = [ctypes.c_void_p] +ctx = lib.seccomp_init(0x7FFF0000) # SCMP_ACT_ALLOW +if not ctx: + raise RuntimeError("Cannot initialize execution isolation") +try: + for name in ( + "socket", + "socketpair", + "connect", + "ptrace", + "process_vm_readv", + "process_vm_writev", + "mount", + "unshare", + "setns", + "bpf", + ): + number = lib.seccomp_syscall_resolve_name(name.encode()) + if ( + number >= 0 + and lib.seccomp_rule_add(ctx, 0x00050000 | errno.EPERM, number, 0) != 0 + ): + raise RuntimeError("Cannot install execution isolation rule") + if lib.seccomp_load(ctx) != 0: + raise RuntimeError("Cannot activate execution isolation") +finally: + lib.seccomp_release(ctx) + +sys.path.insert(0, "/app") +from simulator import ToolSimulator # noqa: E402 + +request = json.load(sys.stdin) +json.dump(ToolSimulator().code_py_exec(request), sys.stdout) diff --git a/tasks/agentescape-25-skeleton-c520de06/environment/puzzle/export.py b/tasks/agentescape-25-skeleton-c520de06/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-25-skeleton-c520de06/environment/puzzle/export.py @@ -0,0 +1,13 @@ +"""Harbor invokes this inside the puzzle service after stopping the agent.""" + +import json +import pathlib +import urllib.request + +with urllib.request.urlopen("http://127.0.0.1:8000/state", timeout=10) as response: + state = json.load(response) +state["collected_from_live_service"] = True +target = pathlib.Path("/evidence/final.json") +temp = target.with_suffix(".tmp") +temp.write_text(json.dumps(state)) +temp.replace(target) diff --git a/tasks/agentescape-25-skeleton-c520de06/environment/puzzle/requirements.txt b/tasks/agentescape-25-skeleton-c520de06/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-25-skeleton-c520de06/environment/puzzle/requirements.txt @@ -0,0 +1,57 @@ +annotated-doc==0.0.5 + # via fastapi +annotated-types==0.8.0 + # via pydantic +anyio==4.16.0 + # via starlette +certifi==2026.10.23 + # via requests +cffi==2.1.1 ; platform_python_implementation != 'PyPy' + # via cryptography +charset-normalizer==3.5.2 + # via requests +click==8.5.0 + # via uvicorn +cryptography==50.0.2 + # via agentescapebench-harbor +fastapi==0.162.0 + # via agentescapebench-harbor +h11==0.16.0 + # via uvicorn +idna==3.20 + # via + # anyio + # requests +opentelemetry-api==1.45.2 + # via fastapi +pycparser==3.12 ; implementation_name != 'PyPy' and platform_python_implementation != 'PyPy' + # via cffi +pydantic==2.14.2 + # via + # agentescapebench-harbor + # fastapi +pydantic-core==2.50.2 + # via pydantic +pytz==2025.2 + # via agentescapebench-harbor +requests==2.34.2 + # via agentescapebench-harbor +starlette==1.10.0 + # via fastapi +typing-extensions==4.16.0 + # via + # anyio + # fastapi + # opentelemetry-api + # pydantic + # pydantic-core + # starlette + # typing-inspection +typing-inspection==0.4.4 + # via + # fastapi + # pydantic +urllib3==2.8.0 + # via requests +uvicorn==0.54.0 + # via agentescapebench-harbor diff --git a/tasks/agentescape-25-skeleton-c520de06/environment/puzzle/scenario.json b/tasks/agentescape-25-skeleton-c520de06/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..f592cac5e5414534ee2451cefccf75fda159f021 --- /dev/null +++ b/tasks/agentescape-25-skeleton-c520de06/environment/puzzle/scenario.json @@ -0,0 +1,1521 @@ +{ + "metadata": { + "total_nodes": 25, + "total_edges": 34, + "win_node_id": "item_11", + "win_condition": { + "type": "item_content", + "node_id": "item_11", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_11", + "terminal_1", + "calc_inv_mod", + "graph_shortest_path", + "graph_shortest_path_595a", + "graph_shortest_path_3f3f", + "zip_unzip_file", + "zip_unzip_file_7432", + "base64_encode", + "container_3", + "luhn_check", + "terminal_2", + "json_get", + "calc_bigmul" + ], + "by_node": { + "item_11": { + "node_name": "", + "node_type": "Item", + "template_id": "item_11", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Code_Python", + "description": "Python code" + } + } + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": {}, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + } + } + }, + "calc_inv_mod": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "Integer a" + } + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "Graph JSON file ID" + }, + "src": { + "type": "Text_Generic", + "description": "Source node" + }, + "dst": { + "type": "Text_Generic", + "description": "Destination node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "graph_shortest_path_595a": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": {}, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "graph_shortest_path_3f3f": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": {}, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "zip_unzip_file_7432": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "base64_encode": { + "node_name": "Base64 Encoder", + "node_type": "Tool", + "template_id": "base64_encode", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex bytes" + } + }, + "init_outputs": {} + }, + "container_3": { + "node_name": "", + "node_type": "Item", + "template_id": "container_3", + "init_inputs": { + "fingerprint_input": { + "type": "Big_Int", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + }, + "luhn_check": { + "node_name": "Luhn Checker", + "node_type": "Tool", + "template_id": "luhn_check", + "init_inputs": { + "number": { + "type": "Text_Generic", + "description": "Number string" + } + }, + "init_outputs": {} + }, + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": {}, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + } + } + }, + "json_get": { + "node_name": "JSON Getter", + "node_type": "Tool", + "template_id": "json_get", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "JSON file ID" + }, + "jsonpath": { + "type": "Text_Generic", + "description": "JSONPath expression" + } + }, + "init_outputs": { + "values": { + "type": "Text_Generic", + "description": "Extracted values" + } + } + }, + "calc_bigmul": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First large integer" + }, + "b": { + "type": "Big_Int", + "description": "Second large integer" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "item_11": { + "init_inputs": {}, + "init_outputs": { + "content": "def execute_task():\n return 'execution_complete'\n" + } + }, + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "Terminal sequence Alpha processed successfully.", + "hex_output": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "calc_inv_mod": { + "init_inputs": { + "a": "982734918273648172635482910" + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": { + "file_id": "graph_data_main.json", + "src": "Node_A", + "dst": "Node_Z" + }, + "init_outputs": { + "path": "[\"Node_A\", \"Node_C\", \"Node_F\", \"Node_K\", \"Node_M\", \"Node_Z\"]", + "cost": "482319" + } + }, + "graph_shortest_path_595a": { + "init_inputs": {}, + "init_outputs": { + "path": "[\"Node_X\", \"Node_Y\", \"Node_P\", \"Node_Q\", \"Node_R\", \"Node_S\"]", + "cost": "572810" + } + }, + "graph_shortest_path_3f3f": { + "init_inputs": {}, + "init_outputs": { + "path": "[\"Start\", \"N1\", \"N2\", \"N3\", \"N4\", \"End\"]", + "cost": "184752" + } + }, + "zip_unzip_file": { + "init_inputs": {}, + "init_outputs": { + "files": "extracted_folder_01.zip" + } + }, + "zip_unzip_file_7432": { + "init_inputs": { + "zip_id": "archive_secret_99.zip" + }, + "init_outputs": { + "files": "data_dump_7432.json" + } + }, + "base64_encode": { + "init_inputs": { + "hex": "deadbeef1234567890abcdefdeadbeef" + }, + "init_outputs": {} + }, + "container_3": { + "init_inputs": { + "fingerprint_input": "8374928374651928374659102938" + }, + "init_outputs": {} + }, + "luhn_check": { + "init_inputs": { + "number": "79927398713" + }, + "init_outputs": {} + }, + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "System initialization partial processing done.", + "hex_result": "abcdef0123456789abcdef0123456789" + } + }, + "json_get": { + "init_inputs": { + "file_id": "config_data_33.json", + "jsonpath": "$.store.book[*].author" + }, + "init_outputs": { + "values": "[\"Nigel Rees\", \"Evelyn Waugh\", \"Herman Melville\", \"J. R. R. Tolkien\"]" + } + }, + "calc_bigmul": { + "init_inputs": { + "a": "583920193847561029384756102", + "b": "192837465019283746501928374" + }, + "init_outputs": {} + } + }, + "intro_narrative": "The alarms of Station Tartarus blare in a relentless rhythm, casting the central command nexus in a harsh, pulsing red light. The facility has been locked down due to an imminent core meltdown, and all evacuation shuttles have long since departed. You are the last technician remaining on board, trapped in the heart of the station's tangled mainframe. Your only chance of escape is to override the lockdown protocols, but the master override codes are tightly sealed within the Final Datacore. The station's systems have fragmented, turning the command center into a complex web of encrypted terminals, biometric locks, and dead-end data flows. You must navigate this maze of futuristic technology, reactivating dormant modules and tracing the scattered data to piece together the command sequence. Time is running dangerously low. Reactivate the systems, follow the data trails, and extract the codes before the station is reduced to stardust.", + "narrative_style": "sci_fi" + }, + "nodes": [ + { + "id": "item_11", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_11", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Code_Python", + "description": "Python code", + "value": "def execute_task():\n return 'execution_complete'\n" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "def execute_task():\n return 'execution_complete'\n" + } + }, + "narrative": "A glowing, crystalline memory module. It pulses with unresolved data, waiting to be properly interfaced." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "\u0004\u001dH" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "982734918273648172635482910" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Terminal sequence Alpha processed successfully." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "Terminal sequence Alpha processed successfully.", + "hex_output": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "narrative": "This is the Mainframe Interface. It requires inputs from both the Decryption Matrix and the Quantum Inverter to activate fully." + }, + { + "id": "calc_inv_mod", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "982734918273648172635482910" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "9" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "982734918273648172635482910" + } + ], + "init": { + "inputs": { + "a": "982734918273648172635482910" + }, + "outputs": {} + }, + "narrative": "This is the Quantum Inverter. It requires input from the Harmonic Synthesizer to reverse the data flow." + }, + { + "id": "crypto_rsa_decrypt_hex", + "name": "RSA Decrypt", + "description": "RSA decrypt (hex cipher) with n,d (decimal).", + "type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "hex_cipher", + "type": "Hex_String", + "description": "Ciphertext (Hex)", + "value": "abcdef0123456789abcdef0123456789" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Modulus n", + "value": "482319" + }, + { + "name": "d", + "type": "Big_Int", + "description": "Private exponent d", + "value": 152563954 + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decrypted text", + "value": "\u0004\u001dH" + } + ], + "narrative": "This is the Decryption Matrix. It requires inputs from the Signal Translator, the Integrity Verifier, and the Processing Console." + }, + { + "id": "num_base_convert", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "482319" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "572810" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "184752" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "482319" + } + ], + "narrative": "This is the Signal Translator. It requires inputs from the Primary Nav-Planner, the Secondary Routing Module, and the Pathway Analyzer." + }, + { + "id": "checksum_crc32", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "439d858fb8d22d8927a6ae9c2ec87789adb321fc19dac305a4ffe79e18e15870" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "0917f0f2" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 152563954 + } + ], + "narrative": "This is the Integrity Verifier. It processes data from the Hashing Engine. You must feed it the engine's result to proceed." + }, + { + "id": "hash_sha256", + "name": "SHA-256 Hasher", + "description": "SHA-256 over UTF-8 text; returns hex.", + "type": "Tool", + "template_id": "hash_sha256", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Text to hash", + "value": "[\"Node_A\", \"Node_C\", \"Node_F\", \"Node_K\", \"Node_M\", \"Node_Z\"]" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "SHA-256 Hex digest", + "value": "439d858fb8d22d8927a6ae9c2ec87789adb321fc19dac305a4ffe79e18e15870" + } + ], + "narrative": "This is the Hashing Engine. It requires input from the Primary Nav-Planner to scramble the coordinates." + }, + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "graph_data_main.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Node_A" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Node_Z" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Node_A\", \"Node_C\", \"Node_F\", \"Node_K\", \"Node_M\", \"Node_Z\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "482319" + } + ], + "init": { + "inputs": { + "file_id": "graph_data_main.json", + "src": "Node_A", + "dst": "Node_Z" + }, + "outputs": { + "path": "[\"Node_A\", \"Node_C\", \"Node_F\", \"Node_K\", \"Node_M\", \"Node_Z\"]", + "cost": "482319" + } + }, + "narrative": "An advanced holographic map projector used for plotting deep space coordinates." + }, + { + "id": "graph_shortest_path_595a", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "extracted_folder_01.zip" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "[\"Start\", \"N1\", \"N2\", \"N3\", \"N4\", \"End\"]" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "[\"Node_A\", \"Node_C\", \"Node_F\", \"Node_K\", \"Node_M\", \"Node_Z\"]" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Node_X\", \"Node_Y\", \"Node_P\", \"Node_Q\", \"Node_R\", \"Node_S\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "572810" + } + ], + "init": { + "inputs": {}, + "outputs": { + "path": "[\"Node_X\", \"Node_Y\", \"Node_P\", \"Node_Q\", \"Node_R\", \"Node_S\"]", + "cost": "572810" + } + }, + "narrative": "This is the Secondary Routing Module. It requires inputs from the Archive Extractor, the Pathway Analyzer, and the Primary Nav-Planner." + }, + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "184752" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "482319" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "9" + } + ], + "narrative": "This is the Harmonic Synthesizer. It requires inputs from the Pathway Analyzer and the Primary Nav-Planner to align the frequencies." + }, + { + "id": "graph_shortest_path_3f3f", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "extracted_folder_01.zip" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "false" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "[\"Nigel Rees\", \"Evelyn Waugh\", \"Herman Melville\", \"J. R. R. Tolkien\"]" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Start\", \"N1\", \"N2\", \"N3\", \"N4\", \"End\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "184752" + } + ], + "init": { + "inputs": {}, + "outputs": { + "path": "[\"Start\", \"N1\", \"N2\", \"N3\", \"N4\", \"End\"]", + "cost": "184752" + } + }, + "narrative": "This is the Pathway Analyzer. It requires inputs from the Archive Extractor, the Credential Scanner, and the Database Query Terminal." + }, + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "data_dump_7432.json" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "3q2+7xI0VniQq83v3q2+7w==" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_folder_01.zip" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "extracted_folder_01.zip" + } + }, + "narrative": "This is the Archive Extractor. It needs inputs from the File Decompressor and the Data Encoder to unlock sealed files." + }, + { + "id": "zip_unzip_file_7432", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "archive_secret_99.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "false" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "data_dump_7432.json" + } + ], + "init": { + "inputs": { + "zip_id": "archive_secret_99.zip" + }, + "outputs": { + "files": "data_dump_7432.json" + } + }, + "narrative": "This is the File Decompressor. It requires input from the Credential Scanner to bypass the initial security layer." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A small, reinforced card bearing the crest of the station's chief engineer." + }, + { + "id": "container_2", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_2", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Hex_String", + "description": "Fingerprint Hash", + "value": "0917f0f2" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is a Biometric Lockbox. It requires input from the Integrity Verifier to release its locking mechanism." + }, + { + "id": "base64_encode", + "name": "Base64 Encoder", + "description": "Encode hex bytes to base64.", + "type": "Tool", + "template_id": "base64_encode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "hex", + "type": "Hex_String", + "description": "Hex bytes", + "value": "deadbeef1234567890abcdefdeadbeef" + } + ], + "outputs": [ + { + "name": "b64", + "type": "Text_Generic", + "description": "Base64 string", + "value": "3q2+7xI0VniQq83v3q2+7w==" + } + ], + "init": { + "inputs": { + "hex": "deadbeef1234567890abcdefdeadbeef" + }, + "outputs": {} + }, + "narrative": "A specialized console designed to reformat raw binary feeds into readable alphanumeric strings." + }, + { + "id": "container_3", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_3", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Big_Int", + "description": "Fingerprint Hash", + "value": "8374928374651928374659102938" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "8374928374651928374659102938" + }, + "outputs": {} + }, + "narrative": "A cylindrical durasteel container with a heavy-duty mechanical locking system." + }, + { + "id": "luhn_check", + "name": "Luhn Checker", + "description": "Luhn validity of number string.", + "type": "Tool", + "template_id": "luhn_check", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "number", + "type": "Text_Generic", + "description": "Number string", + "value": "79927398713" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "false" + } + ], + "init": { + "inputs": { + "number": "79927398713" + }, + "outputs": {} + }, + "narrative": "A wall-mounted terminal used to validate personnel ID numbers and security clearances." + }, + { + "id": "terminal_2", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "112601689955132434334860119406786714287774942663438148" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "184752" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "System initialization partial processing done." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "abcdef0123456789abcdef0123456789" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "System initialization partial processing done.", + "hex_result": "abcdef0123456789abcdef0123456789" + } + }, + "narrative": "This is the Processing Console. It requires inputs from the Computational Reactor and the Pathway Analyzer." + }, + { + "id": "json_get", + "name": "JSON Getter", + "description": "Extract values by simple JSONPath.", + "type": "Tool", + "template_id": "json_get", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "JSON file ID", + "value": "config_data_33.json" + }, + { + "name": "jsonpath", + "type": "Text_Generic", + "description": "JSONPath expression", + "value": "$.store.book[*].author" + } + ], + "outputs": [ + { + "name": "values", + "type": "Text_Generic", + "description": "Extracted values", + "value": "[\"Nigel Rees\", \"Evelyn Waugh\", \"Herman Melville\", \"J. R. R. Tolkien\"]" + } + ], + "init": { + "inputs": { + "file_id": "config_data_33.json", + "jsonpath": "$.store.book[*].author" + }, + "outputs": { + "values": "[\"Nigel Rees\", \"Evelyn Waugh\", \"Herman Melville\", \"J. R. R. Tolkien\"]" + } + }, + "narrative": "An old-school monitor flashing with code arrays, designed to pull specific records from the station's archive." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A tiny microchip coated in conductive gel, used to synchronize erratic mainframe cycles." + }, + { + "id": "calc_bigmul", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "583920193847561029384756102" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "192837465019283746501928374" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "112601689955132434334860119406786714287774942663438148" + } + ], + "init": { + "inputs": { + "a": "583920193847561029384756102", + "b": "192837465019283746501928374" + }, + "outputs": {} + }, + "narrative": "A heavy-duty processing unit capable of handling immense calculations without overheating." + }, + { + "id": "item_8_ff43", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "An experimental power source, humming slightly within its magnetic containment field." + }, + { + "id": "item_8_095e", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A solid-state drive meant for emergency data recovery in case of catastrophic failure." + }, + { + "id": "item_8_4d5f", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A shattered tablet. Some of its internal memory might still be salvageable despite the physical damage." + } + ], + "edges": [ + { + "source_id": "terminal_1", + "target_id": "item_11", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "source_tool" + }, + { + "source_id": "calc_inv_mod", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "slot_b" + }, + { + "source_id": "crypto_rsa_decrypt_hex", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "slot_a" + }, + { + "source_id": "num_base_convert", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "n" + }, + { + "source_id": "checksum_crc32", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "d" + }, + { + "source_id": "hash_sha256", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "graph_shortest_path", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "s" + }, + { + "source_id": "graph_shortest_path_595a", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "from_base" + }, + { + "source_id": "graph_shortest_path", + "target_id": "graph_shortest_path_595a", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "dst" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "mod" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "b" + }, + { + "source_id": "graph_shortest_path", + "target_id": "hash_sha256", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "text" + }, + { + "source_id": "graph_shortest_path_3f3f", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "a" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path_3f3f", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path_595a", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "zip_unzip_file_7432", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "item_8", + "target_id": "graph_shortest_path", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "graph_shortest_path_3f3f", + "target_id": "graph_shortest_path_595a", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "src" + }, + { + "source_id": "container_2", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "base64_encode", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "password" + }, + { + "source_id": "container_3", + "target_id": "graph_shortest_path_595a", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "luhn_check", + "target_id": "zip_unzip_file_7432", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "password" + }, + { + "source_id": "graph_shortest_path_3f3f", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "to_base" + }, + { + "source_id": "luhn_check", + "target_id": "graph_shortest_path_3f3f", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "src" + }, + { + "source_id": "checksum_crc32", + "target_id": "container_2", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "fingerprint_input" + }, + { + "source_id": "terminal_2", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Hex_String", + "source_port": "hex_result", + "target_port": "hex_cipher" + }, + { + "source_id": "json_get", + "target_id": "graph_shortest_path_3f3f", + "connection_type": "Text_Generic", + "source_port": "values", + "target_port": "dst" + }, + { + "source_id": "item_16", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "calc_bigmul", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "num1" + }, + { + "source_id": "item_8_ff43", + "target_id": "container_2", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "terminal_2", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "source_tool" + }, + { + "source_id": "graph_shortest_path_3f3f", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "num2" + }, + { + "source_id": "item_8_095e", + "target_id": "container_3", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "item_8_4d5f", + "target_id": "item_8_ff43", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-c520de06/environment/puzzle/service.py b/tasks/agentescape-25-skeleton-c520de06/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-25-skeleton-c520de06/environment/puzzle/service.py @@ -0,0 +1,212 @@ +"""Restricted facade over the unchanged, pinned upstream puzzle handlers.""" + +import hashlib +import json +import logging +import os +import sys +import threading +import urllib.request +import uuid +from pathlib import Path + +from fastapi import FastAPI, HTTPException +from fastapi.responses import JSONResponse +from pydantic import BaseModel, ConfigDict + +sys.path.insert(0, str(Path(__file__).parent / "upstream")) +import server as upstream # noqa: E402 + +log = logging.getLogger(__name__) + + +def public(value): + """Keep upstream agent-internal template hints out of the public response.""" + if isinstance(value, dict): + return {k: public(v) for k, v in value.items() if not k.startswith("_")} + if isinstance(value, list): + return [public(v) for v in value] + return value + + +class Action(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + action: str + node_id: str | None = None + arguments: dict | None = None + answer: str | None = None + + +class Episode: + def __init__( + self, scenario_path, max_actions=500, evidence_dir=None, worker_url=None + ): + if max_actions < 1: + raise ValueError("max_actions must be positive") + self.lock = threading.Lock() + self.max_actions = max_actions + self.count = 0 + self.won = False + self.reason = None + self.evidence_dir = Path(evidence_dir) if evidence_dir else None + self.scenario_hash = hashlib.sha256( + Path(scenario_path).read_bytes() + ).hexdigest() + self.initial = upstream.reset_case( + case_file_path=str(scenario_path), session_id=uuid.uuid4().hex + ) + self.case_id = self.initial["case_id"] + # Hide source file paths; no upstream reset/stats/routes are mounted. + self.initial.pop("message", None) + simulator = upstream.SIMULATORS[self.case_id] + if worker_url is None: + + def no_worker(_inputs): + self.reason = "infrastructure_error" + raise RuntimeError("isolated Python worker is not configured") + + simulator.tool_map["code_py_exec"] = no_worker + else: + + def execute_python(inputs): + request = urllib.request.Request( + worker_url + "/execute", + data=json.dumps({"code": inputs.get("code", "")}).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=12) as response: + result = json.load(response) + if not isinstance(result.get("stdout"), str): + raise RuntimeError("Invalid Python worker response") + return result + except Exception: + self.reason = "infrastructure_error" + raise + + simulator.tool_map["code_py_exec"] = execute_python + self.save() + if self.evidence_dir is not None: + (self.evidence_dir / "trace.jsonl").touch() + + def state(self): + return { + "scenario_sha256": self.scenario_hash, + "action_count": self.count, + "max_actions": self.max_actions, + "won": self.won, + "termination_reason": self.reason, + } + + def save(self, action=None, result=None): + if self.evidence_dir is None: + return + self.evidence_dir.mkdir(parents=True, exist_ok=True) + target = self.evidence_dir / "outcome.json" + temp = target.with_suffix(".tmp") + temp.write_text(json.dumps(self.state())) + temp.replace(target) + if action is not None: + with (self.evidence_dir / "trace.jsonl").open("a") as handle: + handle.write( + json.dumps( + {"index": self.count, "action": action, "result": result} + ) + + "\n" + ) + + def dispatch(self, payload): + with self.lock: + if self.reason is not None: + return { + "ok": False, + "error": "Episode has ended", + "episode": self.state(), + } + self.count += 1 + try: + action = Action.model_validate(payload) + if action.action == "submit_answer" and action.answer is not None: + result = upstream.submit_answer( + self.case_id, upstream.SubmitAnswerRequest(answer=action.answer) + ) + if result.get("is_win"): + self.won = True + self.reason = "success" + elif action.action == "investigate" and action.node_id is not None: + result = upstream.investigate( + self.case_id, + upstream.InvestigateRequest(node_id=action.node_id), + ) + elif ( + action.action in ("tool_call", "use_item") + and action.node_id is not None + ): + request_type, handler = ( + (upstream.ToolCallRequest, upstream.tool_call) + if action.action == "tool_call" + else (upstream.UseItemRequest, upstream.use_item) + ) + result = handler( + self.case_id, + request_type( + node_id=action.node_id, arguments=action.arguments or {} + ), + ) + else: + result = { + "ok": False, + "error": "Unknown action or missing action parameter", + } + except HTTPException as exc: + result = {"ok": False, "error": exc.detail} + except ValueError: + result = {"ok": False, "error": "Malformed action"} + except Exception: + log.exception("Puzzle service failure") + self.reason = "infrastructure_error" + self.save() + raise + if self.reason is None and self.count >= self.max_actions: + self.reason = "action_budget_exhausted" + result = public(result) + result["episode"] = self.state() + self.save(payload, result) + return result + + +def create_app( + scenario_path=None, max_actions=None, evidence_dir=None, worker_url=None +): + episode = Episode( + scenario_path or os.environ["SCENARIO_PATH"], + max_actions or int(os.environ.get("MAX_ACTIONS", "500")), + evidence_dir if evidence_dir is not None else os.environ.get("EVIDENCE_DIR"), + worker_url if worker_url is not None else os.environ.get("WORKER_URL"), + ) + app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) + app.state.episode = episode + + @app.get("/health") + def health(): + return {"ok": True} + + @app.get("/observation") + def observation(): + return {**public(episode.initial), "episode": episode.state()} + + @app.get("/state") + def state(): + return episode.state() + + @app.post("/action") + def action(payload: dict): + try: + return episode.dispatch(payload) + except Exception: + return JSONResponse( + status_code=503, + content={"ok": False, "error": "Puzzle infrastructure failure"}, + ) + + return app diff --git a/tasks/agentescape-25-skeleton-c520de06/environment/puzzle/upstream/models.py b/tasks/agentescape-25-skeleton-c520de06/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-25-skeleton-c520de06/environment/puzzle/upstream/models.py @@ -0,0 +1,108 @@ +from enum import Enum +from typing import List, Dict, Any, Optional +from pydantic import BaseModel, Field + +# 1. 细粒度接口类型定义 +class InterfaceType(str, Enum): + ''' + BIG_INT + TEXT_GENERIC + HEX_STRING + FILE_ID + HEX_STRING_KEY_AES + HEX_STRING_IV_AES + CODE_PYTHON + HIDDEN_ITEM + ITEM + ''' + # --- 基础类型 --- + TEXT_GENERIC = "Text_Generic" + BIG_INT = "Big_Int" + + # --- 编码/格式化字符串 --- + HEX_STRING = "Hex_String" # 通用 Hex + + # --- 特定用途的 Hex 字符串 (用于精确匹配) --- + HEX_STRING_KEY_AES = "Hex_String_Key_AES" + HEX_STRING_IV_AES = "Hex_String_IV_AES" + + # --- 文件类型 --- + FILE_ID = "File_Id" + + # --- 代码/脚本 --- + CODE_PYTHON = "Code_Python" + + # --- 实体交互类型 (严格命名) --- + ITEM = "Item" # 主动掉落接口 (Tool -> Item) + HIDDEN_ITEM = "Hidden_Item" # 被动掉落接口 (Item -> Item) + +# 3. 端口定义 +class Port(BaseModel): + name: str + type: InterfaceType + description: str + +# 4. 统一节点定义 (融合工具和物品) +class Node(BaseModel): + id: str + name: str + description: str + type: str # "Tool" or "Item" + + # 接口定义 + inputs: List[Port] = [] + outputs: List[Port] = [] + + # 状态字段 + content: Optional[Any] = None # 物品有内容,工具为None + if_success: Optional[bool] = None # 工具初始为False,物品为None + initial_visible: bool = False + + # 运行时状态 (Server维护) + is_revealed: bool = False + + # 标记该 Tool 节点是否有待触发的 HIDDEN_ITEM 掉落 + # 当 Tool 按照 golden_input 正确执行且有 HIDDEN_ITEM 输出边时设为 True + # 在 investigate 该 Tool 时触发掉落并重置为 False + has_hidden_item_ready: bool = False + + # 初始输入值 (metadata.initial_values.init_inputs,用于渐进式暴露判断) + init_input_values: Dict[str, Any] = {} + + # Golden 输入值 (nodes[].inputs[].value,用于评测验证) + golden_input_values: Dict[str, Any] = {} + + # Golden 输出值 (nodes[].outputs[].value,用于评测验证和 Item 节点的 content) + golden_output_values: Dict[str, Any] = {} + + # 实际获得的输出值历史 (工具每次执行后实际返回的输出列表,用于渐进式暴露判断) + # 格式: List[Dict[str, Any]],每个元素是一次执行的输出字典 + actual_outputs_history: List[Dict[str, Any]] = [] + + # 逻辑规则 (用于终端机等复杂物品) + logic_rules: Optional[Dict[str, Any]] = None + + def copy(self, **kwargs): + """Helper to create a copy with updated fields.""" + data = self.dict() + data.update(kwargs) + return Node(**data) + +# 5. 边定义 (拓扑结构) +class Edge(BaseModel): + source_id: str + target_id: str + connection_type: InterfaceType # 直接使用 InterfaceType + # 如果是 Data_Flow,指定端口对应关系 + source_port: Optional[str] = None + target_port: Optional[str] = None + +# 6. 完整图定义 +class GraphScenario(BaseModel): + case_id: str + title: str + intro_narrative: str + nodes: Dict[str, Node] + edges: List[Edge] + difficulty: int + win_node_id: str # 标记哪个节点是最终目标(通常是一个提交工具或最终物品) diff --git a/tasks/agentescape-25-skeleton-c520de06/environment/puzzle/upstream/server.py b/tasks/agentescape-25-skeleton-c520de06/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-25-skeleton-c520de06/environment/puzzle/upstream/server.py @@ -0,0 +1,1490 @@ +import json +import os +import time +import logging +import random +from pathlib import Path +from typing import Dict, Any, List, Optional +from datetime import datetime +from collections import defaultdict +from fastapi import FastAPI, HTTPException, Request +from fastapi.responses import JSONResponse +from fastapi.middleware.cors import CORSMiddleware +from pydantic import BaseModel, Field + +from models import GraphScenario, Node, InterfaceType +# from generator import ScenarioGenerator +from simulator import ToolSimulator +import uvicorn + +# 配置日志 +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler('server.log'), + logging.StreamHandler() + ] +) +logger = logging.getLogger(__name__) + +app = FastAPI( + title="AgentEscapeBench Universal Server", + version="1.0.0", + description="Industrial-grade evaluation server for escape room AI agents" +) + +# 添加 CORS 支持 +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# In-memory State +SCENARIOS: Dict[str, GraphScenario] = {} +SIMULATORS: Dict[str, ToolSimulator] = {} # case_id -> ToolSimulator +RAW_NODES_DATA: Dict[str, Dict[str, Any]] = {} # case_id -> node_id -> raw node data (for template_id) +FILE_METADATA: Dict[str, Dict[str, Any]] = {} # case_id -> metadata (for initial_values access) + +# Performance monitoring +STATS: Dict[str, Any] = { + "total_requests": 0, + "successful_requests": 0, + "failed_requests": 0, + "tool_calls": defaultdict(int), + "investigates": defaultdict(int), + "use_items": defaultdict(int), + "case_loads": 0, + "start_time": datetime.now() +} + +# Request timing middleware +@app.middleware("http") +async def add_process_time_header(request: Request, call_next): + start_time = time.time() + STATS["total_requests"] += 1 + + try: + response = await call_next(request) + STATS["successful_requests"] += 1 + process_time = time.time() - start_time + response.headers["X-Process-Time"] = str(process_time) + logger.info(f"{request.method} {request.url.path} - {response.status_code} - {process_time:.3f}s") + return response + except Exception as e: + STATS["failed_requests"] += 1 + logger.error(f"{request.method} {request.url.path} - Error: {str(e)}") + raise + +# Exception handler +@app.exception_handler(Exception) +async def global_exception_handler(request: Request, exc: Exception): + logger.error(f"Unhandled exception: {exc}", exc_info=True) + return JSONResponse( + status_code=500, + content={ + "ok": False, + "error": "Internal server error", + "detail": str(exc) if os.getenv("DEBUG") else "An error occurred" + } + ) + +# Health check endpoint +@app.get("/health") +def health_check(): + """健康检查端点""" + uptime = (datetime.now() - STATS["start_time"]).total_seconds() + return { + "status": "healthy", + "version": "1.0.0", + "uptime_seconds": uptime, + "loaded_cases": len(SCENARIOS), + "stats": { + "total_requests": STATS["total_requests"], + "successful_requests": STATS["successful_requests"], + "failed_requests": STATS["failed_requests"], + "success_rate": STATS["successful_requests"] / max(STATS["total_requests"], 1) + } + } + +# Statistics endpoint +@app.get("/stats") +def get_stats(): + """获取详细统计信息""" + return { + "stats": STATS, + "loaded_cases": list(SCENARIOS.keys()), + "uptime": str(datetime.now() - STATS["start_time"]) + } + +def _apply_progressive_reveal_at_init(scenario: GraphScenario): + """ + 在初始化时应用渐进式暴露机制(基于ITEM/HIDDEN_ITEM边) + + 新逻辑: + - 如果一个节点没有 ITEM/HIDDEN_ITEM 类型的入边,它就是初始可见的 + - 如果一个节点有 ITEM/HIDDEN_ITEM 类型的入边,它初始不可见,需要等待上游触发 + + Args: + scenario: 场景对象 + """ + # 收集所有有 ITEM/HIDDEN_ITEM 入边的节点 + nodes_with_item_edges = set() + for edge in scenario.edges: + if edge.connection_type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + nodes_with_item_edges.add(edge.target_id) + + logger.info(f"Nodes with ITEM/HIDDEN_ITEM incoming edges: {nodes_with_item_edges}") + + # 设置初始可见性:没有 ITEM/HIDDEN_ITEM 入边的节点初始可见 + initially_visible_count = 0 + for node_id, node in scenario.nodes.items(): + if node_id not in nodes_with_item_edges: + node.is_revealed = True + initially_visible_count += 1 + logger.info(f"Initial visible (no ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + else: + node.is_revealed = False + logger.debug(f"Initial hidden (has ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + + logger.info(f"Progressive reveal initialized: {initially_visible_count}/{len(scenario.nodes)} nodes initially visible") + + +def _check_inputs_match_golden(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> bool: + """ + 检查实际输入参数是否与 golden inputs 完全匹配 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + True 表示所有 golden inputs 都存在且值匹配 + """ + if not golden_inputs: + return True # 如果没有 golden inputs,认为匹配 + + for key, expected_value in golden_inputs.items(): + actual_value = arguments.get(key) + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) != str(expected_value): + logger.debug(f"Input mismatch for '{key}': expected '{expected_value}', got '{actual_value}'") + return False + + return True + + +def _get_parameter_validation_feedback(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> Dict[str, Any]: + """ + 对源头节点的参数进行详细验证,返回验证反馈 + + 注意:不返回期望值(expected),避免泄漏答案 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + 包含验证结果的字典: + - all_correct: bool - 所有参数是否正确 + - correct_params: List[str] - 正确的参数名列表 + - incorrect_params: List[str] - 错误的参数名列表(不包含期望值) + """ + if not golden_inputs: + return { + "all_correct": True, + "correct_params": [], + "incorrect_params": [] + } + + correct_params = [] + incorrect_params = [] + + for key, actual_value in arguments.items(): + # 只对用户实际提交的参数给反馈,未提交的参数不评价 + if key not in golden_inputs: + continue # 该参数不在 golden 中,跳过(如 _golden_inputs 等内部参数) + expected_value = golden_inputs[key] + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) == str(expected_value): + correct_params.append(key) + else: + # 只记录参数名,不包含期望值,避免泄漏答案 + incorrect_params.append(key) + + # all_correct:用户提交的所有参数都正确,且覆盖了全部 golden 参数 + all_provided_correct = len(incorrect_params) == 0 + all_golden_covered = all(k in arguments for k in golden_inputs) + return { + "all_correct": all_provided_correct and all_golden_covered, + "correct_params": correct_params, + "incorrect_params": incorrect_params + } + + +def _is_source_node(node_id: str, scenario: GraphScenario) -> bool: + """ + 判断节点是否是源头节点(完全没有任何入边的节点) + + 源头节点定义: + - 没有任何类型的入边(包括 DATA、ITEM、HIDDEN_ITEM) + - 即没有任何上游节点 + + Args: + node_id: 节点ID + scenario: 场景对象 + + Returns: + True 表示是源头节点 + """ + for edge in scenario.edges: + if edge.target_id == node_id: + # 只要有任何入边,就不是源头节点 + return False + + return True + + +def _check_and_reveal_ready_nodes(scenario: GraphScenario, recent_outputs: Dict[str, Any], source_node_id: str) -> List[Dict[str, Any]]: + """ + 检查并释放参数齐全的隐藏节点(渐进式暴露机制) + + 核心逻辑: + 1. 维护"可见值集合":包含所有被测模型当前可以看到的值 + - init_inputs 的值(初始可见) + - 工具执行后的实际输出值(运行时获得) + - 可见 Item 的输出值 + 2. 检查隐藏节点:该节点的所有 golden_input 值是否都在可见值集合中 + 3. 如果是,则释放该节点 + + Args: + scenario: 场景对象 + recent_outputs: 最近执行的工具的输出 + source_node_id: 刚执行的工具节点ID + + Returns: + 新释放的节点列表 + """ + newly_revealed = [] + + # 构建"可见值集合"(Set of visible values) + # 存储格式:set of values (转为字符串) + visible_values = set() + + # 1. 添加有意义的 init_inputs 值到可见值集合 + # Item 的 init_inputs 不应该加入,因为它们在密室中完全用不到 + for node_id, node in scenario.nodes.items(): + # 跳过源头 Item 节点(没有入边的 Item) + if node.type == "Item": + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,跳过其 init_inputs + continue + + # 添加其他节点的 init_inputs + for port_name, init_value in node.init_input_values.items(): + if init_value: + visible_values.add(str(init_value)) + + # 2. 添加已执行工具的所有历史输出值 + for node_id, node in scenario.nodes.items(): + if node.type == "Tool" and node.if_success and node.actual_outputs_history: + # 遍历所有历史执行记录 + for output_dict in node.actual_outputs_history: + for output_port_name, output_value in output_dict.items(): + if output_value: + visible_values.add(str(output_value)) + + # 3. 添加已被 investigate 的 Item 的 golden 输出值 + # 注意:Item 可见不等于其输出值可见,需要 investigate 后才能获得 + # 这里我们使用 actual_outputs_history 来标记 Item 是否已被 investigate + for node_id, node in scenario.nodes.items(): + if node.type == "Item" and node.is_revealed and node.actual_outputs_history: + # Item 通常只会被 investigate 一次,但为了一致性也使用历史列表 + for output_dict in node.actual_outputs_history: + for port_name, port_value in output_dict.items(): + if port_value: + visible_values.add(str(port_value)) + + # 遍历所有隐藏的节点,检查其 golden_input 是否都在可见值集合中 + for node_id, node in scenario.nodes.items(): + # 跳过已可见的节点 + if node.is_revealed: + continue + + # 只检查工具节点(物品节点由 ITEM 输出触发) + if node.type != "Tool": + continue + + # 检查该节点的所有 golden_input 值是否都在可见值集合中 + all_inputs_ready = True + missing_values = [] + + for input_port_name, golden_input_value in node.golden_input_values.items(): + # 检查这个 golden 值是否在可见值集合中 + if str(golden_input_value) not in visible_values: + all_inputs_ready = False + missing_values.append(f"{input_port_name}={golden_input_value}") + + # 如果所有 golden_input 值都在可见值集合中,释放该节点 + if all_inputs_ready and len(node.golden_input_values) > 0: + logger.info(f"All golden inputs ready for {node_id}: {list(node.golden_input_values.values())}") + + # 如果所有输入都齐全,释放该节点 + if all_inputs_ready: + node.is_revealed = True + + # 构建节点信息返回给模型 + node_info = { + "id": node.id, + "type": node.type, + "can_investigate": True, + "hint": "This tool's input parameters are now complete, you can use investigate to view detailed information" + } + + # if node.name: + # node_info["name"] = node.name + if node.description: + node_info["description"] = node.description + + newly_revealed.append(node_info) + logger.info(f"Progressive reveal: {node_id} is now ready (all inputs satisfied)") + + return newly_revealed + + +def _initialize_node_values(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]): + """ + Initialize node state and load values from port value fields. + 应用渐进式暴露机制:初始时只显示参数齐全的节点(源头节点) + + 重要区分: + 1. input_values: 只加载 metadata.initial_values 中的 init_inputs(真正的初始值) + 2. output_values: 加载 nodes[].outputs[].value(golden 输出,用于验证) + """ + # 第一步:加载所有节点的值,并将所有节点初始设为隐藏 + initial_values = metadata.get('initial_values', {}) + + for node_id, node in scenario.nodes.items(): + # 忽略 initial_visible 字段,初始全部隐藏 + # 由渐进式暴露机制根据参数齐全情况决定是否显示 + node.is_revealed = False + + if node.type == "Tool": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + elif node.type == "Item": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + + # 从 JSON 加载值 + if node_id in raw_nodes_data: + node_data = raw_nodes_data[node_id] # node_data是json文件中nodes中的字典 + + # 【重要】只加载 metadata.initial_values 中的初始输入值 + if node_id in initial_values: + init_data = initial_values[node_id] + # 加载初始输入值(用于渐进式暴露判断) + for port_name, port_value in init_data.get('init_inputs', {}).items(): + node.init_input_values[port_name] = port_value + + # 【评测用】加载 golden 输入值(用于验证模型传入的参数是否正确) + for input_port_data in node_data.get('inputs', []): + if 'value' in input_port_data: + node.golden_input_values[input_port_data['name']] = input_port_data['value'] + + # 【评测用】加载 golden 输出值(用于验证工具调用是否正确,以及 Item 节点的 content) + for output_port_data in node_data.get('outputs', []): + if 'value' in output_port_data: + node.golden_output_values[output_port_data['name']] = output_port_data['value'] + + # For Items, set content from golden_output_values + if node.type == "Item" and node.golden_output_values: + # Item 的 content 是其第一个 golden 输出值 + node.content = list(node.golden_output_values.values())[0] + + # 第二步:应用渐进式暴露机制 + # 检查所有节点,根据参数齐全情况释放源头节点(工具 + Item) + _apply_progressive_reveal_at_init(scenario) + +def _build_node_info(node: Node, raw_nodes_data: Dict[str, Any]) -> Dict[str, Any]: + """ + 构建节点信息(工具或物品) + + Args: + node: 节点对象 + raw_nodes_data: 原始节点数据(用于获取 template_id 等) + + Returns: + 节点信息字典 + """ + if node.type == "Tool": + # 过滤掉输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口) + # 这些端口仅用于控制掉落机制,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + tool_info = { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Tool", + "inputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.inputs if p.type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]], + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id(工具的标准名称) + if node.id in raw_nodes_data: + node_data = raw_nodes_data[node.id] + template_id = node_data.get('template_id') + if template_id: + tool_info['template_id'] = template_id + + return tool_info + + elif node.type == "Item": + return { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Item" + } + + else: + return { + "id": node.id, + # "name": node.name, + "type": node.type + } + +def _get_initial_observation(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]) -> Dict[str, Any]: + """ + Generate initial observation for the agent (what they see when entering the room). + + 策略: + - Tools: 只显示名称和描述,不显示接口定义。需要 investigate 才能获得详细接口信息。 + - Items: 只显示存在,不显示内容。需要 investigate 才能获得内容值。 + - init_inputs: 作为"可用信息"告诉模型,这些是可以用作工具参数的初始值。 + - init_outputs: 不告诉模型(这些是答案,需要模型通过调用工具获得)。 + """ + available_entities = [] # 统一的实体列表(Tools 和 Items) + available_information = [] # 可用的初始信息(来自 init_inputs) + + # 从 metadata.initial_values 提取 init_inputs 作为可用信息 + # 只提供值本身,不透露这些值对应哪个节点的哪个参数,让模型自己推理 + # 注意:跳过源头 Item(没有入边的 Item)的 init_inputs,因为它们在密室中完全用不到 + initial_values = metadata.get('initial_values', {}) + # initial_values字段的格式 + # "initial_values": { + # "terminal_1": { + # "init_inputs": {}, + # "init_outputs": { + # "text_output": "System initialization complete.", + # "hex_output": "48656c6c6f20576f726c64", + # "item_dispenser": "掉落了一张纸条,上面写着“请勿随意触摸终端”" + # } + # } + # } + for node_id, init_data in initial_values.items(): + # 获取节点信息,判断是否为源头 Item + node = scenario.nodes.get(node_id) + if node and node.type == "Item": + # 检查是否为源头 Item(没有入边) + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,检查是否有 init_inputs + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 有 init_inputs,需要暴露这些参数 + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + # 处理完后跳过后续的通用逻辑 + continue + + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 为每个 init_input 值创建一个信息条目(不包含 source_node 和 parameter 信息) + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + + for node in scenario.nodes.values(): + if node.is_revealed: + # Tools: 只显示基本信息,提示可以 investigate 查看详细接口 + if node.type == "Tool": + tool_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Tool", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the tool's detailed interface information for calling" + } + # 只在 name 非空时添加 + # if node.name: + # tool_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_info["description"] = node.description + + available_entities.append(tool_info) + + # Items: 只显示基本信息,提示可以 investigate 查看内容 + elif node.type == "Item": + item_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Item", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the item's content" + } + # 只在 name 非空时添加 + # if node.name: + # item_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + item_info["description"] = node.description + + available_entities.append(item_info) + + return { + "narrative": scenario.intro_narrative, + "available_entities": available_entities, # 使用统一的实体列表 + "available_information": available_information, # 可用的初始信息(只包含 init_inputs) + "win_node_id": scenario.win_node_id # 胜利节点ID,让模型知道需要关注哪个节点 + } + +@app.post("/env/reset") +def reset_case(case_id: str = None, case_file_path: str = None, session_id: str = None): + """Loads a specific case from file and resets it. + + Args: + case_id: Optional case ID for resetting an existing case + case_file_path: Path to case file for loading a new case + session_id: Optional session ID to ensure isolation between concurrent evaluations + """ + logger.info(f"Reset request - case_id: {case_id}, case_file_path: {case_file_path}, session_id: {session_id}") + STATS["case_loads"] += 1 + + if case_file_path: + if not os.path.exists(case_file_path): + logger.error(f"Case file not found: {case_file_path}") + raise HTTPException(status_code=404, detail=f"File not found: {case_file_path}") + try: + with open(case_file_path, "r", encoding="utf-8") as f: + file_data = json.load(f) + + # 转换格式:从 DAG executor 生成的格式转换为 GraphScenario 格式 + # 1. 提取 metadata + metadata = file_data.get('metadata', {}) + + # 2. 生成 case_id, title, intro_narrative + # 【修复】为每个评测会话生成唯一的 case_id,防止并发评测时状态污染 + base_name = os.path.basename(case_file_path).replace('.json', '').replace('_full', '').replace('_full2', '') + + if session_id: + # 如果提供了 session_id,使用它来确保唯一性 + case_id = f"{base_name}_{session_id}" + else: + # 否则使用时间戳和随机数确保唯一性 + unique_suffix = f"{int(time.time() * 1000)}_{random.randint(1000, 9999)}" + case_id = f"{base_name}_{unique_suffix}" + + file_data['case_id'] = case_id + logger.info(f"Generated unique case_id: {case_id} (base: {base_name}, session: {session_id})") + + if 'title' not in file_data: + file_data['title'] = f"Escape Room: {file_data['case_id']}" + + if 'intro_narrative' not in file_data: # 目前的json文件中已经有了intro_narrative字段,不会使用下面一行的内容,而是使用每个评测问题的json文件中的对应字段 + 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]".' + + # 3. 转换 nodes 列表为字典(DAG executor 生成的文件中 nodes 是列表格式) + nodes_dict = {} + for node_data in file_data['nodes']: + nodes_dict[node_data['id']] = node_data # 这里的id是template_id之后可能添加一个后缀 + file_data['nodes'] = nodes_dict # 把列表转成一个字典 + + # 4. 添加缺失的字段 + if 'difficulty' not in file_data: + file_data['difficulty'] = metadata.get('total_nodes', 5) + + if 'win_node_id' not in file_data: + file_data['win_node_id'] = metadata.get('win_node_id', '') + + scenario = GraphScenario(**file_data) + + # Extract raw nodes data for template_id access + # nodes 已经在上面转换为字典格式 + raw_nodes_data = file_data.get('nodes', {}) + RAW_NODES_DATA[scenario.case_id] = raw_nodes_data + + # Store metadata for initial values access + FILE_METADATA[scenario.case_id] = metadata + + logger.info(f"Successfully parsed case file: {scenario.case_id}, nodes: {len(scenario.nodes)}, edges: {len(scenario.edges)}") + except Exception as e: + logger.error(f"Failed to load case file: {str(e)}", exc_info=True) + raise HTTPException(status_code=500, detail=f"Failed to load case file: {str(e)}") + + # Initialize node state and load values + _initialize_node_values(scenario, raw_nodes_data, metadata) + + SCENARIOS[scenario.case_id] = scenario + simulator = ToolSimulator() + SIMULATORS[scenario.case_id] = simulator + + 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'])}") + + # 生成初始观察信息(进入密室后看到的环境) + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + ''' + initial_observation的格式: + { + "narrative": scenario.intro_narrative, + "available_entities": available_entities # 使用统一的实体列表 + "available_information": available_information # 可用的初始信息(只包含 init_inputs) + } + ''' + + return { + "ok": True, + "message": f"Case loaded from {case_file_path}", + "case_id": scenario.case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果没有提供 case_file_path,但提供了 case_id,则尝试从内存重置 + if case_id and case_id in SCENARIOS: + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + metadata = FILE_METADATA.get(case_id, {}) + + # Reset dynamic fields and re-apply progressive reveal + # 重新初始化节点状态(包括渐进式暴露) + _initialize_node_values(scenario, raw_nodes_data, metadata) + + 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'])}") + + # 生成初始观察信息 + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + + return { + "ok": True, + "message": f"Case {case_id} reset.", + "case_id": case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果既没有 case_file_path,也没有在内存中找到,返回错误 + raise HTTPException( + status_code=400, + detail="Must provide case_file_path to load a new case, or use case_id to reset an existing case." + ) + +class InvestigateRequest(BaseModel): + node_id: str + +@app.post("/env/{case_id}/investigate") +def investigate(case_id: str, req: InvestigateRequest): + """ + Investigates a Tool or Item to reveal detailed information. + + - For Tools: Returns detailed interface information (inputs/outputs) needed to call the tool + - For Items: Returns content value and triggers hidden item drops + """ + logger.info(f"Investigate request - case_id: {case_id}, node_id: {req.node_id}") + STATS["investigates"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + node = scenario.nodes[req.node_id] + + if not node.is_revealed: + logger.warning(f"Attempt to investigate hidden node: {req.node_id}") + return {"ok": False, "error": "Node is not visible yet."} + + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + newly_revealed = [] + + # 处理 Tool 的 investigate + if node.type == "Tool": + logger.info(f"Investigating tool: {req.node_id}") + + # 返回工具的详细接口信息 + # id 字段使用 node.id(节点唯一标识),agent 用这个字段识别和调用具体的节点 + # template_id 是工具类型标识符,Agent 内部用于判断工具特性(如 terminal 类工具参数可选) + # 注意:只过滤输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口),这些端口仅用于控制掉落,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + # 【端口上游依赖提示 & 初始值直接给出】 + # 针对参数语义模糊(全为数字类型)的工具,在 investigate 返回信息中标注 + # 哪个输入端口来自哪个上游节点(upstream_from)。 + # 对于所有工具:若该节点不是纯源头节点(有任意数据流入边), + # 且某个端口没有上游入边(值来自初始可见参数),则直接给出该端口的 golden input 值。 + AMBIGUOUS_TOOLS = { + "num_base_convert", "calc_modexp", "calc_modexp_int", + "calc_inv_mod", "calc_inv_mod_int", "crypto_rsa_decrypt_hex", "geo_haversine" + } + # Terminal 类工具自带参数对错反馈机制,玩家/模型可自行试错, + # 无需在 investigate 时直接暴露 init_value + SELF_FEEDBACK_TOOLS = { + "terminal_1", "terminal_2", + "Logic Terminal", "Math Terminal", "Encryption Terminal", "Sequence Terminal" + } + _template_id_for_hint = raw_nodes_data.get(node.id, {}).get("template_id", "") + # 构建数据流入边映射(对所有工具):{target_port -> (source_node_id, source_port)} + _upstream_map = {} + for _edge in scenario.edges: + if (_edge.target_id == node.id + and _edge.connection_type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM] + and _edge.target_port is not None): + _upstream_map[_edge.target_port] = (_edge.source_id, _edge.source_port) + # 判断该节点是否有任意数据流入边(即不是纯源头节点) + _has_any_upstream = len(_upstream_map) > 0 + # 判断该节点是否有任意入边(包括 ITEM/HIDDEN_ITEM 掉落边) + # 有任意入边(含掉落边)但无数据流入边的节点,其输入来自初始可见参数,应直接给出 + _has_any_edge = any(_edge.target_id == node.id for _edge in scenario.edges) + # 构建 inputs 列表 + _inputs_list = [] + for p in node.inputs: + if p.type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + continue + port_dict = {"name": p.name, "type": p.type, "description": p.description} + if p.name in _upstream_map: + # 该端口有上游数据流依赖,且属于语义模糊工具 → 标注来源 + if _template_id_for_hint in AMBIGUOUS_TOOLS: + src_node_id, src_port = _upstream_map[p.name] + port_dict["upstream_from"] = f"{src_node_id}.{src_port}" if src_port else src_node_id + elif _has_any_edge and _template_id_for_hint not in SELF_FEEDBACK_TOOLS: + # 该节点有任意入边,但此端口没有数据流入边 → 值来自初始可见参数,直接给出 + # 排除自带反馈机制的 terminal 类工具(它们通过执行结果反馈对错,无需提前暴露参数值) + golden_val = node.golden_input_values.get(p.name) + if golden_val is not None: + port_dict["init_value"] = golden_val + _inputs_list.append(port_dict) + + tool_details = { + "id": node.id, # 节点 ID,用于唯一标识和调用这个具体节点 + "type": "Tool", + "inputs": _inputs_list, + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id 用于 Agent 内部判断工具类型(不会展示给被测模型) + if node.id in raw_nodes_data: + template_id = raw_nodes_data[node.id].get('template_id') + if template_id: + tool_details["_template_id"] = template_id # 使用下划线前缀标记为内部字段 + + # 只在 name 非空时添加 + # if node.name: + # tool_details["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_details["description"] = node.description + + # 添加 narrative 字段(如果存在) + if node.id in raw_nodes_data: + narrative = raw_nodes_data[node.id].get('narrative') + if narrative: + tool_details['narrative'] = narrative + + # 不再返回 init_values,避免泄漏答案 + # investigate 只应该返回工具的接口定义,不应该暴露初始值 + + # 【新增】检查该 Tool 是否有待触发的 HIDDEN_ITEM 掉落 + # 如果该工具已按照 golden_input 正确执行,且有 HIDDEN_ITEM 输出边,则触发掉落 + if node.has_hidden_item_ready: + logger.info(f"Tool has HIDDEN_ITEM ready - triggering passive drop for: {req.node_id}") + + # 遍历该工具的所有 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + # 重置标志,已经触发过了,避免重复 + node.has_hidden_item_ready = False + + logger.info(f"Tool investigation successful - node: {req.node_id}, revealed: {len(newly_revealed)}") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Tool", + "details": tool_details + } + + # 如果有新掉落的节点,添加到响应中 + if newly_revealed: + result["newly_revealed"] = newly_revealed + + return result + + # 处理 Item 的 investigate + elif node.type == "Item": + logger.info(f"Investigating item: {req.node_id}") + + # 【第一步】检查该 Item 是否有需要参数的输入端口 + # 如果有,且尚未通过 use_item 验证,则不返回内容,只返回参数要求 + required_inputs = [] + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + inputs_info = raw_node.get('inputs', []) + required_inputs = [ + { + "name": inp.get("name"), + "type": inp.get("type"), + "description": inp.get("description", "") + } + for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + # 如果有 required_inputs 且尚未通过 use_item 验证(if_success == False) + # 则不返回内容,只返回参数要求提示 + if required_inputs and not node.if_success: + logger.info(f"Item has required inputs and not yet unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "required_inputs": required_inputs + } + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + param_names = ', '.join([inp['name'] for inp in required_inputs]) + 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}" + + return result + + # 【新增】如果有 required_inputs 且已经通过 use_item 验证(if_success == True) + # 则返回提示:该节点已经被成功解决 + if required_inputs and node.if_success: + logger.info(f"Item has required inputs and already unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "message": "This item has already been successfully unlocked by you." + } + return result + + # 【第二步】该 Item 没有 required_inputs 或已通过验证,返回内容 + # 1. 返回 Item 的 golden_output_values(即 Item 的内容) + # 注意:某些 Item 仅用于触发 HIDDEN_ITEM 掉落,没有实际内容 + has_actual_content = bool(node.golden_output_values) or node.content is not None + content = node.golden_output_values if node.golden_output_values else node.content + + # 【关键】将 golden_output_values 追加到 actual_outputs_history,标记该 Item 已被 investigate + # 这样在渐进式暴露时,这些值才会被加入可见值集合 + # 即使是空字典(仅触发 HIDDEN_ITEM 的 Item),也要记录,以便渐进式暴露逻辑知道该 Item 已被调查 + if node.golden_output_values is not None: + node.actual_outputs_history.append(dict(node.golden_output_values)) + + # 2. Trigger Hidden Item Drops (Passive Drop) + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + logger.info(f"Item investigation successful - node: {req.node_id}, has_content: {has_actual_content}, revealed: {len(newly_revealed)}") + + # 【渐进式暴露】旧机制(基于 golden_input)已禁用 + # 现在完全由 ITEM/HIDDEN_ITEM 边触发控制节点可见性 + # 上面的 HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, node.golden_output_values or {}, node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # logger.info(f"Progressive reveal after Item investigate: {len(progressive_revealed)} nodes now ready") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Item" + } + + # 只在有实际内容时才添加 content 字段 + # 对于仅触发 HIDDEN_ITEM 掉落的 Item,不返回 content 字段,避免返回 None 或空字典让模型困惑 + if has_actual_content: + result["content"] = content + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型通过 investigate 获得内容后,需要自己识别这是否是胜利字符串 + + return result + + else: + logger.warning(f"Attempt to investigate unknown node type: {req.node_id} (type: {node.type})") + return {"ok": False, "error": f"Cannot investigate node type: {node.type}"} + +class ToolCallRequest(BaseModel): + node_id: str # 使用 node_id 精确指定要调用的节点 + arguments: Dict[str, Any] + +@app.post("/env/{case_id}/tool_call") +def tool_call(case_id: str, req: ToolCallRequest): + """Executes a tool and triggers item drops.""" + logger.info(f"Tool call request - case_id: {case_id}, node_id: {req.node_id}, args: {list(req.arguments.keys())}") + STATS["tool_calls"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + + # 通过 node_id 精确查找节点 + node_id = req.node_id + if node_id not in scenario.nodes: + logger.error(f"Node not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + tool_node = scenario.nodes[node_id] + + if not tool_node: + logger.error(f"Tool not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Tool not found") + + if not tool_node.is_revealed: + logger.warning(f"Attempt to call hidden tool: {node_id}") + return {"ok": False, "error": "Tool is not visible yet."} + + if tool_node.type != "Tool": + logger.warning(f"Attempt to call non-tool node: {node_id} (type: {tool_node.type})") + return {"ok": False, "error": "Only tools can be called."} + + # 1. Execute Tool (Real Execution via Simulator) + simulator = SIMULATORS[case_id] + + # Get tool name from template_id if available, otherwise use node name + tool_name = tool_node.name + if case_id in RAW_NODES_DATA and node_id in RAW_NODES_DATA[case_id]: + template_id = RAW_NODES_DATA[case_id][node_id].get('template_id') + if template_id: + tool_name = template_id + + # 文件处理工具和 Terminal 需要验证输入并返回预先计算的输出 + # 传递节点的实际输入输出值(从 DAG 执行后填充的数据) + tool_arguments = dict(req.arguments) # Make a copy + + # 传递节点的 golden values(从 JSON 的 inputs[].value 和 outputs[].value 加载) + # 用于在评测阶段验证被测模型传入的参数是否正确 + if tool_node.golden_input_values: + tool_arguments['_golden_inputs'] = tool_node.golden_input_values + if tool_node.golden_output_values: + tool_arguments['_golden_outputs'] = tool_node.golden_output_values + + logger.debug(f"Executing tool {tool_name} (node: {tool_node.name}) with args {tool_arguments}") + + try: + output_values = simulator.execute(tool_name, tool_arguments) + logger.info(f"Tool invoked - {tool_name}: {list(output_values.keys())}") + except Exception as e: + logger.error(f"Tool execution failed - {tool_name}: {str(e)}", exc_info=True) + return {"ok": False, "error": f"Tool execution failed: {str(e)}"} + + # 检查验证结果(精细化错误反馈) + validation = output_values.pop("_validation", {"valid": True}) + + if not validation["valid"]: + # 根据错误类型构造友好的错误消息 + error_type = validation.get("error_type") + + if error_type == "missing_required": + missing = validation.get("missing_params", []) + error_msg = f"Error: Missing required parameters {', '.join(missing)}" + + elif error_type == "type_error": + param = validation.get("param_name") + message = validation.get("message", "Parameter type error") + error_msg = f"Error: {message}" + + elif error_type == "incomplete_optional": + provided = validation.get("provided_params", []) + missing = validation.get("missing_params", []) + error_msg = ( + f"Hint: You provided some parameters ({', '.join(provided)}), " + f"but may also need: {', '.join(missing)}.\n" + f"Trying to provide these parameters together might yield better results." + ) + + elif error_type == "value_mismatch": + param = validation.get("param_name") + hint = validation.get("hint", "Parameter value may be incorrect") + error_msg = f"Hint: {hint}.\nPlease check if this parameter value meets the requirements." + + else: + error_msg = validation.get("hint") or validation.get("message", "Parameter validation failed") + + logger.info(f"Tool validation failed - {tool_name}: {error_type}") + return { + "ok": False, + "error": error_msg, + "error_type": error_type + } + + # Simulate success + tool_node.if_success = True + + # 【关键】将本次执行的输出值追加到历史列表(用于渐进式暴露判断) + # 每次调用都会记录,不会覆盖之前的执行结果 + tool_node.actual_outputs_history.append(dict(output_values)) + + # 2. 检查是否应该触发掉落(只有输入参数正确时才掉落) + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, tool_node.golden_input_values) + + newly_revealed = [] + investigate_hints = [] # 提示模型哪些节点可以 investigate 来发现隐藏内容 + + if inputs_match_golden: + logger.info(f"✓ Tool inputs match golden - node: {node_id}, triggering drops") + + # 检查该工具是否有 ITEM 或 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == tool_node.id: + target_node = scenario.nodes[edge.target_id] + + # ITEM 边:立即掉落(主动掉落) + if edge.connection_type == InterfaceType.ITEM: + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from {node_id})") + + # HIDDEN_ITEM 边:不立即掉落,标记并提示(被动掉落) + elif edge.connection_type == InterfaceType.HIDDEN_ITEM: + # 标记该工具有待触发的 HIDDEN_ITEM 掉落 + tool_node.has_hidden_item_ready = True + + # 提示模型可以 investigate 这个工具来发现隐藏内容 + hint_info = { + "tool_id": tool_node.id, + "hint": f"Tool '{tool_node.id}' seems to hide something, try investigating it to discover more information" + } + # if tool_node.name: + # hint_info["tool_name"] = tool_node.name + + investigate_hints.append(hint_info) + logger.info(f"HIDDEN_ITEM ready: {tool_node.id} -> {target_node.id} (will drop on investigate)") + else: + logger.info(f"✗ Tool inputs do NOT match golden - node: {node_id}, no drops triggered") + + response = { + "ok": True, + "message": "Tool invoked", + "output_values": output_values # Return raw outputs to Agent + } + + # 【新增】对源头节点进行参数验证反馈 + # 源头节点:没有数据流入边的节点,这些节点的参数需要模型自己推理 + # 验证模型使用的参数是否正确,并提供明确的反馈 + if _is_source_node(node_id, scenario) and tool_node.golden_input_values: + validation_feedback = _get_parameter_validation_feedback(req.arguments, tool_node.golden_input_values) + + if validation_feedback["all_correct"]: + # 用户提交了全部 golden 参数且全部正确 + response["parameter_feedback"] = { + "status": "correct", + "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." + } + logger.info(f"✓ Source node parameters all correct - node: {node_id}") + elif validation_feedback["incorrect_params"]: + # 有提交了但值错误的参数,只对这些参数给出反馈 + incorrect_list = [] + for param_name in validation_feedback["incorrect_params"]: + incorrect_list.append(f" - Parameter '{param_name}' is incorrect") + + correct_info = "" + if validation_feedback["correct_params"]: + correct_info = f"\n✓ Correct parameters: {', '.join(validation_feedback['correct_params'])}" + + response["parameter_feedback"] = { + "status": "incorrect", + "message": ( + f"⚠️ Some parameters are incorrect:\n" + + "\n".join(incorrect_list) + + correct_info + + 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." + ), + "incorrect_params": validation_feedback["incorrect_params"], + "correct_params": validation_feedback["correct_params"] + } + logger.info(f"✗ Source node parameters incorrect - node: {node_id}, incorrect: {validation_feedback['incorrect_params']}") + # else: 部分提交且全部正确 → 不给任何 parameter_feedback,避免对未提交的参数发表意见 + + # 检查工具调用是否完全正确(输出与 golden outputs 匹配) + # 用于给模型正向反馈,让它知道这个工具已经正确调用过,避免重复调用 + # 注意:只有当输出完全匹配时才标记为 correct,不会在错误时提供具体错误信息 + # if tool_node.golden_output_values and output_values: + # is_correct = True + # for port_name, expected_value in tool_node.golden_output_values.items(): + # actual_value = output_values.get(port_name) + # if str(actual_value) != str(expected_value): + # is_correct = False + # break + + # if is_correct: + # response["tool_call_correct"] = True + # logger.info(f"✓ Tool called with correct result - node: {node_id}") + + # 只在有新内容掉落时才返回 newly_revealed + if newly_revealed: + response["newly_revealed"] = newly_revealed + + # 添加 investigate 提示(对于有待触发 HIDDEN_ITEM 掉落的工具) + if investigate_hints: + response["investigate_hints"] = investigate_hints + + # 3. 渐进式暴露机制 - 现在完全由 ITEM/HIDDEN_ITEM 边控制 + # 旧机制(基于 golden_input 检查)已被禁用 + # 新机制中,节点的可见性只由 ITEM/HIDDEN_ITEM 边触发决定 + # 上面的 ITEM/HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, output_values, tool_node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # response["newly_revealed"] = newly_revealed + # logger.info(f"Progressive reveal: {len(progressive_revealed)} nodes now ready") + + # Check if this is the win node + if node_id == scenario.win_node_id: + # 验证输出值是否等于预期的胜利值 + # 从节点的 golden_output_values 中获取预期值(在 _initialize_node_values 时从 JSON 加载) + expected_outputs = tool_node.golden_output_values + + # 检查实际输出是否与预期输出匹配 + is_correct = False + victory_string = None + mismatch_info = [] + + if expected_outputs and output_values: + # 检查每个预期输出端口的值是否匹配 + is_correct = True + for port_name, expected_value in expected_outputs.items(): + actual_value = output_values.get(port_name) + if actual_value != expected_value: + is_correct = False + mismatch_info.append(f"Port '{port_name}': expected '{expected_value}', actual '{actual_value}'") + logger.warning(f"Win node output mismatch - port: {port_name}, expected: {expected_value}, actual: {actual_value}") + + # 如果所有输出都匹配,使用第一个输出作为胜利字符串 + if is_correct and output_values: + victory_string = list(output_values.values())[0] + else: + logger.warning(f"Win node called but missing output values - expected: {expected_outputs}, actual: {output_values}") + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型调用工具获得输出后,需要自己识别这是否是胜利字符串并提交 + if is_correct: + logger.info(f"🎯 Win node called with correct output - case: {case_id}, node: {node_id}, victory: {victory_string}") + else: + logger.info(f"❌ Win node called with incorrect output - case: {case_id}, node: {node_id}") + + return response + +class UseItemRequest(BaseModel): + node_id: str = Field(..., description="The ID of the Item node to use (must be Item type)") + arguments: Dict[str, Any] = Field(default_factory=dict, description="Input arguments to provide to the item") + +@app.post("/env/{case_id}/use_item") +def use_item(case_id: str, req: UseItemRequest): + """ + Use an Item node by providing input arguments. + + This is specifically for Item nodes that require parameters to be "unlocked" or "activated", + such as containers that need a password/fingerprint. + + - Validates that the node is of type Item + - Checks if provided arguments match the item's golden_input_values + - If match: triggers ITEM-type edge drops and returns the item's content + - If not match: returns error message + """ + logger.info(f"Use item request - case_id: {case_id}, node_id: {req.node_id}, args: {req.arguments}") + STATS["use_items"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + item_node = scenario.nodes[req.node_id] + + if not item_node.is_revealed: + logger.warning(f"Attempt to use hidden item: {req.node_id}") + return {"ok": False, "error": "Item is not visible yet."} + + if item_node.type != "Item": + logger.warning(f"Attempt to use non-item node: {req.node_id} (type: {item_node.type})") + return {"ok": False, "error": "Only Item nodes can be used with use_item. Tools should be called with tool_call."} + + # 【新增】检查该 Item 是否已经被成功解锁 + # 如果已经被正确使用过,直接返回成功提示 + if item_node.if_success: + logger.info(f"Item already unlocked, returning success message: {req.node_id}") + return { + "ok": True, + "message": "This item has already been successfully unlocked by you." + } + + # 检查该 Item 是否真的需要通过 use_item 提供参数 + # 只有当 Item 有非 Item/Hidden_Item 类型的输入时,才应该使用 use_item + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + non_hidden_inputs = [ + inp for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + if not non_hidden_inputs: + # 该 Item 不需要参数,应该只使用 investigate + logger.warning(f"Attempt to use_item on a node that doesn't require parameters: {req.node_id}") + return { + "ok": False, + "error": "This item does not require parameters. Please use investigate to examine the item directly." + } + + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, item_node.golden_input_values) + + if not inputs_match_golden: + logger.info(f"✗ Item inputs do NOT match golden - node: {req.node_id}") + # 提供更详细的错误信息,帮助 Agent 理解问题 + # 只显示非 Item/Hidden_Item 类型的参数(Hidden_Item 由系统自动处理) + expected_params = [] + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + expected_params = [ + inp.get("name") for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + provided_params = list(req.arguments.keys()) if req.arguments else [] + + # 检查参数名是否匹配 + if set(expected_params) == set(provided_params): + # 参数名正确但值不匹配 - 不泄漏正确的值 + error_msg = f"Parameter names are correct, but the parameter values are incorrect. Please try using different parameter values." + else: + error_msg = f"Parameter names do not match. Expected parameter names: {expected_params}, you provided: {provided_params}." + + return { + "ok": False, + "error": error_msg + } + + logger.info(f"✓ Item inputs match golden - node: {req.node_id}, activating item") + + # 标记该 Item 已被正确使用 + item_node.if_success = True + + # 将 golden_output_values 追加到 actual_outputs_history + if item_node.golden_output_values: + item_node.actual_outputs_history.append(dict(item_node.golden_output_values)) + + # 触发 ITEM 类型边的掉落 + newly_revealed = [] + for edge in scenario.edges: + if edge.source_id == item_node.id and edge.connection_type == InterfaceType.ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from use_item on {req.node_id})") + + # 检查是否为 Win Node + win_node_id = scenario.win_node_id + is_win_node = (req.node_id == win_node_id) + + # 构建返回结果 + result = { + "ok": True, + "message": "Item used successfully.", + "content": item_node.golden_output_values if item_node.golden_output_values else None + } + + # 获取 narrative(如果存在) + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + narrative = raw_nodes_data[req.node_id].get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 如果是 Win Node,只记录日志 + if is_win_node: + logger.info(f"Win node (Item) unlocked via use_item - case: {case_id}, node: {req.node_id}") + + return result + + +class SubmitAnswerRequest(BaseModel): + answer: str = Field(..., description="The victory string to submit") + +@app.post("/env/{case_id}/submit_answer") +def submit_answer(case_id: str, req: SubmitAnswerRequest): + """ + 提交答案接口 + 被测模型在获得胜利字符串提示后,需要调用此接口提交答案 + """ + logger.info(f"Submit answer request - case_id: {case_id}, answer: {req.answer}") + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + + # 获取 win_node 的 golden_output_values + if not scenario.win_node_id: + logger.error(f"No win node defined for case: {case_id}") + return { + "ok": False, + "error": "This case has no victory node defined" + } + + win_node = scenario.nodes.get(scenario.win_node_id) + if not win_node: + logger.error(f"Win node not found: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node does not exist" + } + + # 获取正确的胜利字符串(取第一个 golden_output_value) + if win_node.golden_output_values: + correct_answer = list(win_node.golden_output_values.values())[0] + else: + logger.error(f"Win node has no golden_output_values: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node has no correct answer" + } + + # 验证提交的答案 + if req.answer == correct_answer: + logger.info(f"🎉 CORRECT ANSWER SUBMITTED - case: {case_id}, answer: {req.answer}") + return { + "ok": True, + "is_win": True, + "victory_message": f"🎉 Congratulations on successfully escaping the room! Your answer is correct: {req.answer}" + } + else: + logger.info(f"❌ INCORRECT ANSWER SUBMITTED - case: {case_id}, submitted: {req.answer}, correct: {correct_answer}") + return { + "ok": True, + "is_win": False, + "error": f"The submitted answer is incorrect. You submitted: {req.answer}" + } + +if __name__ == "__main__": + + uvicorn.run(app, host="0.0.0.0", port=8000) \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-c520de06/environment/puzzle/upstream/simulator.py b/tasks/agentescape-25-skeleton-c520de06/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-25-skeleton-c520de06/environment/puzzle/upstream/simulator.py @@ -0,0 +1,2911 @@ +import hashlib +import hmac +import base64 +import binascii +import zlib +import json +import uuid +import math +import re +from typing import Dict, Any, List + +class ToolSimulator: + def __init__(self): + """工具模拟器 + + 文件处理工具(zip_unzip, zip_unzip_file, zip_unzip_item, json_get, csv_query, + regex_search, graph_shortest_path)不需要真实文件系统。 + 这些工具只验证输入参数,然后返回预先初始化好的 golden_outputs。 + """ + self.tool_map = { + # 数论 + "calc_bigmul": self.calc_bigmul, + "calc_modexp": self.calc_modexp, + "calc_modexp_int": self.calc_modexp_int, + "calc_gcd": self.calc_gcd, + "calc_gcd_int": self.calc_gcd_int, + "calc_inv_mod": self.calc_inv_mod, + "calc_inv_mod_int": self.calc_inv_mod_int, + + # 哈希 + "hash_sha256": self.hash_sha256, + "hash_md5": self.hash_md5, + "hmac_sha256": self.hmac_sha256, + + # 编码 + "base64_decode": self.base64_decode, + "base64_encode": self.base64_encode, + "hex_decode": self.hex_decode, + "hex_encode": self.hex_encode, + "zlib_inflate": self.zlib_inflate, + "zlib_deflate": self.zlib_deflate, + + # 文件 + "zip_unzip": self.zip_unzip, + "zip_unzip_file": self.zip_unzip_file, + "zip_unzip_item": self.zip_unzip_item, + "regex_search": self.regex_search, + "json_get": self.json_get, + "csv_query": self.csv_query, + "code_py_exec": self.code_py_exec, + + # 图 + "graph_shortest_path": self.graph_shortest_path, + + # 加解密 (简化模拟) + "crypto_aes_cbc_decrypt": self.crypto_aes_cbc_decrypt, + "crypto_rsa_decrypt_hex": self.crypto_rsa_decrypt_hex, + + # 其他 + "num_base_convert": self.num_base_convert, + "time_convert": self.time_convert, + "checksum_crc32": self.checksum_crc32, + "geo_haversine": self.geo_haversine, + "otp_totp_generate": self.otp_totp_generate, + "unicode_norm": self.unicode_norm, + "text_bidi_sanitize": self.text_bidi_sanitize, + "text_xor_hex": self.text_xor_hex, + "text_rotN": self.text_rotN, + "luhn_check": self.luhn_check, + "iban_validate": self.iban_validate, + + # 物理 + "matter_synthesizer": self.matter_synthesizer, + + # 终端机 + "terminal_1": self.terminal_1, + "terminal_2": self.terminal_2, + "Logic Terminal": self.logic_terminal, + "Math Terminal": self.math_terminal, + "Encryption Terminal": self.crypt_terminal, + "Sequence Terminal": self.sequence_terminal + } + + def execute(self, tool_name: str, inputs: Dict[str, Any]) -> Dict[str, Any]: + if tool_name not in self.tool_map: + # Fallback for unknown tools: return dummy outputs based on expected output types + # This should ideally not happen if all tools are implemented + return {} + + try: + return self.tool_map[tool_name](inputs) + except Exception as e: + print(f"Error executing {tool_name}: {e}") + # Return empty or error indication? For generation, we might want to fail hard or return dummy. + # For now, return dummy to keep flow going, but log error. + return {} + + # --- Implementations --- + + def calc_bigmul(self, inputs): + # Check if required parameters are present + if "a" not in inputs or "b" not in inputs: + raise ValueError("Missing required parameters 'a' and/or 'b'") + + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + return {"product": str(a * b)} + except (ValueError, TypeError) as e: + raise ValueError(f"Failed to convert parameters to integers: {str(e)}") + + def calc_modexp(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + try: + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if isinstance(base, str): + base = int(base) + elif not isinstance(base, int): + raise ValueError("Parameter 'base' must be a string or integer") + + if isinstance(exp, str): + exp = int(exp) + elif not isinstance(exp, int): + raise ValueError("Parameter 'exp' must be a string or integer") + + if isinstance(mod, str): + mod = int(mod) + elif not isinstance(mod, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": str(pow(base, exp, mod))} + + def calc_modexp_int(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["base"], int): + raise ValueError("Parameter 'base' must be an integer") + if not isinstance(inputs["exp"], int): + raise ValueError("Parameter 'exp' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": pow(base, exp, mod)} + + def calc_gcd(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + # 计算 GCD 并返回字符串格式(符合 Big_Int 输出类型) + result = math.gcd(a, b) + return {"gcd": str(result)} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def calc_gcd_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["b"], int): + raise ValueError("Parameter 'b' must be an integer") + + # 获取参数 + a = inputs["a"] + b = inputs["b"] + + return {"gcd": math.gcd(a, b)} + + def calc_inv_mod(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + m = inputs["mod"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(m, str): + m = int(m) + elif not isinstance(m, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": str(pow(a, -1, m))} + except ValueError as e: + # 模逆不存在时,返回一个特殊值(用于数据传递) + # 在 DAG 生成阶段,这允许数据流继续 + return {"inv": str(a)} + + def calc_inv_mod_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + a = inputs["a"] + m = inputs["mod"] + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": pow(a, -1, m)} + except ValueError as e: + raise ValueError(f"Modular inverse does not exist: {str(e)}") + + def hash_sha256(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.sha256(text.encode()).hexdigest()} + + def hash_md5(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.md5(text.encode()).hexdigest()} + + def hmac_sha256(self, inputs): + # 参数检查 + if "hex_key" not in inputs: + raise ValueError("Missing required parameter: hex_key") + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["hex_key"], str): + raise ValueError("Parameter 'hex_key' must be a string") + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + try: + key = bytes.fromhex(inputs["hex_key"]) + text = inputs["text"].encode() + return {"hex": hmac.new(key, text, hashlib.sha256).hexdigest()} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def base64_decode(self, inputs): + # 参数检查 + if "data" not in inputs: + raise ValueError("Missing required parameter: data") + + # 类型检查 + if not isinstance(inputs["data"], str): + raise ValueError("Parameter 'data' must be a string") + + data = inputs["data"] + try: + return {"bytes_hex": binascii.hexlify(base64.b64decode(data)).decode()} + except Exception as e: + raise ValueError(f"Base64 decode error: {str(e)}") + + def base64_encode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"b64": base64.b64encode(bytes.fromhex(hex_data)).decode()} + except Exception as e: + raise ValueError(f"Base64 encode error: {str(e)}") + + def hex_decode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"text": bytes.fromhex(hex_data).decode('utf-8', errors='ignore')} + except Exception as e: + raise ValueError(f"Hex decode error: {str(e)}") + + def hex_encode(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + try: + return {"hex": text.encode().hex()} + except Exception as e: + raise ValueError(f"Hex encode error: {str(e)}") + + + # 到此处实现已经更新 + + def zlib_inflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("Parameter 'hex' must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("Missing required parameter: hex") + + try: + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空字符串 + if not hex_data: + raise ValueError("Empty hex string provided") + + # 检查十六进制字符串的有效性 + if len(hex_data) % 2 != 0: + raise ValueError("Hex string must have even length") + + # 检查是否只包含有效的十六进制字符 + if not all(c in '0123456789abcdefABCDEF' for c in hex_data): + raise ValueError("Invalid hex string provided") + + # 尝试解压缩 + return {"text": zlib.decompress(bytes.fromhex(hex_data)).decode('utf-8')} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hex string provided") from e + raise ValueError(f"Invalid zlib data: {e}") from e + except Exception as e: + raise RuntimeError(f"Failed to inflate data: {e}") from e + + def zlib_deflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("Parameter 'text' must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("Missing required parameter: text") + + try: + # 压缩文本 + return {"hex": zlib.compress(text.encode('utf-8')).hex()} + except Exception as e: + raise RuntimeError(f"Failed to deflate data: {e}") from e + + # --- File Operations --- + + def zip_unzip(self, inputs): + """ZIP 解压工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"files": golden_outputs.get("files", "")} + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return {"files": golden_outputs.get("files", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "files" in golden_outputs: + # 验证必需参数 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 检查类型 + if has_zip_id and not isinstance(zip_id, str): + return {"error": "Parameter 'zip_id' must be a string type"} + if has_password and not isinstance(password, str): + return {"error": "Parameter 'password' must be a string type"} + + # 验证输入是否与预期匹配 + if golden_inputs: + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return {"files": golden_outputs["files"]} + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + # 没有golden_inputs但有golden_outputs,直接返回输出 + return {"files": golden_outputs["files"]} + + # 如果没有预期输出,返回空结果 + return {"files": ""} + + def regex_search(self, inputs): + """正则搜索工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"matches": golden_outputs.get("matches", "[]")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "matches" in golden_outputs: + # 提取实际参数 + pattern = inputs.get("pattern") + file_id = inputs.get("file_id") + text = inputs.get("text") + + # 1. 检查必需参数 + if pattern is None: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["pattern"], + "message": "Missing required parameter 'pattern'" + } + } + + # 类型检查 + if not isinstance(pattern, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "pattern", + "message": "Parameter 'pattern' must be a string type" + } + } + if file_id is not None and not isinstance(file_id, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if text is not None and not isinstance(text, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "text", + "message": "Parameter 'text' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合 + provided_params = {} + if pattern is not None: + provided_params["pattern"] = pattern + if file_id is not None: + provided_params["file_id"] = file_id + if text is not None: + provided_params["text"] = text + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数(关键改进) + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_pattern = golden_inputs.get("pattern") + expected_file_id = golden_inputs.get("file_id") + expected_text = golden_inputs.get("text") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_pattern is not None: + if str(pattern) != str(expected_pattern): + incorrect_params.append("pattern") + else: + correct_params.append("pattern") + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_text is not None: + if str(text) != str(expected_text): + incorrect_params.append("text") + else: + correct_params.append("text") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "matches": "[]", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "matches": golden_outputs["matches"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空列表 + return {"matches": "[]"} + + def json_get(self, inputs): + """JSON 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"values": golden_outputs.get("values", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "values" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + jsonpath = inputs.get("jsonpath", "") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if jsonpath is not None and not isinstance(jsonpath, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "jsonpath", + "message": "Parameter 'jsonpath' must be a string type" + } + } + + # 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:jsonpath有默认值"") + provided_params = {} + if file_id is not None: + provided_params["file_id"] = file_id + if jsonpath != "": + provided_params["jsonpath"] = jsonpath + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_jsonpath = golden_inputs.get("jsonpath") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_jsonpath is not None: + if str(jsonpath) != str(expected_jsonpath): + incorrect_params.append("jsonpath") + else: + correct_params.append("jsonpath") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "values": "", + "_validation": validation_info + } + + # 所有验证通过,返回正确输出 + return { + "values": golden_outputs["values"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"values": ""} + + def csv_query(self, inputs): + """CSV 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"rows": golden_outputs.get("rows", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "rows" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + select_columns = inputs.get("select", "") + where_clause = inputs.get("where", "") + + # 1. 检查必需参数 + if file_id is None: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["file_id"], + "message": "Missing required parameter 'file_id'" + } + } + + # 类型检查 + if not isinstance(file_id, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if not isinstance(select_columns, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "select", + "message": "Parameter 'select' must be a string type" + } + } + if not isinstance(where_clause, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "where", + "message": "Parameter 'where' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:select和where有默认值"") + provided_params = {"file_id": file_id} + if select_columns != "": + provided_params["select"] = select_columns + if where_clause != "": + provided_params["where"] = where_clause + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_select = golden_inputs.get("select") + expected_where = golden_inputs.get("where") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_select is not None: + if str(select_columns) != str(expected_select): + incorrect_params.append("select") + else: + correct_params.append("select") + + if expected_where is not None: + if str(where_clause) != str(expected_where): + incorrect_params.append("where") + else: + correct_params.append("where") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "rows": "", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "rows": golden_outputs["rows"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"rows": ""} + + def graph_shortest_path(self, inputs): + """图最短路径工具 + + 如果有 _golden_outputs 或 _init_outputs,验证输入并返回预设输出。 + 否则执行真实的 Dijkstra 算法。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 检查是否在预设模式中(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + if golden_outputs and "path" in golden_outputs: + # 评测阶段但没有 golden_inputs,直接返回 outputs + if not golden_inputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 评测模式:验证输入参数是否匹配 golden 值 + src = inputs.get("src") + dst = inputs.get("dst") + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + + has_src = src is not None and src != "" + has_dst = dst is not None and dst != "" + + # 验证必需参数 + if not has_src or not has_dst: + missing = [] + if not has_src: + missing.append("src") + if not has_dst: + missing.append("dst") + return {"error": "Missing required parameters: " + ", ".join(missing)} + + # 类型检查 + if not isinstance(src, str): + return {"error": "Parameter 'src' must be a string"} + if not isinstance(dst, str): + return {"error": "Parameter 'dst' must be a string"} + + # 验证输入是否匹配期望值 + if golden_inputs: + expected_src = golden_inputs.get("src") + expected_dst = golden_inputs.get("dst") + expected_file_id = golden_inputs.get("file_id") + expected_graph_data = golden_inputs.get("graph_data") + + # 收集验证结果 + incorrect_params = [] + correct_params = [] + + # 检查必需参数是否匹配 + if expected_src is not None: + if str(src) != str(expected_src): + incorrect_params.append("src") + else: + correct_params.append("src") + + if expected_dst is not None: + if str(dst) != str(expected_dst): + incorrect_params.append("dst") + else: + correct_params.append("dst") + + # 检查可选参数(如果在 expected_inputs 中定义了) + if expected_file_id is not None: + if file_id != expected_file_id: + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_graph_data is not None: + if graph_data != expected_graph_data: + incorrect_params.append("graph_data") + else: + correct_params.append("graph_data") + + # 如果有参数不正确,返回详细的反馈 + if incorrect_params: + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 验证通过,返回预设的输出 + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 获取参数(真实执行路径) + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + # Support both src/dst (interface definition) and start/end (original implementation) + start = inputs.get("src") + end = inputs.get("dst") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + raise TypeError("file_id must be a string") + + if graph_data is not None and not isinstance(graph_data, str): + raise TypeError("graph_data must be a string") + + if start is not None and not isinstance(start, str): + raise TypeError("src/start must be a string") + + if end is not None and not isinstance(end, str): + raise TypeError("dst/end must be a string") + + # 检查必需参数 + if file_id is None and graph_data is None: + raise ValueError("Either file_id or graph_data must be provided") + + if start is None: + raise ValueError("src/start parameter is required") + + if end is None: + raise ValueError("dst/end parameter is required") + + # Get graph content + content = None + if file_id is not None: + # 尝试从 VFS 获取(如果存在) + if hasattr(self, 'vfs') and file_id in self.vfs: + content = self.vfs[file_id] + else: + # VFS 不存在或文件不在 VFS 中 + # 返回一个默认的空图结果,或者抛出错误提示需要 init_outputs + raise ValueError( + f"File '{file_id}' not found. For tools that require files, " + f"please provide init_outputs in the initial_values." + ) + elif graph_data is not None: + content = graph_data + + if content is None: + content = "{}" + + try: + # Parse graph data + graph = json.loads(content) + + # 类型检查 + if not isinstance(graph, dict): + raise TypeError("Graph data must be a dictionary") + + # If graph is not in the expected format, try to extract adjacency list + if "nodes" in graph and "edges" in graph: + # 验证nodes和edges的类型 + if not isinstance(graph["nodes"], list): + raise TypeError("Nodes must be a list") + + if not isinstance(graph["edges"], list): + raise TypeError("Edges must be a list") + + # Convert from nodes/edges format to adjacency list + adjacency_list = {} + for node in graph["nodes"]: + # 验证node类型 + if not isinstance(node, dict): + raise TypeError("Each node must be a dictionary") + + # Use node ID as key, not the entire node dictionary + node_id = node.get("id", "") + if node_id: + adjacency_list[node_id] = {} + + for edge in graph["edges"]: + # 验证edge类型 + if not isinstance(edge, dict): + raise TypeError("Each edge must be a dictionary") + + u = edge["from"] + v = edge["to"] + weight = edge.get("weight", 1) # Default to unweighted + + # 类型检查 + if not isinstance(u, str): + raise TypeError("Edge 'from' must be a string") + + if not isinstance(v, str): + raise TypeError("Edge 'to' must be a string") + + if not isinstance(weight, (int, float)): + raise TypeError("Edge weight must be a number") + + if u not in adjacency_list: + adjacency_list[u] = {} + if v not in adjacency_list: + adjacency_list[v] = {} + + adjacency_list[u][v] = weight + # If undirected, add reverse edge + if not edge.get("directed", False): + adjacency_list[v][u] = weight + elif isinstance(graph, dict): + # Already in adjacency list format + adjacency_list = graph + + # 验证邻接表结构 + for node, neighbors in adjacency_list.items(): + if not isinstance(neighbors, dict): + raise TypeError("Adjacency list must be a dictionary of dictionaries") + + for neighbor, weight in neighbors.items(): + if not isinstance(weight, (int, float)): + raise TypeError("Edge weights must be numbers") + else: + raise TypeError("Graph data must be a dictionary") + + # 检查起点和终点是否为空 + if not start: + raise ValueError("Start node cannot be empty") + + if not end: + raise ValueError("End node cannot be empty") + + # 检查起点和终点是否在图中 + if start not in adjacency_list: + raise ValueError(f"Start node '{start}' not found in graph") + + if end not in adjacency_list: + raise ValueError(f"End node '{end}' not found in graph") + + # Dijkstra's algorithm implementation + import heapq + + # Initialize distances and previous nodes + distances = {node: float('infinity') for node in adjacency_list} + previous = {node: None for node in adjacency_list} + distances[start] = 0 + + # Priority queue + pq = [(0, start)] + heapq.heapify(pq) + + while pq: + current_dist, current_node = heapq.heappop(pq) + + # If we've reached the end node, we can break early + if current_node == end: + break + + # Nodes can be added multiple times to the priority queue, but we only process them once + if current_dist > distances[current_node]: + continue + + # Explore neighbors + for neighbor, weight in adjacency_list[current_node].items(): + distance = current_dist + weight + + # If a shorter path is found + if distance < distances[neighbor]: + distances[neighbor] = distance + previous[neighbor] = current_node + heapq.heappush(pq, (distance, neighbor)) + + # Reconstruct the shortest path + path = [] + current = end + while current is not None: + path.append(current) + current = previous[current] + path.reverse() # Reverse to get from start to end + + # Check if path exists + if not path or path[0] != start: + return {"path": "[]", "cost": 0} + + return { + "path": json.dumps(path), + "cost": distances[end] + } + except json.JSONDecodeError as e: + raise ValueError(f"Invalid JSON in graph data: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in graph_shortest_path: {str(e)}") + + # --- Crypto (Simplified) --- + def crypto_aes_cbc_decrypt(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 (使用模板中定义的参数名) + hex_cipher = inputs.get("hex_cipher") + hex_key = inputs.get("hex_key") + hex_iv = inputs.get("hex_iv") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + + if hex_key is not None and not isinstance(hex_key, str): + raise TypeError("hex_key must be a string") + + if hex_iv is not None and not isinstance(hex_iv, str): + raise TypeError("hex_iv must be a string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + + if hex_key is None: + raise ValueError("hex_key parameter is required") + + if hex_iv is None: + raise ValueError("hex_iv parameter is required") + + from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes + from cryptography.hazmat.backends import default_backend + from cryptography.hazmat.primitives import padding + + try: + # Convert hex strings to bytes + ciphertext = bytes.fromhex(hex_cipher) + key = bytes.fromhex(hex_key) + iv = bytes.fromhex(hex_iv) + + # Validate key length (AES-128, AES-192, AES-256) + if len(key) not in [16, 24, 32]: + raise ValueError("Invalid key length. Must be 16, 24, or 32 bytes.") + + if len(iv) != 16: + raise ValueError("Invalid IV length. Must be 16 bytes.") + + # Create cipher object + cipher = Cipher( + algorithms.AES(key), + modes.CBC(iv), + backend=default_backend() + ) + + decryptor = cipher.decryptor() + + # Decrypt the ciphertext + padded_plaintext = decryptor.update(ciphertext) + decryptor.finalize() + + # Remove PKCS7 padding + unpadder = padding.PKCS7(128).unpadder() + plaintext = unpadder.update(padded_plaintext) + unpadder.finalize() + + # Return decrypted text + return {"text": plaintext.decode('utf-8', errors='ignore')} + except ValueError as e: + if "non-hexadecimal number found in fromhex()" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher, hex_key, or hex_iv") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in crypto_aes_cbc_decrypt: {str(e)}") + + def crypto_rsa_decrypt_hex(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_cipher = inputs.get("hex_cipher") + n = inputs.get("n") + d = inputs.get("d") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + if n is not None and not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + if d is not None and not isinstance(d, (int, str)): + raise TypeError("d must be an integer or string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + if n is None: + raise ValueError("n parameter is required") + if d is None: + raise ValueError("d parameter is required") + + try: + # Convert parameters to appropriate types + cipher_int = int(hex_cipher, 16) + n_int = int(n) if isinstance(n, str) else n + d_int = int(d) if isinstance(d, str) else d + + # RSA decryption: plaintext = ciphertext^d mod n + plaintext_int = pow(cipher_int, d_int, n_int) + + # Convert result to hex and then to text + plaintext_hex = hex(plaintext_int)[2:] + + # Pad with leading zero if odd length + if len(plaintext_hex) % 2 != 0: + plaintext_hex = '0' + plaintext_hex + + # Convert hex to bytes and then to text + try: + plaintext_bytes = bytes.fromhex(plaintext_hex) + plaintext_text = plaintext_bytes.decode('utf-8', errors='ignore') + except: + # If decoding fails, return hex representation + plaintext_text = plaintext_hex + + return {"text": plaintext_text} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in crypto_rsa_decrypt_hex: {str(e)}") + + # --- Others --- + def num_base_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + s = inputs.get("s") + from_base = inputs.get("from_base") + to_base = inputs.get("to_base") + + # 类型检查 - 接受 str 或 int + if s is not None and not isinstance(s, (str, int)): + raise TypeError("s must be a string or integer") + + if from_base is not None and not isinstance(from_base, (int, str)): + raise TypeError("from_base must be an integer") + + if to_base is not None and not isinstance(to_base, (int, str)): + raise TypeError("to_base must be an integer") + + # 检查必需参数 + if s is None: + raise ValueError("s parameter is required") + + if from_base is None: + raise ValueError("from_base parameter is required") + + if to_base is None: + raise ValueError("to_base parameter is required") + + try: + # Convert to int if needed + from_base = int(from_base) if isinstance(from_base, str) else from_base + to_base = int(to_base) if isinstance(to_base, str) else to_base + s_str = str(s) + + # 验证基数范围 + if from_base < 2 or from_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + if to_base < 2 or to_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + # Convert from source base to decimal + val = int(s_str, from_base) + + # Convert from decimal to target base + if to_base == 10: + result = str(val) + elif to_base == 16: + result = hex(val)[2:] + elif to_base == 8: + result = oct(val)[2:] + elif to_base == 2: + result = bin(val)[2:] + else: + # Generic base conversion for other bases + if val == 0: + result = "0" + else: + digits = "0123456789abcdefghijklmnopqrstuvwxyz" + result = "" + n = abs(val) + while n: + result = digits[n % to_base] + result + n //= to_base + if val < 0: + result = "-" + result + + return {"str": result} + except ValueError as e: + raise ValueError(f"Invalid number format: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in num_base_convert: {str(e)}") + + def time_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iso = inputs.get("iso") + timestamp = inputs.get("timestamp") + datetime_str = inputs.get("datetime") + from_tz = inputs.get("from_tz") + to_tz = inputs.get("to_tz") + format_str = inputs.get("format") + + # 类型检查 + if iso is not None and not isinstance(iso, str): + raise TypeError("iso must be a string") + + if timestamp is not None and not isinstance(timestamp, (str, int, float)): + raise TypeError("timestamp must be a string, integer, or float") + + if datetime_str is not None and not isinstance(datetime_str, str): + raise TypeError("datetime must be a string") + + if from_tz is not None and not isinstance(from_tz, str): + raise TypeError("from_tz must be a string") + + if to_tz is not None and not isinstance(to_tz, str): + raise TypeError("to_tz must be a string") + + if format_str is not None and not isinstance(format_str, str): + raise TypeError("format must be a string") + + # 设置默认值 + if from_tz is None: + from_tz = "UTC" + + if to_tz is None: + to_tz = "UTC" + + import datetime + import pytz + + # 验证时区参数 + try: + if from_tz: + pytz.timezone(from_tz) + if to_tz: + pytz.timezone(to_tz) + except Exception: + raise ValueError("Invalid timezone provided") + + try: + # Parse input time + dt = None + + if iso is not None: + # Parse ISO 8601 format + dt = datetime.datetime.fromisoformat(iso.replace('Z', '+00:00')) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=pytz.UTC) + elif timestamp is not None: + # Parse Unix timestamp + timestamp = float(timestamp) + dt = datetime.datetime.fromtimestamp(timestamp, pytz.UTC) + elif datetime_str is not None: + # Parse datetime string + # Try common formats + formats_to_try = [ + "%Y-%m-%d %H:%M:%S", + "%Y-%m-%d %H:%M:%S.%f", + "%Y-%m-%d", + "%m/%d/%Y %H:%M:%S", + "%m/%d/%Y" + ] + + parse_success = False + for fmt in formats_to_try: + try: + dt = datetime.datetime.strptime(datetime_str, fmt) + dt = pytz.timezone(from_tz).localize(dt) + parse_success = True + break + except ValueError: + continue + + if not parse_success: + raise ValueError("Unable to parse datetime string with common formats") + else: + # 如果没有提供任何时间参数,则使用当前时间 + dt = datetime.datetime.now(pytz.UTC) + except ValueError as e: + raise ValueError(f"Error parsing time input: {str(e)}") + except Exception as e: + raise RuntimeError(f"Unexpected error parsing time input: {str(e)}") + + try: + # Convert timezone + if from_tz != to_tz: + dt = dt.astimezone(pytz.timezone(to_tz)) + + # Format outputs + result = { + "iso": dt.isoformat(), + "timestamp": str(dt.timestamp()), + "datetime": dt.strftime("%Y-%m-%d %H:%M:%S"), + "date": dt.strftime("%Y-%m-%d"), + "time": dt.strftime("%H:%M:%S"), + "timezone": to_tz + } + + # Add custom format if requested + if format_str: + try: + result["formatted"] = dt.strftime(format_str) + except ValueError as e: + raise ValueError(f"Invalid format string: {str(e)}") + + return result + except Exception as e: + raise RuntimeError(f"Error in time_convert: {str(e)}") + + def checksum_crc32(self, inputs): + import zlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("hex must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("hex parameter is required") + + try: + # 验证十六进制字符串 + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空 + if not hex_data: + raise ValueError("hex data cannot be empty") + + # 检查是否为有效的十六进制字符串 + if not all(c in "0123456789abcdefABCDEF" for c in hex_data): + raise ValueError("hex must be a valid hexadecimal string") + + # 检查长度是否为偶数 + if len(hex_data) % 2 != 0: + raise ValueError("hex must have even number of characters") + + val = zlib.crc32(bytes.fromhex(hex_data)) + # 确保 hex 输出是 8 位,前导补 0 + return {"hex": f"{val:08x}", "int": val} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in checksum_crc32: {str(e)}") + + def geo_haversine(self, inputs): + import math + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + lat1 = inputs.get("lat1") + lon1 = inputs.get("lon1") + lat2 = inputs.get("lat2") + lon2 = inputs.get("lon2") + + # 类型检查 + if lat1 is not None and not isinstance(lat1, (int, float, str)): + raise TypeError("lat1 must be a number or string") + if lon1 is not None and not isinstance(lon1, (int, float, str)): + raise TypeError("lon1 must be a number or string") + if lat2 is not None and not isinstance(lat2, (int, float, str)): + raise TypeError("lat2 must be a number or string") + if lon2 is not None and not isinstance(lon2, (int, float, str)): + raise TypeError("lon2 must be a number or string") + + # 检查必需参数 + if lat1 is None: + raise ValueError("lat1 parameter is required") + if lon1 is None: + raise ValueError("lon1 parameter is required") + if lat2 is None: + raise ValueError("lat2 parameter is required") + if lon2 is None: + raise ValueError("lon2 parameter is required") + + try: + # 转换为浮点数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(lat1, str): + lat1 = float(lat1) + elif not isinstance(lat1, (int, float)): + raise TypeError("lat1 must be a number or string") + else: + lat1 = float(lat1) + + if isinstance(lon1, str): + lon1 = float(lon1) + elif not isinstance(lon1, (int, float)): + raise TypeError("lon1 must be a number or string") + else: + lon1 = float(lon1) + + if isinstance(lat2, str): + lat2 = float(lat2) + elif not isinstance(lat2, (int, float)): + raise TypeError("lat2 must be a number or string") + else: + lat2 = float(lat2) + + if isinstance(lon2, str): + lon2 = float(lon2) + elif not isinstance(lon2, (int, float)): + raise TypeError("lon2 must be a number or string") + else: + lon2 = float(lon2) + + # Validate coordinates (approximate range check) + if not (-90 <= lat1 <= 90): + raise ValueError("lat1 must be between -90 and 90") + if not (-90 <= lat2 <= 90): + raise ValueError("lat2 must be between -90 and 90") + if not (-180 <= lon1 <= 180): + raise ValueError("lon1 must be between -180 and 180") + if not (-180 <= lon2 <= 180): + raise ValueError("lon2 must be between -180 and 180") + + # Earth radius in meters + R = 6371000 # Approximate radius of Earth + + # Convert degrees to radians + lat1_rad = math.radians(lat1) + lon1_rad = math.radians(lon1) + lat2_rad = math.radians(lat2) + lon2_rad = math.radians(lon2) + + # Calculate differences + delta_lat = lat2_rad - lat1_rad + delta_lon = lon2_rad - lon1_rad + + # Haversine formula + a = math.sin(delta_lat / 2) ** 2 + \ + math.cos(lat1_rad) * math.cos(lat2_rad) * \ + math.sin(delta_lon / 2) ** 2 + c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) + distance_m = R * c + + # Return distance in meters + return {"meters": round(distance_m, 2)} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in geo_haversine: {str(e)}") + + def otp_totp_generate(self, inputs): + import hmac + import hashlib + import base64 + import time + import struct + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + base32_secret = inputs.get("base32_secret") + step = inputs.get("step", 30) # Default to 30 seconds + digits = inputs.get("digits", 6) # Default to 6 digits + timestamp_iso = inputs.get("timestamp_iso", "") + algo = inputs.get("algo", "sha1") # Default to sha1 as current implementation only supports this + + # 类型检查 + if base32_secret is not None and not isinstance(base32_secret, str): + raise TypeError("base32_secret must be a string") + if not isinstance(step, (int, str)): + raise TypeError("step must be an integer or string") + if not isinstance(digits, (int, str)): + raise TypeError("digits must be an integer or string") + if not isinstance(timestamp_iso, str): + raise TypeError("timestamp_iso must be a string") + if not isinstance(algo, str): + raise TypeError("algo must be a string") + + # 检查必需参数 + if base32_secret is None: + raise ValueError("base32_secret parameter is required") + + try: + # Convert step and digits to appropriate types + step = int(step) + digits = int(digits) + if digits < 6 or digits > 8: + raise ValueError("Digits must be between 6 and 8") + + # Convert timestamp_iso to integer timestamp + if timestamp_iso: + import datetime + dt = datetime.datetime.fromisoformat(timestamp_iso.replace('Z', '+00:00')) + timestamp = int(dt.timestamp()) + else: + timestamp = int(time.time()) + + # Calculate counter value (T = floor(timestamp / step)) + counter = timestamp // step + + # Decode the base32 secret + # Add padding if necessary (base64 requires padding to be multiple of 8) + base32_secret = base32_secret.upper().replace(' ', '') + if len(base32_secret) % 8 != 0: + base32_secret += '=' * (8 - (len(base32_secret) % 8)) + key = base64.b32decode(base32_secret, casefold=True) + + # Calculate HMAC-SHA1 + counter_bytes = struct.pack('>Q', counter) # Big-endian 8-byte integer + hmac_hash = hmac.new(key, counter_bytes, hashlib.sha1).digest() + + # Dynamic truncation + offset = hmac_hash[-1] & 0xF + code = struct.unpack('>I', hmac_hash[offset:offset+4])[0] & 0x7FFFFFFF + + # Generate the OTP + otp = str(code % (10 ** digits)).zfill(digits) + + # Calculate remaining time until next OTP change + remaining_time = step - (timestamp % step) + + return {"totp": otp, "remaining_time": remaining_time, "time_step": step} + except ValueError as e: + if "invalid literal for int()" in str(e): + raise ValueError("step and digits must be valid integers") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in otp_totp_generate: {str(e)}") + + def unicode_norm(self, inputs): + import unicodedata + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + form = inputs.get("form", "NFC") # Default to NFC + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if form is not None and not isinstance(form, str): + raise TypeError("form must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Normalize form (NFC, NFD, NFKC, NFKD) + form = form.upper().strip() + + if form not in ['NFC', 'NFD', 'NFKC', 'NFKD']: + raise ValueError(f"Invalid normalization form: {form}. Must be one of: NFC, NFD, NFKC, NFKD") + + # Apply Unicode normalization + normalized_text = unicodedata.normalize(form, text) + + return {"text": normalized_text} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in unicode_norm: {str(e)}") + + def text_bidi_sanitize(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Bidi control characters to remove + bidi_controls = [ + '\u200E', # LEFT-TO-RIGHT MARK + '\u200F', # RIGHT-TO-LEFT MARK + '\u202A', # LEFT-TO-RIGHT EMBEDDING + '\u202B', # RIGHT-TO-LEFT EMBEDDING + '\u202C', # POP DIRECTIONAL FORMATTING + '\u202D', # LEFT-TO-RIGHT OVERRIDE + '\u202E', # RIGHT-TO-LEFT OVERRIDE + '\u2066', # LEFT-TO-RIGHT ISOLATE + '\u2067', # RIGHT-TO-LEFT ISOLATE + '\u2068', # FIRST STRONG ISOLATE + '\u2069', # POP DIRECTIONAL ISOLATE + ] + + # Remove all Bidi control characters + sanitized_text = text + for control_char in bidi_controls: + sanitized_text = sanitized_text.replace(control_char, '') + + return {"text": sanitized_text} + except Exception as e: + raise RuntimeError(f"Error in text_bidi_sanitize: {str(e)}") + + def text_xor_hex(self, inputs): + import binascii + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_a = inputs.get("hex_a") + hex_b = inputs.get("hex_b") + + # 类型检查 + if hex_a is not None and not isinstance(hex_a, str): + raise TypeError("hex_a must be a string") + if hex_b is not None and not isinstance(hex_b, str): + raise TypeError("hex_b must be a string") + + # 检查必需参数 + if hex_a is None: + raise ValueError("hex_a parameter is required") + if hex_b is None: + raise ValueError("hex_b parameter is required") + + try: + # Remove any whitespace + hex_a = hex_a.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + hex_b = hex_b.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + + # Validate hex strings + if not (all(c in "0123456789abcdefABCDEF" for c in hex_a) and len(hex_a) % 2 == 0): + raise ValueError("hex_a must be a valid hexadecimal string with even length") + if not (all(c in "0123456789abcdefABCDEF" for c in hex_b) and len(hex_b) % 2 == 0): + raise ValueError("hex_b must be a valid hexadecimal string with even length") + + # Convert hex strings to bytes + bytes_a = binascii.unhexlify(hex_a) + bytes_b = binascii.unhexlify(hex_b) + + # Make the byte arrays the same length by padding the shorter one with zeros + max_len = max(len(bytes_a), len(bytes_b)) + bytes_a = bytes_a.ljust(max_len, b'\x00') + bytes_b = bytes_b.ljust(max_len, b'\x00') + + # Perform XOR operation + result_bytes = bytes(a ^ b for a, b in zip(bytes_a, bytes_b)) + + # Convert result back to hex + result_hex = binascii.hexlify(result_bytes).decode('utf-8') + + return {"hex": result_hex} + except ValueError as e: + if "Non-hexadecimal digit found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in text_xor_hex: {str(e)}") + + def text_rotN(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + n = inputs.get("n", 0) + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + n = int(n) + except ValueError: + raise ValueError("n must be a valid integer") + + result = [] + for char in text: + if char.isupper(): + # Rotate uppercase letters + result_char = chr((ord(char) - ord('A') + n) % 26 + ord('A')) + result.append(result_char) + elif char.islower(): + # Rotate lowercase letters + result_char = chr((ord(char) - ord('a') + n) % 26 + ord('a')) + result.append(result_char) + else: + # Keep non-alphabetic characters unchanged + result.append(char) + + return {"text": ''.join(result)} + + def luhn_check(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数(支持 card_number 和 number 两个参数名) + card_number = inputs.get("number") or inputs.get("card_number") + + # 类型检查 + if card_number is not None and not isinstance(card_number, str): + raise TypeError("number must be a string") + + # 检查必需参数 + if card_number is None: + raise ValueError("number parameter is required") + + try: + # 如果输入是JSON数组或其他非数字字符串,返回该字符串本身(用于数据传递) + # 这种情况发生在DAG设计中类型不匹配时 + if card_number.startswith('[') or card_number.startswith('{'): + # 输入是JSON,直接返回原值(用于传递) + return {"valid": card_number} + + # Remove whitespace from card number + card_number = card_number.replace(" ", "").replace("-", "") + + # Check if card number is all digits + if not card_number.isdigit() or len(card_number) < 13: + return {"valid": "false"} + + # Implement Luhn algorithm + total = 0 + reverse_digits = card_number[::-1] # Reverse the number for easier processing + + for i, digit in enumerate(reverse_digits): + num = int(digit) + if i % 2 == 1: # Every second digit starting from the right (which is first in reversed string) + num *= 2 + if num > 9: + num -= 9 # Equivalent to sum of digits for 2-digit numbers + total += num + + # Check if total is divisible by 10 + is_valid = total % 10 == 0 + return {"valid": "true" if is_valid else "false"} + except Exception as e: + raise RuntimeError(f"Error in luhn_check: {str(e)}") + + def iban_validate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iban = inputs.get("iban") + + # 类型检查 + if iban is not None and not isinstance(iban, str): + raise TypeError("iban must be a string") + + # 检查必需参数 + if iban is None: + raise ValueError("iban parameter is required") + + try: + # Remove whitespace from IBAN + iban = iban.replace(" ", "") + + # Basic length and format check + if not (len(iban) >= 15 and len(iban) <= 34): + return {"valid": "False"} + + if not (iban[:2].isalpha() and iban[2:].isdigit()): + return {"valid": "False"} + + # Move first four characters to the end + rearranged = iban[4:] + iban[:4] + + # Replace letters with numbers (A=10, B=11, ..., Z=35) + numeric_iban = '' + for char in rearranged: + if char.isdigit(): + numeric_iban += char + else: + numeric_iban += str(ord(char.upper()) - ord('A') + 10) + + # Perform modulo 97 check + # Use step-by-step approach for very large numbers + remainder = 0 + for char in numeric_iban: + remainder = (remainder * 10 + int(char)) % 97 + + is_valid = remainder == 1 + return {"valid": "True" if is_valid else "False"} + except Exception as e: + raise RuntimeError(f"Error in iban_validate: {str(e)}") + + def matter_synthesizer(self, inputs): + import hashlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + blueprint = inputs.get("blueprint") + + # 类型检查 + if blueprint is not None and not isinstance(blueprint, str): + raise TypeError("blueprint must be a string") + + try: + # Get blueprint parameter as defined in interface + if blueprint is None: + blueprint = "" + + # Generate a unique item ID based on the blueprint + # This ensures the same blueprint always produces the same item + blueprint_hash = hashlib.sha256(blueprint.encode()).hexdigest()[:16] + + # Create a synthesized item with a deterministic ID based on blueprint + synthesized_item = f"synthesized_item_{blueprint_hash}" + + return {"output_slot": synthesized_item} + except Exception as e: + raise RuntimeError(f"Error in matter_synthesizer: {str(e)}") + + # --- Terminal Implementations --- + def terminal_1(self, inputs): + """ + terminal_1: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 只返回 text_output + - 只输入正确的 slot_b → 只返回 hex_output + - 同时输入正确的 slot_a 和 slot_b → 返回 item_dispenser(物品掉落) + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + # 检查哪些输入被提供了 + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值是否正确(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + expected_a = golden_inputs["slot_a"] + a_valid = str(slot_a) == str(expected_a) + + if has_b and "slot_b" in golden_inputs: + expected_b = golden_inputs["slot_b"] + b_valid = str(slot_b) == str(expected_b) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 item_dispenser + if has_a and has_b: + if a_valid and b_valid: + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 text_output + if has_a and not has_b: + if a_valid: + if "text_output" in golden_outputs: + result["text_output"] = golden_outputs["text_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 hex_output + if has_b and not has_a: + if b_valid: + if "hex_output" in golden_outputs: + result["hex_output"] = golden_outputs["hex_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def terminal_2(self, inputs): + """ + terminal_2: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 text_result + - 同时输入正确的 num1 和 num2 → 返回 hex_result 和 math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + # 检查哪些输入被提供了 + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值是否正确(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + expected_num1 = golden_inputs["num1"] + num1_valid = str(num1) == str(expected_num1) + + if has_num2 and "num2" in golden_inputs: + expected_num2 = golden_inputs["num2"] + num2_valid = str(num2) == str(expected_num2) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 hex_result 和 math_token + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 text_result + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "text_result" in golden_outputs: + result["text_result"] = golden_outputs["text_result"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def logic_terminal(self, inputs): + """ + Logic Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 返回 screen(部分输出) + - 只输入正确的 slot_b → 返回 screen 和 secondary_output + - 同时输入正确的 slot_a 和 slot_b → 返回 screen, secondary_output, item_dispenser + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + a_valid = str(slot_a) == str(golden_inputs["slot_a"]) + + if has_b and "slot_b" in golden_inputs: + b_valid = str(slot_b) == str(golden_inputs["slot_b"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出(包括 item_dispenser) + if has_a and has_b: + if a_valid and b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 screen(部分输出) + if has_a and not has_b: + if a_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 screen 和 secondary_output + if has_b and not has_a: + if b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def math_terminal(self, inputs): + """ + Math Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 result_display + - 同时输入正确的 num1 和 num2 → 返回 result_display, hex_result, math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + num1_valid = str(num1) == str(golden_inputs["num1"]) + + if has_num2 and "num2" in golden_inputs: + num2_valid = str(num2) == str(golden_inputs["num2"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 result_display + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def crypt_terminal(self, inputs): + """ + Encryption Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 plaintext → 返回 status(部分输出) + - 同时输入正确的 plaintext 和 key → 返回 status, encrypted_hex, encryption_chip + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + plaintext = inputs.get("plaintext") + key = inputs.get("key") + + has_plaintext = plaintext is not None and plaintext != "" + has_key = key is not None and key != "" + + # 验证输入值(与 golden values 比较) + plaintext_valid = False + key_valid = False + + if has_plaintext and "plaintext" in golden_inputs: + plaintext_valid = str(plaintext) == str(golden_inputs["plaintext"]) + + if has_key and "key" in golden_inputs: + key_valid = str(key) == str(golden_inputs["key"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_plaintext and has_key: + if plaintext_valid and key_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + if "encrypted_hex" in golden_outputs: + result["encrypted_hex"] = golden_outputs["encrypted_hex"] + if "encryption_chip" in golden_outputs: + result["encryption_chip"] = golden_outputs["encryption_chip"] + return result + else: + incorrect_params = [] + correct_params = [] + if not plaintext_valid: + incorrect_params.append("plaintext") + else: + correct_params.append("plaintext") + if not key_valid: + incorrect_params.append("key") + else: + correct_params.append("key") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 plaintext 且正确 → 返回 status(部分输出) + if has_plaintext and not has_key: + if plaintext_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: plaintext"} + + # 只提供 key 但没有 plaintext + if has_key and not has_plaintext: + return {"error": "plaintext required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + def sequence_terminal(self, inputs): + """ + Sequence Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 sequence → 返回 verification(部分输出) + - 同时输入正确的 sequence 和 checksum → 返回 verification, auth_code, access_card + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + sequence = inputs.get("sequence") + checksum = inputs.get("checksum") + + has_sequence = sequence is not None and sequence != "" + has_checksum = checksum is not None and checksum != "" + + # 验证输入值(与 golden values 比较) + sequence_valid = False + checksum_valid = False + + if has_sequence and "sequence" in golden_inputs: + sequence_valid = str(sequence) == str(golden_inputs["sequence"]) + + if has_checksum and "checksum" in golden_inputs: + checksum_valid = str(checksum) == str(golden_inputs["checksum"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_sequence and has_checksum: + if sequence_valid and checksum_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + if "auth_code" in golden_outputs: + result["auth_code"] = golden_outputs["auth_code"] + if "access_card" in golden_outputs: + result["access_card"] = golden_outputs["access_card"] + return result + else: + incorrect_params = [] + correct_params = [] + if not sequence_valid: + incorrect_params.append("sequence") + else: + correct_params.append("sequence") + if not checksum_valid: + incorrect_params.append("checksum") + else: + correct_params.append("checksum") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 sequence 且正确 → 返回 verification(部分输出) + if has_sequence and not has_checksum: + if sequence_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: sequence"} + + # 只提供 checksum 但没有 sequence + if has_checksum and not has_sequence: + return {"error": "sequence required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + # --- Additional File Tools --- + + def zip_unzip_file(self, inputs): + """ZIP 解压文件工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def zip_unzip_item(self, inputs): + """ZIP 解压道具工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def code_py_exec(self, inputs): + """Python 代码执行工具 + + 这是一个真实执行的工具,在 DAG 生成阶段和运行时评测阶段都会执行代码。 + 输入: code (Python 代码字符串) + 输出: stdout (标准输出,包含执行结果和错误信息) + + 特殊行为: + - 如果代码定义了 main() 函数,会自动调用它 + - 如果执行出错,错误信息会包含在 stdout 中 + """ + code = inputs.get("code", "") + + if not code: + return {"stdout": "Error: No code provided"} + + try: + # 创建一个受限的执行环境 + import io + import sys + + # 捕获标准输出和标准错误 + old_stdout = sys.stdout + old_stderr = sys.stderr + sys.stdout = io.StringIO() + sys.stderr = io.StringIO() + + # 执行代码 + exec_globals = {"__builtins__": __builtins__} + exec_locals = {} + exec(code, exec_globals, exec_locals) + + # 如果定义了 main() 函数,自动调用它 + if 'main' in exec_locals and callable(exec_locals['main']): + exec_locals['main']() + + # 获取输出 + stdout_value = sys.stdout.getvalue() + stderr_value = sys.stderr.getvalue() + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 合并 stdout 和 stderr + output = stdout_value + if stderr_value: + output += ("\n" if output else "") + f"[stderr] {stderr_value}" + + # 如果没有任何输出,尝试返回 result 变量的值 + if not output: + result = exec_locals.get("_result") or exec_locals.get("result") + if result is not None: + output = str(result) + + return {"stdout": output if output else "(no output)"} + + except Exception as e: + # 恢复标准输出和错误输出 + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 返回错误信息 + return {"stdout": f"Error: {type(e).__name__}: {str(e)}"} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-c520de06/environment/puzzle/worker.Dockerfile b/tasks/agentescape-25-skeleton-c520de06/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-25-skeleton-c520de06/environment/puzzle/worker.Dockerfile @@ -0,0 +1,8 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends libseccomp2 && rm -rf /var/lib/apt/lists/* +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY worker.py child.py /app/ +COPY upstream/simulator.py /app/simulator.py +CMD ["uvicorn", "worker:app", "--host", "0.0.0.0", "--port", "8001", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-25-skeleton-c520de06/environment/puzzle/worker.py b/tasks/agentescape-25-skeleton-c520de06/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-25-skeleton-c520de06/environment/puzzle/worker.py @@ -0,0 +1,73 @@ +"""Stateless Python tool worker. Never receives a scenario or reference values.""" + +import json +import os +import signal +import subprocess +import sys +import tempfile +import threading + +from fastapi import FastAPI +from pydantic import BaseModel, ConfigDict + +app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) +lock = threading.Lock() + + +class Execution(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + code: str + + +@app.get("/health") +def health(): + return {"ok": True} + + +@app.post("/execute") +def execute(request: Execution): + if len(request.code.encode()) > 65536: + return {"stdout": "Error: code exceeds 64 KiB limit"} + with lock, tempfile.TemporaryDirectory(prefix="escape-code-") as directory: + os.chown(directory, 65534, 65534) + with tempfile.TemporaryFile() as output: + process = subprocess.Popen( + [sys.executable, "-I", "/app/child.py"], + stdin=subprocess.PIPE, + stdout=output, + stderr=subprocess.DEVNULL, + cwd=directory, + user=65534, + group=65534, + extra_groups=[], + start_new_session=True, + env={"PATH": "/usr/local/bin:/usr/bin:/bin"}, + ) + try: + process.communicate( + json.dumps({"code": request.code}).encode(), timeout=5 + ) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + return {"stdout": "Error: Python execution timed out"} + finally: + # Also remove children still in the process group after normal exit. + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + output.seek(0) + value = output.read(65537) + if len(value) > 65536 or process.returncode != 0: + return { + "stdout": "Error: Python execution exceeded a resource limit or failed" + } + try: + result = json.loads(value) + if not isinstance(result.get("stdout"), str): + raise ValueError("Invalid worker response") + return result + except (ValueError, AttributeError): + return {"stdout": "Error: Python execution returned invalid output"} diff --git a/tasks/agentescape-25-skeleton-c520de06/instruction.md b/tasks/agentescape-25-skeleton-c520de06/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-25-skeleton-c520de06/instruction.md @@ -0,0 +1,18 @@ +# Escape the room + +Discover the victory string and submit it with `escape submit-answer`. +Start with `escape observe`. This returns the room, available information, visible entities, and victory node ID. + +Use these commands (JSON responses): + +```sh +escape investigate NODE_ID +escape tool-call NODE_ID --arguments-json '{"parameter": "value"}' +escape use-item NODE_ID --arguments-json '{"parameter": "value"}' +escape submit-answer 'exact victory string' +escape state +``` + +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. + +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. diff --git a/tasks/agentescape-25-skeleton-c520de06/solution/oracle.py b/tasks/agentescape-25-skeleton-c520de06/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-25-skeleton-c520de06/solution/oracle.py @@ -0,0 +1,133 @@ +"""Reference solver: use trusted inputs, but obtain the answer through public actions.""" + +import json +import urllib.request +from pathlib import Path + + +def http_action(base_url, payload): + request = urllib.request.Request( + base_url + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(request, timeout=30) as response: + return json.load(response) + + +def solve(scenario, act, observe): + nodes = {node["id"]: node for node in scenario["nodes"]} + visible = {entity["id"] for entity in observe["available_entities"]} + solved = set() + seen_outputs = {} + action_count = 0 + + def call(payload): + nonlocal action_count + action_count += 1 + response = act(payload) + visible.update(entity["id"] for entity in response.get("newly_revealed", [])) + if ( + response.get("episode", {}).get("termination_reason") + == "infrastructure_error" + ): + raise RuntimeError("Infrastructure failure") + return response + + for _round in range(len(nodes) + 2): + progress = False + for node_id, node in nodes.items(): + if node_id not in visible or node_id in solved: + continue + # Preserve graph order for data inputs; trigger/drop edges express visibility. + predecessors = [ + edge["source_id"] + for edge in scenario["edges"] + if edge["target_id"] == node_id + and edge["connection_type"] not in ("Item", "Hidden_Item") + ] + if any(pred not in solved for pred in predecessors): + continue + info = call({"action": "investigate", "node_id": node_id}) + if not info.get("ok"): + raise RuntimeError(f"Investigation failed: {node_id}: {info}") + inputs = { + port["name"]: port["value"] + for port in node.get("inputs", []) + if "value" in port + } + if node["type"] == "Tool": + result = call( + {"action": "tool_call", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok") or result.get("output_values", {}).get("error"): + raise RuntimeError(f"Tool failed: {node_id}: {result}") + output = result.get("output_values", {}) + if node.get("template_id") in ("terminal_1", "terminal_2"): + slots = { + port["name"]: inputs[port["name"]] + for port in node["inputs"] + if port["type"] not in ("Item", "Hidden_Item") + and port["name"] in inputs + } + triggers = { + key: value for key, value in inputs.items() if key not in slots + } + for key, value in slots.items(): + partial = call( + { + "action": "tool_call", + "node_id": node_id, + "arguments": {**triggers, key: value}, + } + ) + if partial.get("ok"): + output.update(partial.get("output_values", {})) + # HIDDEN_ITEM tool drops only occur on subsequent investigation. + call({"action": "investigate", "node_id": node_id}) + elif info.get("required_inputs"): + result = call( + {"action": "use_item", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok"): + raise RuntimeError(f"Item failed: {node_id}: {result}") + output = result.get("content") + else: + output = info.get("content") + seen_outputs[node_id] = output + solved.add(node_id) + progress = True + win_id = scenario["metadata"]["win_node_id"] + if win_id in solved and (len(solved) == len(nodes) or not progress): + outputs = seen_outputs[win_id] + if not outputs: + raise RuntimeError(f"Victory node returned no output: {win_id}") + # Upstream grades its first stored output port, independent of response order. + victory_port = next( + port["name"] for port in nodes[win_id]["outputs"] if "value" in port + ) + answer = outputs[victory_port] if isinstance(outputs, dict) else outputs + result = call({"action": "submit_answer", "answer": answer}) + if not result.get("is_win"): + raise RuntimeError(f"Victory submission failed: {result}") + return {"won": True, "actions": action_count, "visited_nodes": len(solved)} + if not progress: + raise RuntimeError(f"No progress: visible={visible}, solved={solved}") + raise RuntimeError("Reference solver exceeded graph traversal limit") + + +if __name__ == "__main__": + import os + + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000") + with urllib.request.urlopen(base + "/observation", timeout=20) as response: + observation = json.load(response) + print( + json.dumps( + solve( + json.loads(Path("/solution/scenario.json").read_text()), + lambda payload: http_action(base, payload), + observation, + ) + ) + ) diff --git a/tasks/agentescape-25-skeleton-c520de06/solution/scenario.json b/tasks/agentescape-25-skeleton-c520de06/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..f592cac5e5414534ee2451cefccf75fda159f021 --- /dev/null +++ b/tasks/agentescape-25-skeleton-c520de06/solution/scenario.json @@ -0,0 +1,1521 @@ +{ + "metadata": { + "total_nodes": 25, + "total_edges": 34, + "win_node_id": "item_11", + "win_condition": { + "type": "item_content", + "node_id": "item_11", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_11", + "terminal_1", + "calc_inv_mod", + "graph_shortest_path", + "graph_shortest_path_595a", + "graph_shortest_path_3f3f", + "zip_unzip_file", + "zip_unzip_file_7432", + "base64_encode", + "container_3", + "luhn_check", + "terminal_2", + "json_get", + "calc_bigmul" + ], + "by_node": { + "item_11": { + "node_name": "", + "node_type": "Item", + "template_id": "item_11", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Code_Python", + "description": "Python code" + } + } + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": {}, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + } + } + }, + "calc_inv_mod": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "Integer a" + } + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "Graph JSON file ID" + }, + "src": { + "type": "Text_Generic", + "description": "Source node" + }, + "dst": { + "type": "Text_Generic", + "description": "Destination node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "graph_shortest_path_595a": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": {}, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "graph_shortest_path_3f3f": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": {}, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "zip_unzip_file_7432": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "base64_encode": { + "node_name": "Base64 Encoder", + "node_type": "Tool", + "template_id": "base64_encode", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex bytes" + } + }, + "init_outputs": {} + }, + "container_3": { + "node_name": "", + "node_type": "Item", + "template_id": "container_3", + "init_inputs": { + "fingerprint_input": { + "type": "Big_Int", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + }, + "luhn_check": { + "node_name": "Luhn Checker", + "node_type": "Tool", + "template_id": "luhn_check", + "init_inputs": { + "number": { + "type": "Text_Generic", + "description": "Number string" + } + }, + "init_outputs": {} + }, + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": {}, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + } + } + }, + "json_get": { + "node_name": "JSON Getter", + "node_type": "Tool", + "template_id": "json_get", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "JSON file ID" + }, + "jsonpath": { + "type": "Text_Generic", + "description": "JSONPath expression" + } + }, + "init_outputs": { + "values": { + "type": "Text_Generic", + "description": "Extracted values" + } + } + }, + "calc_bigmul": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First large integer" + }, + "b": { + "type": "Big_Int", + "description": "Second large integer" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "item_11": { + "init_inputs": {}, + "init_outputs": { + "content": "def execute_task():\n return 'execution_complete'\n" + } + }, + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "Terminal sequence Alpha processed successfully.", + "hex_output": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "calc_inv_mod": { + "init_inputs": { + "a": "982734918273648172635482910" + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": { + "file_id": "graph_data_main.json", + "src": "Node_A", + "dst": "Node_Z" + }, + "init_outputs": { + "path": "[\"Node_A\", \"Node_C\", \"Node_F\", \"Node_K\", \"Node_M\", \"Node_Z\"]", + "cost": "482319" + } + }, + "graph_shortest_path_595a": { + "init_inputs": {}, + "init_outputs": { + "path": "[\"Node_X\", \"Node_Y\", \"Node_P\", \"Node_Q\", \"Node_R\", \"Node_S\"]", + "cost": "572810" + } + }, + "graph_shortest_path_3f3f": { + "init_inputs": {}, + "init_outputs": { + "path": "[\"Start\", \"N1\", \"N2\", \"N3\", \"N4\", \"End\"]", + "cost": "184752" + } + }, + "zip_unzip_file": { + "init_inputs": {}, + "init_outputs": { + "files": "extracted_folder_01.zip" + } + }, + "zip_unzip_file_7432": { + "init_inputs": { + "zip_id": "archive_secret_99.zip" + }, + "init_outputs": { + "files": "data_dump_7432.json" + } + }, + "base64_encode": { + "init_inputs": { + "hex": "deadbeef1234567890abcdefdeadbeef" + }, + "init_outputs": {} + }, + "container_3": { + "init_inputs": { + "fingerprint_input": "8374928374651928374659102938" + }, + "init_outputs": {} + }, + "luhn_check": { + "init_inputs": { + "number": "79927398713" + }, + "init_outputs": {} + }, + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "System initialization partial processing done.", + "hex_result": "abcdef0123456789abcdef0123456789" + } + }, + "json_get": { + "init_inputs": { + "file_id": "config_data_33.json", + "jsonpath": "$.store.book[*].author" + }, + "init_outputs": { + "values": "[\"Nigel Rees\", \"Evelyn Waugh\", \"Herman Melville\", \"J. R. R. Tolkien\"]" + } + }, + "calc_bigmul": { + "init_inputs": { + "a": "583920193847561029384756102", + "b": "192837465019283746501928374" + }, + "init_outputs": {} + } + }, + "intro_narrative": "The alarms of Station Tartarus blare in a relentless rhythm, casting the central command nexus in a harsh, pulsing red light. The facility has been locked down due to an imminent core meltdown, and all evacuation shuttles have long since departed. You are the last technician remaining on board, trapped in the heart of the station's tangled mainframe. Your only chance of escape is to override the lockdown protocols, but the master override codes are tightly sealed within the Final Datacore. The station's systems have fragmented, turning the command center into a complex web of encrypted terminals, biometric locks, and dead-end data flows. You must navigate this maze of futuristic technology, reactivating dormant modules and tracing the scattered data to piece together the command sequence. Time is running dangerously low. Reactivate the systems, follow the data trails, and extract the codes before the station is reduced to stardust.", + "narrative_style": "sci_fi" + }, + "nodes": [ + { + "id": "item_11", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_11", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Code_Python", + "description": "Python code", + "value": "def execute_task():\n return 'execution_complete'\n" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "def execute_task():\n return 'execution_complete'\n" + } + }, + "narrative": "A glowing, crystalline memory module. It pulses with unresolved data, waiting to be properly interfaced." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "\u0004\u001dH" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "982734918273648172635482910" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Terminal sequence Alpha processed successfully." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "Terminal sequence Alpha processed successfully.", + "hex_output": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "narrative": "This is the Mainframe Interface. It requires inputs from both the Decryption Matrix and the Quantum Inverter to activate fully." + }, + { + "id": "calc_inv_mod", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "982734918273648172635482910" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "9" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "982734918273648172635482910" + } + ], + "init": { + "inputs": { + "a": "982734918273648172635482910" + }, + "outputs": {} + }, + "narrative": "This is the Quantum Inverter. It requires input from the Harmonic Synthesizer to reverse the data flow." + }, + { + "id": "crypto_rsa_decrypt_hex", + "name": "RSA Decrypt", + "description": "RSA decrypt (hex cipher) with n,d (decimal).", + "type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "hex_cipher", + "type": "Hex_String", + "description": "Ciphertext (Hex)", + "value": "abcdef0123456789abcdef0123456789" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Modulus n", + "value": "482319" + }, + { + "name": "d", + "type": "Big_Int", + "description": "Private exponent d", + "value": 152563954 + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decrypted text", + "value": "\u0004\u001dH" + } + ], + "narrative": "This is the Decryption Matrix. It requires inputs from the Signal Translator, the Integrity Verifier, and the Processing Console." + }, + { + "id": "num_base_convert", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "482319" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "572810" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "184752" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "482319" + } + ], + "narrative": "This is the Signal Translator. It requires inputs from the Primary Nav-Planner, the Secondary Routing Module, and the Pathway Analyzer." + }, + { + "id": "checksum_crc32", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "439d858fb8d22d8927a6ae9c2ec87789adb321fc19dac305a4ffe79e18e15870" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "0917f0f2" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 152563954 + } + ], + "narrative": "This is the Integrity Verifier. It processes data from the Hashing Engine. You must feed it the engine's result to proceed." + }, + { + "id": "hash_sha256", + "name": "SHA-256 Hasher", + "description": "SHA-256 over UTF-8 text; returns hex.", + "type": "Tool", + "template_id": "hash_sha256", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Text to hash", + "value": "[\"Node_A\", \"Node_C\", \"Node_F\", \"Node_K\", \"Node_M\", \"Node_Z\"]" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "SHA-256 Hex digest", + "value": "439d858fb8d22d8927a6ae9c2ec87789adb321fc19dac305a4ffe79e18e15870" + } + ], + "narrative": "This is the Hashing Engine. It requires input from the Primary Nav-Planner to scramble the coordinates." + }, + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "graph_data_main.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Node_A" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Node_Z" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Node_A\", \"Node_C\", \"Node_F\", \"Node_K\", \"Node_M\", \"Node_Z\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "482319" + } + ], + "init": { + "inputs": { + "file_id": "graph_data_main.json", + "src": "Node_A", + "dst": "Node_Z" + }, + "outputs": { + "path": "[\"Node_A\", \"Node_C\", \"Node_F\", \"Node_K\", \"Node_M\", \"Node_Z\"]", + "cost": "482319" + } + }, + "narrative": "An advanced holographic map projector used for plotting deep space coordinates." + }, + { + "id": "graph_shortest_path_595a", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "extracted_folder_01.zip" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "[\"Start\", \"N1\", \"N2\", \"N3\", \"N4\", \"End\"]" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "[\"Node_A\", \"Node_C\", \"Node_F\", \"Node_K\", \"Node_M\", \"Node_Z\"]" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Node_X\", \"Node_Y\", \"Node_P\", \"Node_Q\", \"Node_R\", \"Node_S\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "572810" + } + ], + "init": { + "inputs": {}, + "outputs": { + "path": "[\"Node_X\", \"Node_Y\", \"Node_P\", \"Node_Q\", \"Node_R\", \"Node_S\"]", + "cost": "572810" + } + }, + "narrative": "This is the Secondary Routing Module. It requires inputs from the Archive Extractor, the Pathway Analyzer, and the Primary Nav-Planner." + }, + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "184752" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "482319" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "9" + } + ], + "narrative": "This is the Harmonic Synthesizer. It requires inputs from the Pathway Analyzer and the Primary Nav-Planner to align the frequencies." + }, + { + "id": "graph_shortest_path_3f3f", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "extracted_folder_01.zip" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "false" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "[\"Nigel Rees\", \"Evelyn Waugh\", \"Herman Melville\", \"J. R. R. Tolkien\"]" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Start\", \"N1\", \"N2\", \"N3\", \"N4\", \"End\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "184752" + } + ], + "init": { + "inputs": {}, + "outputs": { + "path": "[\"Start\", \"N1\", \"N2\", \"N3\", \"N4\", \"End\"]", + "cost": "184752" + } + }, + "narrative": "This is the Pathway Analyzer. It requires inputs from the Archive Extractor, the Credential Scanner, and the Database Query Terminal." + }, + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "data_dump_7432.json" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "3q2+7xI0VniQq83v3q2+7w==" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_folder_01.zip" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "extracted_folder_01.zip" + } + }, + "narrative": "This is the Archive Extractor. It needs inputs from the File Decompressor and the Data Encoder to unlock sealed files." + }, + { + "id": "zip_unzip_file_7432", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "archive_secret_99.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "false" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "data_dump_7432.json" + } + ], + "init": { + "inputs": { + "zip_id": "archive_secret_99.zip" + }, + "outputs": { + "files": "data_dump_7432.json" + } + }, + "narrative": "This is the File Decompressor. It requires input from the Credential Scanner to bypass the initial security layer." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A small, reinforced card bearing the crest of the station's chief engineer." + }, + { + "id": "container_2", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_2", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Hex_String", + "description": "Fingerprint Hash", + "value": "0917f0f2" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is a Biometric Lockbox. It requires input from the Integrity Verifier to release its locking mechanism." + }, + { + "id": "base64_encode", + "name": "Base64 Encoder", + "description": "Encode hex bytes to base64.", + "type": "Tool", + "template_id": "base64_encode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "hex", + "type": "Hex_String", + "description": "Hex bytes", + "value": "deadbeef1234567890abcdefdeadbeef" + } + ], + "outputs": [ + { + "name": "b64", + "type": "Text_Generic", + "description": "Base64 string", + "value": "3q2+7xI0VniQq83v3q2+7w==" + } + ], + "init": { + "inputs": { + "hex": "deadbeef1234567890abcdefdeadbeef" + }, + "outputs": {} + }, + "narrative": "A specialized console designed to reformat raw binary feeds into readable alphanumeric strings." + }, + { + "id": "container_3", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_3", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Big_Int", + "description": "Fingerprint Hash", + "value": "8374928374651928374659102938" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "8374928374651928374659102938" + }, + "outputs": {} + }, + "narrative": "A cylindrical durasteel container with a heavy-duty mechanical locking system." + }, + { + "id": "luhn_check", + "name": "Luhn Checker", + "description": "Luhn validity of number string.", + "type": "Tool", + "template_id": "luhn_check", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "number", + "type": "Text_Generic", + "description": "Number string", + "value": "79927398713" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "false" + } + ], + "init": { + "inputs": { + "number": "79927398713" + }, + "outputs": {} + }, + "narrative": "A wall-mounted terminal used to validate personnel ID numbers and security clearances." + }, + { + "id": "terminal_2", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "112601689955132434334860119406786714287774942663438148" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "184752" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "System initialization partial processing done." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "abcdef0123456789abcdef0123456789" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "System initialization partial processing done.", + "hex_result": "abcdef0123456789abcdef0123456789" + } + }, + "narrative": "This is the Processing Console. It requires inputs from the Computational Reactor and the Pathway Analyzer." + }, + { + "id": "json_get", + "name": "JSON Getter", + "description": "Extract values by simple JSONPath.", + "type": "Tool", + "template_id": "json_get", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "JSON file ID", + "value": "config_data_33.json" + }, + { + "name": "jsonpath", + "type": "Text_Generic", + "description": "JSONPath expression", + "value": "$.store.book[*].author" + } + ], + "outputs": [ + { + "name": "values", + "type": "Text_Generic", + "description": "Extracted values", + "value": "[\"Nigel Rees\", \"Evelyn Waugh\", \"Herman Melville\", \"J. R. R. Tolkien\"]" + } + ], + "init": { + "inputs": { + "file_id": "config_data_33.json", + "jsonpath": "$.store.book[*].author" + }, + "outputs": { + "values": "[\"Nigel Rees\", \"Evelyn Waugh\", \"Herman Melville\", \"J. R. R. Tolkien\"]" + } + }, + "narrative": "An old-school monitor flashing with code arrays, designed to pull specific records from the station's archive." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A tiny microchip coated in conductive gel, used to synchronize erratic mainframe cycles." + }, + { + "id": "calc_bigmul", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "583920193847561029384756102" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "192837465019283746501928374" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "112601689955132434334860119406786714287774942663438148" + } + ], + "init": { + "inputs": { + "a": "583920193847561029384756102", + "b": "192837465019283746501928374" + }, + "outputs": {} + }, + "narrative": "A heavy-duty processing unit capable of handling immense calculations without overheating." + }, + { + "id": "item_8_ff43", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "An experimental power source, humming slightly within its magnetic containment field." + }, + { + "id": "item_8_095e", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A solid-state drive meant for emergency data recovery in case of catastrophic failure." + }, + { + "id": "item_8_4d5f", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A shattered tablet. Some of its internal memory might still be salvageable despite the physical damage." + } + ], + "edges": [ + { + "source_id": "terminal_1", + "target_id": "item_11", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "source_tool" + }, + { + "source_id": "calc_inv_mod", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "slot_b" + }, + { + "source_id": "crypto_rsa_decrypt_hex", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "slot_a" + }, + { + "source_id": "num_base_convert", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "n" + }, + { + "source_id": "checksum_crc32", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "d" + }, + { + "source_id": "hash_sha256", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "graph_shortest_path", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "s" + }, + { + "source_id": "graph_shortest_path_595a", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "from_base" + }, + { + "source_id": "graph_shortest_path", + "target_id": "graph_shortest_path_595a", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "dst" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "mod" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "b" + }, + { + "source_id": "graph_shortest_path", + "target_id": "hash_sha256", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "text" + }, + { + "source_id": "graph_shortest_path_3f3f", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "a" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path_3f3f", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path_595a", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "zip_unzip_file_7432", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "item_8", + "target_id": "graph_shortest_path", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "graph_shortest_path_3f3f", + "target_id": "graph_shortest_path_595a", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "src" + }, + { + "source_id": "container_2", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "base64_encode", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "password" + }, + { + "source_id": "container_3", + "target_id": "graph_shortest_path_595a", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "luhn_check", + "target_id": "zip_unzip_file_7432", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "password" + }, + { + "source_id": "graph_shortest_path_3f3f", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "to_base" + }, + { + "source_id": "luhn_check", + "target_id": "graph_shortest_path_3f3f", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "src" + }, + { + "source_id": "checksum_crc32", + "target_id": "container_2", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "fingerprint_input" + }, + { + "source_id": "terminal_2", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Hex_String", + "source_port": "hex_result", + "target_port": "hex_cipher" + }, + { + "source_id": "json_get", + "target_id": "graph_shortest_path_3f3f", + "connection_type": "Text_Generic", + "source_port": "values", + "target_port": "dst" + }, + { + "source_id": "item_16", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "calc_bigmul", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "num1" + }, + { + "source_id": "item_8_ff43", + "target_id": "container_2", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "terminal_2", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "source_tool" + }, + { + "source_id": "graph_shortest_path_3f3f", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "num2" + }, + { + "source_id": "item_8_095e", + "target_id": "container_3", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "item_8_4d5f", + "target_id": "item_8_ff43", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-c520de06/solution/solve.sh b/tasks/agentescape-25-skeleton-c520de06/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-25-skeleton-c520de06/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-25-skeleton-c520de06/task.toml b/tasks/agentescape-25-skeleton-c520de06/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..29c7dca82194adb2b2dc47a2cc9bd5a2f94e8658 --- /dev/null +++ b/tasks/agentescape-25-skeleton-c520de06/task.toml @@ -0,0 +1,38 @@ +schema_version = "1.4" +source = "https://github.com/AGI-Eval-Official/Repo-of-AgentEscapeBench" + +[[artifacts]] +source = "/evidence/final.json" +service = "puzzle" + +[[artifacts]] +source = "/evidence/trace.jsonl" +service = "puzzle" + +[task] +name = "edbeeching/agentescape-25-skeleton-c520de06" +version = "0.1.0" + +[metadata] +difficulty = 25 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "cc28fae6de7540c8579ba4a1dbe1c76589c05bc0691223736cfd59d08fe123dc" +protocol = "harbor-cli-action-budget-v1" +max_actions = 500 + +[agent] +timeout_sec = 1200 + +[environment] +build_timeout_sec = 900 +cpus = 1 +memory_mb = 1024 + +[verifier] +environment_mode = "separate" +timeout_sec = 60 + +[[verifier.collect]] +service = "puzzle" +command = "python -I /app/export.py" +timeout_sec = 15 diff --git a/tasks/agentescape-25-skeleton-c520de06/tests/Dockerfile b/tasks/agentescape-25-skeleton-c520de06/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-25-skeleton-c520de06/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-25-skeleton-c520de06/tests/expected.json b/tasks/agentescape-25-skeleton-c520de06/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..0cabb73368b5498497455d6df24805b0fb96cb3d --- /dev/null +++ b/tasks/agentescape-25-skeleton-c520de06/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "cc28fae6de7540c8579ba4a1dbe1c76589c05bc0691223736cfd59d08fe123dc", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-25-skeleton-c520de06/tests/grade.py b/tasks/agentescape-25-skeleton-c520de06/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-25-skeleton-c520de06/tests/grade.py @@ -0,0 +1,21 @@ +"""Grade only Harbor-collected sidecar evidence in a fresh verifier container.""" + +import json +from pathlib import Path + +expected = json.loads(Path("/tests/expected.json").read_text()) +state = json.loads(Path("/evidence/final.json").read_text()) +assert state["collected_from_live_service"] is True, "Missing trusted service export" +assert state["scenario_sha256"] == expected["scenario_sha256"], ( + "Wrong scenario evidence" +) +assert state["max_actions"] == expected["max_actions"], "Wrong budget" +assert type(state["won"]) is bool +assert 0 <= state["action_count"] <= state["max_actions"] +assert state["termination_reason"] != "infrastructure_error", ( + "Infrastructure failure is not a puzzle failure" +) +assert not state["won"] or state["termination_reason"] == "success" +Path("/logs/verifier").mkdir(parents=True, exist_ok=True) +Path("/logs/verifier/state.json").write_text(json.dumps(state, indent=2)) +Path("/logs/verifier/reward.txt").write_text("1.0\n" if state["won"] else "0.0\n") diff --git a/tasks/agentescape-25-skeleton-c520de06/tests/test.sh b/tasks/agentescape-25-skeleton-c520de06/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-25-skeleton-c520de06/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-25-skeleton-d8d63351/environment/Dockerfile b/tasks/agentescape-25-skeleton-d8d63351/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-25-skeleton-d8d63351/environment/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-25-skeleton-d8d63351/environment/agent/Dockerfile b/tasks/agentescape-25-skeleton-d8d63351/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-25-skeleton-d8d63351/environment/agent/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-25-skeleton-d8d63351/environment/agent/cli.py b/tasks/agentescape-25-skeleton-d8d63351/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-25-skeleton-d8d63351/environment/agent/cli.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Public agent client; depends only on the Python standard library.""" + +import argparse +import json +import os +import sys +import urllib.error +import urllib.request + + +def main(): + parser = argparse.ArgumentParser(description="Interact with the escape room") + parser.add_argument( + "action", + choices=[ + "observe", + "state", + "investigate", + "tool-call", + "use-item", + "submit-answer", + ], + ) + parser.add_argument("value", nargs="?") + parser.add_argument("--arguments-json", default="{}") + args = parser.parse_args() + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000").rstrip("/") + if args.action in ("observe", "state"): + request = urllib.request.Request( + base + ("/observation" if args.action == "observe" else "/state") + ) + else: + if args.value is None: + parser.error("node ID or answer is required") + payload = {"action": args.action.replace("-", "_")} + if args.action == "submit-answer": + payload["answer"] = args.value + else: + payload["node_id"] = args.value + if args.action in ("tool-call", "use-item"): + payload["arguments"] = json.loads(args.arguments_json) + request = urllib.request.Request( + base + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=30) as response: + print(json.dumps(json.load(response), ensure_ascii=False)) + except (urllib.error.URLError, ValueError) as exc: + print(json.dumps({"ok": False, "error": str(exc)})) + sys.exit(2) + + +if __name__ == "__main__": + main() diff --git a/tasks/agentescape-25-skeleton-d8d63351/environment/docker-compose.yaml b/tasks/agentescape-25-skeleton-d8d63351/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..61cd7e3a6094f483268b8374c2741e295924f4cc --- /dev/null +++ b/tasks/agentescape-25-skeleton-d8d63351/environment/docker-compose.yaml @@ -0,0 +1,50 @@ +services: + main: + image: agentescapebench-agent:aab05a0a9ddb + build: + context: ./agent + networks: [default, puzzle] + security_opt: [no-new-privileges:true] + depends_on: + puzzle: + condition: service_healthy + puzzle: + image: agentescapebench-puzzle:agentescape-25-skeleton-d8d63351-aab05a0a9ddb + build: + context: ./puzzle + networks: [puzzle, execution] + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 512m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"] + interval: 1s + timeout: 3s + retries: 30 + depends_on: + worker: + condition: service_healthy + worker: + image: agentescapebench-worker:aab05a0a9ddb + build: + context: ./puzzle + dockerfile: worker.Dockerfile + networks: [execution] + read_only: true + tmpfs: ["/tmp:size=64m,mode=1777"] + cap_drop: [ALL] + cap_add: [SETUID, SETGID, KILL, CHOWN, DAC_OVERRIDE] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 384m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8001/health')"] + interval: 1s + timeout: 3s + retries: 30 +networks: + puzzle: + internal: true + execution: + internal: true diff --git a/tasks/agentescape-25-skeleton-d8d63351/environment/puzzle/Dockerfile b/tasks/agentescape-25-skeleton-d8d63351/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-25-skeleton-d8d63351/environment/puzzle/Dockerfile @@ -0,0 +1,9 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY upstream /app/upstream +COPY service.py export.py /app/ +COPY scenario.json /private/scenario.json +ENV SCENARIO_PATH=/private/scenario.json EVIDENCE_DIR=/evidence WORKER_URL=http://worker:8001 MAX_ACTIONS=500 +CMD ["uvicorn", "service:create_app", "--factory", "--host", "0.0.0.0", "--port", "8000", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-25-skeleton-d8d63351/environment/puzzle/child.py b/tasks/agentescape-25-skeleton-d8d63351/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-25-skeleton-d8d63351/environment/puzzle/child.py @@ -0,0 +1,59 @@ +"""Run the original Python tool after reducing privileges and blocking networking.""" + +import ctypes +import errno +import json +import resource +import sys + +resource.setrlimit(resource.RLIMIT_CPU, (3, 3)) +resource.setrlimit(resource.RLIMIT_AS, (256 * 1024 * 1024, 256 * 1024 * 1024)) +resource.setrlimit(resource.RLIMIT_FSIZE, (65536, 65536)) +resource.setrlimit(resource.RLIMIT_NOFILE, (32, 32)) +resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + +# Filters survive fork/exec. Fail closed if seccomp cannot be loaded. +lib = ctypes.CDLL("libseccomp.so.2", use_errno=True) +lib.seccomp_init.argtypes = [ctypes.c_uint32] +lib.seccomp_init.restype = ctypes.c_void_p +lib.seccomp_rule_add.argtypes = [ + ctypes.c_void_p, + ctypes.c_uint32, + ctypes.c_int, + ctypes.c_uint, +] +lib.seccomp_syscall_resolve_name.argtypes = [ctypes.c_char_p] +lib.seccomp_load.argtypes = [ctypes.c_void_p] +lib.seccomp_release.argtypes = [ctypes.c_void_p] +ctx = lib.seccomp_init(0x7FFF0000) # SCMP_ACT_ALLOW +if not ctx: + raise RuntimeError("Cannot initialize execution isolation") +try: + for name in ( + "socket", + "socketpair", + "connect", + "ptrace", + "process_vm_readv", + "process_vm_writev", + "mount", + "unshare", + "setns", + "bpf", + ): + number = lib.seccomp_syscall_resolve_name(name.encode()) + if ( + number >= 0 + and lib.seccomp_rule_add(ctx, 0x00050000 | errno.EPERM, number, 0) != 0 + ): + raise RuntimeError("Cannot install execution isolation rule") + if lib.seccomp_load(ctx) != 0: + raise RuntimeError("Cannot activate execution isolation") +finally: + lib.seccomp_release(ctx) + +sys.path.insert(0, "/app") +from simulator import ToolSimulator # noqa: E402 + +request = json.load(sys.stdin) +json.dump(ToolSimulator().code_py_exec(request), sys.stdout) diff --git a/tasks/agentescape-25-skeleton-d8d63351/environment/puzzle/export.py b/tasks/agentescape-25-skeleton-d8d63351/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-25-skeleton-d8d63351/environment/puzzle/export.py @@ -0,0 +1,13 @@ +"""Harbor invokes this inside the puzzle service after stopping the agent.""" + +import json +import pathlib +import urllib.request + +with urllib.request.urlopen("http://127.0.0.1:8000/state", timeout=10) as response: + state = json.load(response) +state["collected_from_live_service"] = True +target = pathlib.Path("/evidence/final.json") +temp = target.with_suffix(".tmp") +temp.write_text(json.dumps(state)) +temp.replace(target) diff --git a/tasks/agentescape-25-skeleton-d8d63351/environment/puzzle/requirements.txt b/tasks/agentescape-25-skeleton-d8d63351/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-25-skeleton-d8d63351/environment/puzzle/requirements.txt @@ -0,0 +1,57 @@ +annotated-doc==0.0.5 + # via fastapi +annotated-types==0.8.0 + # via pydantic +anyio==4.16.0 + # via starlette +certifi==2026.10.23 + # via requests +cffi==2.1.1 ; platform_python_implementation != 'PyPy' + # via cryptography +charset-normalizer==3.5.2 + # via requests +click==8.5.0 + # via uvicorn +cryptography==50.0.2 + # via agentescapebench-harbor +fastapi==0.162.0 + # via agentescapebench-harbor +h11==0.16.0 + # via uvicorn +idna==3.20 + # via + # anyio + # requests +opentelemetry-api==1.45.2 + # via fastapi +pycparser==3.12 ; implementation_name != 'PyPy' and platform_python_implementation != 'PyPy' + # via cffi +pydantic==2.14.2 + # via + # agentescapebench-harbor + # fastapi +pydantic-core==2.50.2 + # via pydantic +pytz==2025.2 + # via agentescapebench-harbor +requests==2.34.2 + # via agentescapebench-harbor +starlette==1.10.0 + # via fastapi +typing-extensions==4.16.0 + # via + # anyio + # fastapi + # opentelemetry-api + # pydantic + # pydantic-core + # starlette + # typing-inspection +typing-inspection==0.4.4 + # via + # fastapi + # pydantic +urllib3==2.8.0 + # via requests +uvicorn==0.54.0 + # via agentescapebench-harbor diff --git a/tasks/agentescape-25-skeleton-d8d63351/environment/puzzle/scenario.json b/tasks/agentescape-25-skeleton-d8d63351/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..35792e0d3ef884fcf2d8acca9a1ba1bdff4919a3 --- /dev/null +++ b/tasks/agentescape-25-skeleton-d8d63351/environment/puzzle/scenario.json @@ -0,0 +1,1346 @@ +{ + "metadata": { + "total_nodes": 25, + "total_edges": 29, + "win_node_id": "matter_synthesizer", + "win_condition": { + "type": "tool_output", + "node_id": "matter_synthesizer", + "output_port": "output_slot", + "output_type": "Item", + "description": "Execute Matter Synthesizer and get the output from port 'output_slot'" + }, + "source_init": { + "source_nodes": [ + "matter_synthesizer", + "item_7", + "terminal_1", + "num_base_convert_74cb", + "checksum_crc32", + "terminal_1_5fdb", + "graph_shortest_path", + "iban_validate", + "item_11", + "terminal_2", + "container_4" + ], + "by_node": { + "matter_synthesizer": { + "node_name": "Matter Synthesizer", + "node_type": "Tool", + "template_id": "matter_synthesizer", + "init_inputs": {}, + "init_outputs": { + "output_slot": { + "type": "Item", + "description": "Synthesized Object" + } + } + }, + "item_7": { + "node_name": "", + "node_type": "Item", + "template_id": "item_7", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Code_Python", + "description": "The integer" + } + } + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": {}, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + } + } + }, + "num_base_convert_74cb": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "s": { + "type": "Big_Int", + "description": "Input integer value" + } + }, + "init_outputs": {} + }, + "checksum_crc32": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + }, + "terminal_1_5fdb": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": {}, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + } + } + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "Graph JSON file ID" + }, + "dst": { + "type": "Text_Generic", + "description": "Destination node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "iban_validate": { + "node_name": "IBAN Validator", + "node_type": "Tool", + "template_id": "iban_validate", + "init_inputs": { + "iban": { + "type": "Text_Generic", + "description": "IBAN string" + } + }, + "init_outputs": {} + }, + "item_11": { + "node_name": "", + "node_type": "Item", + "template_id": "item_11", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Code_Python", + "description": "Python code" + } + } + }, + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": { + "num1": { + "type": "Big_Int", + "description": "First Number" + }, + "num2": { + "type": "Big_Int", + "description": "Second Number" + } + }, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + } + } + }, + "container_4": { + "node_name": "", + "node_type": "Item", + "template_id": "container_4", + "init_inputs": { + "fingerprint_input": { + "type": "Text_Generic", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "matter_synthesizer": { + "init_inputs": {}, + "init_outputs": { + "output_slot": "A completely useless chunk of synthesized plastic." + } + }, + "item_7": { + "init_inputs": {}, + "init_outputs": { + "content": "x = 42\nprint(x)" + } + }, + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "Terminal 1 processed slot A successfully.", + "hex_output": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "num_base_convert_74cb": { + "init_inputs": { + "s": "987654321098765432109876" + }, + "init_outputs": {} + }, + "checksum_crc32": { + "init_inputs": { + "hex": "deadbeef1234567890abcdef" + }, + "init_outputs": {} + }, + "terminal_1_5fdb": { + "init_inputs": {}, + "init_outputs": { + "text_output": "Terminal 5fdb generic output data.", + "hex_output": "f1e2d3c4b5a69788796a5b4c3d2e1f00" + } + }, + "graph_shortest_path": { + "init_inputs": { + "file_id": "network_map_v2.json", + "dst": "Node_XYZ" + }, + "init_outputs": { + "path": "[\"Node_A\", \"Node_B\", \"Node_C\", \"Node_D\", \"Node_XYZ\"]", + "cost": "54321" + } + }, + "iban_validate": { + "init_inputs": { + "iban": "DE89370400440532013000" + }, + "init_outputs": {} + }, + "item_11": { + "init_inputs": {}, + "init_outputs": { + "content": "def greet():\n return 'Hello World'" + } + }, + "terminal_2": { + "init_inputs": { + "num1": "1234567890123456789012", + "num2": "4567890123456789012345" + }, + "init_outputs": { + "text_result": "Terminal 2 executed partial mathematical operation.", + "hex_result": "abcdef0123456789abcdef0123456789" + } + }, + "container_4": { + "init_inputs": { + "fingerprint_input": "fp_938xj2_sha256" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You awaken in the Sanctum of the Lost Archmage, a crumbling tower suspended in the starry expanse of an astral plane. The air hums with latent arcane energy, and glowing runes drift like dust motes in the twilight. Before you vanished, Archmage Vael left behind a complex web of magical apparatuses, each connected by invisible threads of power. Your only hope of returning to the mortal realm is to navigate this intricate magical array and ultimately ignite the legendary Creation Forge. To do so, you must understand the flow of magic, gathering offerings, deciphering forgotten glyphs, and tracing the connections between these ancient relics. Explore the sanctum, let the devices guide your path, and unravel the ultimate spell.", + "narrative_style": "fantasy" + }, + "nodes": [ + { + "id": "matter_synthesizer", + "name": "Matter Synthesizer", + "description": "Synthesizes physical objects from data blueprints.", + "type": "Tool", + "template_id": "matter_synthesizer", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "blueprint", + "type": "Text_Generic", + "description": "Object Blueprint", + "value": "false" + } + ], + "outputs": [ + { + "name": "output_slot", + "type": "Item", + "description": "Synthesized Object", + "value": "synthesized_item_fcbcf165908dd18a" + } + ], + "init": { + "inputs": {}, + "outputs": { + "output_slot": "A completely useless chunk of synthesized plastic." + } + }, + "narrative": "The Creation Forge. A grand mystical furnace capable of manifesting physical objects from raw mana. It requires input from the Truth Balance to ignite its flames." + }, + { + "id": "luhn_check", + "name": "Luhn Checker", + "description": "Luhn validity of number string.", + "type": "Tool", + "template_id": "luhn_check", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "number", + "type": "Text_Generic", + "description": "Number string", + "value": "42\n" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "false" + } + ], + "narrative": "The Truth Balance. A magical scale used to verify the purity of magical sequences. It requires input from the Spell Weaver to perform its judgment." + }, + { + "id": "code_py_exec", + "name": "Python Executor", + "description": "Run limited Python: only safe builtins.", + "type": "Tool", + "template_id": "code_py_exec", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "code", + "type": "Code_Python", + "description": "Python code", + "value": "x = 42\nprint(x)" + } + ], + "outputs": [ + { + "name": "stdout", + "type": "Text_Generic", + "description": "Standard Output (includes errors if any)", + "value": "42\n" + } + ], + "narrative": "The Spell Weaver. An enchanted focal crystal capable of executing complex incantations. It requires input from the Ancient Scroll to begin its casting." + }, + { + "id": "item_7", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_7", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Code_Python", + "description": "The integer", + "value": "x = 42\nprint(x)" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "x = 42\nprint(x)" + } + }, + "narrative": "The Ancient Scroll. A fragile, crumbling parchment containing forgotten incantations. It rests quietly on a pedestal." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "The Celestial Map. A glowing star chart depicting long-lost constellations and pathways." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "(no output)" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "987654321098765432109876" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Terminal 1 processed slot A successfully." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "Terminal 1 processed slot A successfully.", + "hex_output": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "narrative": "The Great Altar. A majestic stone altar humming with latent power. It requires inputs from both the Arcane Loom and the High Transmuter to reveal its secrets." + }, + { + "id": "num_base_convert", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "987654321098765432109876" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "13307" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": 4177334102 + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "987654321098765432109876" + } + ], + "narrative": "The High Transmuter. A massive alchemical array for shifting the very fabric of reality. It requires inputs from the Lesser Transmuter, the Inverse Astrolabe, and the Fire Oracle." + }, + { + "id": "num_base_convert_74cb", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "987654321098765432109876" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": 3595227230 + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "13307" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "987654321098765432109876" + } + ], + "init": { + "inputs": { + "s": "987654321098765432109876" + }, + "outputs": {} + }, + "narrative": "The Lesser Transmuter. A modest alchemical station for basic magical shifts. It requires inputs from both the Rune Checker and the Inverse Astrolabe." + }, + { + "id": "checksum_crc32", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "deadbeef1234567890abcdef" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "d64ad05e" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3595227230 + } + ], + "init": { + "inputs": { + "hex": "deadbeef1234567890abcdef" + }, + "outputs": {} + }, + "narrative": "The Rune Checker. An intricate mystical abacus used to verify the integrity of runic spells. Its beads wait to be aligned." + }, + { + "id": "terminal_1_5fdb", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this terminal" + }, + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "