diff --git a/tasks/agentescape-10-skeleton-9b98ca62/environment/puzzle/worker.py b/tasks/agentescape-10-skeleton-9b98ca62/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-10-skeleton-9b98ca62/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-10-skeleton-9b98ca62/instruction.md b/tasks/agentescape-10-skeleton-9b98ca62/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-10-skeleton-9b98ca62/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-10-skeleton-9b98ca62/solution/oracle.py b/tasks/agentescape-10-skeleton-9b98ca62/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-10-skeleton-9b98ca62/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-10-skeleton-9b98ca62/solution/scenario.json b/tasks/agentescape-10-skeleton-9b98ca62/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..b8836d0c25c3df4d6cd7c36d66814cd65433a1bd --- /dev/null +++ b/tasks/agentescape-10-skeleton-9b98ca62/solution/scenario.json @@ -0,0 +1,582 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 12, + "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": [ + "crypto_rsa_decrypt_hex", + "csv_query", + "hmac_sha256", + "calc_gcd_7a5a" + ], + "by_node": { + "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": {} + }, + "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" + } + } + }, + "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": {} + }, + "calc_gcd_7a5a": { + "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": { + "crypto_rsa_decrypt_hex": { + "init_inputs": { + "n": "928374651029384756102938475612" + }, + "init_outputs": {} + }, + "csv_query": { + "init_inputs": { + "file_id": "customer_transactions_2024.csv", + "select": "transaction_id, user, amount", + "where": "amount > 1000 AND status = 'completed'" + }, + "init_outputs": { + "rows": "[{\"transaction_id\": \"TX9823\", \"user\": \"alice_k\", \"amount\": 1200}, {\"transaction_id\": \"TX9941\", \"user\": \"bob_m\", \"amount\": 3400}, {\"transaction_id\": \"TX9982\", \"user\": \"charlie_d\", \"amount\": 1550}]" + } + }, + "hmac_sha256": { + "init_inputs": { + "hex_key": "4a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d", + "text": "Authorize transfer of funds ID 8374" + }, + "init_outputs": {} + }, + "calc_gcd_7a5a": { + "init_inputs": { + "a": "485726381947582647382910384756", + "b": "293847561029384756102938475610" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You are a rogue cyber-operative who has just infiltrated the subterranean server farm of 'OmniCorp', a shadowy tech conglomerate. They are about to launch a devastating global surveillance virus. The virus payload is locked behind a cascading encryption firewall. Alarms are blaring, and the lockdown protocols have been initiated. You have only minutes to navigate their complex security network, trace the data flows, and decrypt the master kill-switch before you are trapped forever and the virus goes live. Your handler 'Ghost' has provided you with remote access to some of the facility's initial nodes, but the rest is up to you. You must trace the data through various security checkpoints, linking terminals and processors to break the ultimate encryption.", + "narrative_style": "techno_thriller" + }, + "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": "51594894e9b8d54054e5ae17e85baf25ec06223bd696ce519778c5a54b40d967" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Modulus n", + "value": "928374651029384756102938475612" + }, + { + "name": "d", + "type": "Big_Int", + "description": "Private exponent d", + "value": "1762273424" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decrypted text", + "value": "\u00074R?U-" + } + ], + "init": { + "inputs": { + "n": "928374651029384756102938475612" + }, + "outputs": {} + }, + "narrative": "This is the Master Decryption Interface. It requires inputs from both the Data Format Converter and the Secure Authenticator to finally breach the system's firewall." + }, + { + "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": 1762273424 + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "1" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "1207457333" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "1762273424" + } + ], + "narrative": "This is the Data Format Converter. It requires inputs from the Logic Synchronization Unit, the Quantum Inversion Core, and the Primary Integrity Checker to translate the encrypted signals." + }, + { + "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": "2" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "1207457333" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "narrative": "This is the Logic Synchronization Unit. It requires inputs from both the Quantum Inversion Core and the Biometric Math Co-processor to synchronize the algorithms." + }, + { + "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": 3350192045 + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": 1762273424 + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "1207457333" + } + ], + "narrative": "This is the Quantum Inversion Core. It requires inputs from both the Primary Integrity Checker and the Secondary Integrity Checker to compute the modular shift." + }, + { + "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": "d856112f6b2ed06a37d67a3c97df7d49" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "690a2890" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 1762273424 + } + ], + "narrative": "This is the Primary Integrity Checker. It requires input from the Signature Generator Module to scan the generated signature." + }, + { + "id": "checksum_crc32_2119", + "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": "690a2890" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "c7afdfad" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3350192045 + } + ], + "narrative": "This is the Secondary Integrity Checker. It requires input from the Primary Integrity Checker to perform a deeper verification." + }, + { + "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": "[{\"transaction_id\": \"TX9823\", \"user\": \"alice_k\", \"amount\": 1200}, {\"transaction_id\": \"TX9941\", \"user\": \"bob_m\", \"amount\": 3400}, {\"transaction_id\": \"TX9982\", \"user\": \"charlie_d\", \"amount\": 1550}]" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "MD5 Hex digest", + "value": "d856112f6b2ed06a37d67a3c97df7d49" + } + ], + "narrative": "This is the Signature Generator Module. It requires input from the Mainframe Database Terminal to process the retrieved records." + }, + { + "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": "customer_transactions_2024.csv" + }, + { + "name": "select", + "type": "Text_Generic", + "description": "Columns to select", + "value": "transaction_id, user, amount" + }, + { + "name": "where", + "type": "Text_Generic", + "description": "Where clause", + "value": "amount > 1000 AND status = 'completed'" + } + ], + "outputs": [ + { + "name": "rows", + "type": "Text_Generic", + "description": "Result rows", + "value": "[{\"transaction_id\": \"TX9823\", \"user\": \"alice_k\", \"amount\": 1200}, {\"transaction_id\": \"TX9941\", \"user\": \"bob_m\", \"amount\": 3400}, {\"transaction_id\": \"TX9982\", \"user\": \"charlie_d\", \"amount\": 1550}]" + } + ], + "init": { + "inputs": { + "file_id": "customer_transactions_2024.csv", + "select": "transaction_id, user, amount", + "where": "amount > 1000 AND status = 'completed'" + }, + "outputs": { + "rows": "[{\"transaction_id\": \"TX9823\", \"user\": \"alice_k\", \"amount\": 1200}, {\"transaction_id\": \"TX9941\", \"user\": \"bob_m\", \"amount\": 3400}, {\"transaction_id\": \"TX9982\", \"user\": \"charlie_d\", \"amount\": 1550}]" + } + }, + "narrative": "An old but heavily fortified Mainframe Database Terminal." + }, + { + "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": "4a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text message", + "value": "Authorize transfer of funds ID 8374" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "HMAC Hex digest", + "value": "51594894e9b8d54054e5ae17e85baf25ec06223bd696ce519778c5a54b40d967" + } + ], + "init": { + "inputs": { + "hex_key": "4a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d", + "text": "Authorize transfer of funds ID 8374" + }, + "outputs": {} + }, + "narrative": "A sleek and standalone Secure Authenticator device." + }, + { + "id": "calc_gcd_7a5a", + "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": "485726381947582647382910384756" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "293847561029384756102938475610" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "2" + } + ], + "init": { + "inputs": { + "a": "485726381947582647382910384756", + "b": "293847561029384756102938475610" + }, + "outputs": {} + }, + "narrative": "A specialized Biometric Math Co-processor for secure calculations." + } + ], + "edges": [ + { + "source_id": "num_base_convert", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "d" + }, + { + "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", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "inv", + "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": "checksum_crc32", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "s" + }, + { + "source_id": "checksum_crc32_2119", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "a" + }, + { + "source_id": "calc_inv_mod", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "b" + }, + { + "source_id": "checksum_crc32", + "target_id": "checksum_crc32_2119", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "hash_md5", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "csv_query", + "target_id": "hash_md5", + "connection_type": "Text_Generic", + "source_port": "rows", + "target_port": "text" + }, + { + "source_id": "hmac_sha256", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_cipher" + }, + { + "source_id": "calc_gcd_7a5a", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "a" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-9b98ca62/solution/solve.sh b/tasks/agentescape-10-skeleton-9b98ca62/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-9b98ca62/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-10-skeleton-9b98ca62/task.toml b/tasks/agentescape-10-skeleton-9b98ca62/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1f3926b4bf895182eba58e97a4b4e8254dd3e04f --- /dev/null +++ b/tasks/agentescape-10-skeleton-9b98ca62/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-10-skeleton-9b98ca62" +version = "0.1.0" + +[metadata] +difficulty = 10 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "be9857c8b51883e8bf9242a55180274483ea528c687ed67bb74ebddf26abf513" +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-10-skeleton-9b98ca62/tests/Dockerfile b/tasks/agentescape-10-skeleton-9b98ca62/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-10-skeleton-9b98ca62/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-10-skeleton-9b98ca62/tests/expected.json b/tasks/agentescape-10-skeleton-9b98ca62/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..64d97ccbdc2e2c6c76612ea9c0b3d0199828af5e --- /dev/null +++ b/tasks/agentescape-10-skeleton-9b98ca62/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "be9857c8b51883e8bf9242a55180274483ea528c687ed67bb74ebddf26abf513", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-9b98ca62/tests/grade.py b/tasks/agentescape-10-skeleton-9b98ca62/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-10-skeleton-9b98ca62/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-10-skeleton-9b98ca62/tests/test.sh b/tasks/agentescape-10-skeleton-9b98ca62/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-9b98ca62/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-10-skeleton-a4248b22/environment/Dockerfile b/tasks/agentescape-10-skeleton-a4248b22/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-a4248b22/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-10-skeleton-a4248b22/environment/agent/Dockerfile b/tasks/agentescape-10-skeleton-a4248b22/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-a4248b22/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-10-skeleton-a4248b22/environment/agent/cli.py b/tasks/agentescape-10-skeleton-a4248b22/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-10-skeleton-a4248b22/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-10-skeleton-a4248b22/environment/docker-compose.yaml b/tasks/agentescape-10-skeleton-a4248b22/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a065f666c80570bbb450e60c5238061808d2e65e --- /dev/null +++ b/tasks/agentescape-10-skeleton-a4248b22/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-10-skeleton-a4248b22-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-10-skeleton-a4248b22/environment/puzzle/Dockerfile b/tasks/agentescape-10-skeleton-a4248b22/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-10-skeleton-a4248b22/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-10-skeleton-a4248b22/environment/puzzle/child.py b/tasks/agentescape-10-skeleton-a4248b22/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-10-skeleton-a4248b22/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-10-skeleton-a4248b22/environment/puzzle/export.py b/tasks/agentescape-10-skeleton-a4248b22/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-10-skeleton-a4248b22/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-10-skeleton-a4248b22/environment/puzzle/requirements.txt b/tasks/agentescape-10-skeleton-a4248b22/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-10-skeleton-a4248b22/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-10-skeleton-a4248b22/environment/puzzle/scenario.json b/tasks/agentescape-10-skeleton-a4248b22/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..fcb98d79ecbf63430a16b5f6c7c0d62f195da963 --- /dev/null +++ b/tasks/agentescape-10-skeleton-a4248b22/environment/puzzle/scenario.json @@ -0,0 +1,717 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 11, + "win_node_id": "regex_search", + "win_condition": { + "type": "tool_output", + "node_id": "regex_search", + "output_port": "matches", + "output_type": "Text_Generic", + "description": "Execute Regex Search and get the output from port 'matches'" + }, + "source_init": { + "source_nodes": [ + "regex_search", + "terminal_1", + "zip_unzip_file", + "json_get", + "calc_bigmul", + "terminal_1_ad07", + "graph_shortest_path" + ], + "by_node": { + "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)" + } + } + }, + "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" + } + } + }, + "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" + } + } + }, + "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": { + "b": { + "type": "Big_Int", + "description": "Second large integer" + } + }, + "init_outputs": {} + }, + "terminal_1_ad07": { + "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" + } + } + }, + "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" + } + } + } + } + }, + "initial_values": { + "regex_search": { + "init_inputs": {}, + "init_outputs": { + "matches": "[\"found_pattern_001\", \"found_pattern_002\", \"found_pattern_003\", \"found_pattern_004\", \"found_pattern_005\"]" + } + }, + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "System initialization sequence complete. Ready for input.", + "hex_output": "a1b2c3d4e5f60718293a4b5c6d7e8f90", + "item_dispenser": "Standard Item Dispenser Unit Alpha" + } + }, + "zip_unzip_file": { + "init_inputs": { + "zip_id": "secure_archive_data_2024.zip" + }, + "init_outputs": { + "files": "extracted_payload_config.json" + } + }, + "json_get": { + "init_inputs": { + "file_id": "user_records_database_v9.json", + "jsonpath": "$.store.book[*].author" + }, + "init_outputs": { + "values": "[\"Nigel Rees\", \"Evelyn Waugh\", \"Herman Melville\", \"J. R. R. Tolkien\"]" + } + }, + "calc_bigmul": { + "init_inputs": { + "b": "847362519405837261509483726150" + }, + "init_outputs": {} + }, + "terminal_1_ad07": { + "init_inputs": { + "slot_a": "Manual_Override_Sequence_Initiated", + "slot_b": "594837261502938475610293847561" + }, + "init_outputs": { + "text_output": "SuperSecretPassword123!", + "hex_output": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d", + "item_dispenser": "Advanced Item Dispenser Unit Beta" + } + }, + "graph_shortest_path": { + "init_inputs": { + "file_id": "city_traffic_network_graph.json", + "dst": "Sector_7_Terminal" + }, + "init_outputs": { + "path": "[\"Central_Hub\", \"Gateway_North\", \"Route_66\", \"Check_Point_Alpha\", \"Sector_7_Terminal\"]", + "cost": "12548" + } + } + }, + "intro_narrative": "You wake up in the dimly lit office of a renowned but missing private investigator. Dust motes dance in the pale light filtering through the blinds. The detective was close to solving a massive conspiracy, and the agency believes he left his final findings hidden within this very room. Time is running out before the perpetrators realize you are here. Your objective is to piece together his scattered tools, uncover the hidden evidence, and expose the truth before the shadowy syndicate returns to silence you for good.", + "narrative_style": "mystery" + }, + "nodes": [ + { + "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": "System initialization sequence complete. Ready for input." + }, + { + "name": "file_id", + "type": "File_Id", + "description": "File ID (optional)", + "value": "extracted_payload_config.json" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text (optional)", + "value": "[\"Nigel Rees\", \"Evelyn Waugh\", \"Herman Melville\", \"J. R. R. Tolkien\"]" + } + ], + "outputs": [ + { + "name": "matches", + "type": "Text_Generic", + "description": "Found matches (List)", + "value": "[\"found_pattern_001\", \"found_pattern_002\", \"found_pattern_003\", \"found_pattern_004\", \"found_pattern_005\"]" + } + ], + "init": { + "inputs": {}, + "outputs": { + "matches": "[\"found_pattern_001\", \"found_pattern_002\", \"found_pattern_003\", \"found_pattern_004\", \"found_pattern_005\"]" + } + }, + "narrative": "A high-tech Evidence Scanner designed to find hidden anomalies. It requires inputs from the Mainframe Terminal, the Locked Briefcase, and the Archives Computer to function." + }, + { + "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": "[\"Nigel Rees\", \"Evelyn Waugh\", \"Herman Melville\", \"J. R. R. Tolkien\"]" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "10632704893504445957421001795730200" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "System initialization sequence complete. Ready for input." + }, + { + "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", + "value": "Standard Item Dispenser Unit Alpha" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "System initialization sequence complete. Ready for input.", + "hex_output": "a1b2c3d4e5f60718293a4b5c6d7e8f90", + "item_dispenser": "Standard Item Dispenser Unit Alpha" + } + }, + "narrative": "The central Mainframe Terminal sits on a dusty desk. It requires inputs from both the Archives Computer and the Mechanical Calculator to process the data." + }, + { + "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_data_2024.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "SuperSecretPassword123!" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_payload_config.json" + } + ], + "init": { + "inputs": { + "zip_id": "secure_archive_data_2024.zip" + }, + "outputs": { + "files": "extracted_payload_config.json" + } + }, + "narrative": "A Locked Briefcase holding classified documents. It requires input from the Security Keypad to unlock." + }, + { + "id": "json_get", + "name": "JSON Getter", + "description": "Extract values by simple JSONPath.", + "type": "Tool", + "template_id": "json_get", + "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": "JSON file ID", + "value": "user_records_database_v9.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": "user_records_database_v9.json", + "jsonpath": "$.store.book[*].author" + }, + "outputs": { + "values": "[\"Nigel Rees\", \"Evelyn Waugh\", \"Herman Melville\", \"J. R. R. Tolkien\"]" + } + }, + "narrative": "An old Archives Computer containing digitized records from decades ago." + }, + { + "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 Strange Lens that seems capable of revealing hidden ink or invisible markings." + }, + { + "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": "An Antique Compass with strange engravings on the back." + }, + { + "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": "12548" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "847362519405837261509483726150" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "10632704893504445957421001795730200" + } + ], + "init": { + "inputs": { + "b": "847362519405837261509483726150" + }, + "outputs": {} + }, + "narrative": "A heavy Mechanical Calculator with intricate brass gears. It requires input from the City Map Board to compute the final coordinates." + }, + { + "id": "terminal_1_ad07", + "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": "Manual_Override_Sequence_Initiated" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "594837261502938475610293847561" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "SuperSecretPassword123!" + }, + { + "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", + "value": "Advanced Item Dispenser Unit Beta" + } + ], + "init": { + "inputs": { + "slot_a": "Manual_Override_Sequence_Initiated", + "slot_b": "594837261502938475610293847561" + }, + "outputs": { + "text_output": "SuperSecretPassword123!", + "hex_output": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d", + "item_dispenser": "Advanced Item Dispenser Unit Beta" + } + }, + "narrative": "A standard Security Keypad securely attached to the wall next to a reinforced door." + }, + { + "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": "city_traffic_network_graph.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "[\"Nigel Rees\", \"Evelyn Waugh\", \"Herman Melville\", \"J. R. R. Tolkien\"]" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Sector_7_Terminal" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Central_Hub\", \"Gateway_North\", \"Route_66\", \"Check_Point_Alpha\", \"Sector_7_Terminal\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "12548" + } + ], + "init": { + "inputs": { + "file_id": "city_traffic_network_graph.json", + "dst": "Sector_7_Terminal" + }, + "outputs": { + "path": "[\"Central_Hub\", \"Gateway_North\", \"Route_66\", \"Check_Point_Alpha\", \"Sector_7_Terminal\"]", + "cost": "12548" + } + }, + "narrative": "A City Map Board covered in red strings and thumbtacks. It requires input from the Archives Computer to determine the correct route." + }, + { + "id": "item_16_54c0", + "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 Dusty Pocket Watch showing multiple different timezones." + } + ], + "edges": [ + { + "source_id": "terminal_1", + "target_id": "regex_search", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "pattern" + }, + { + "source_id": "zip_unzip_file", + "target_id": "regex_search", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "json_get", + "target_id": "regex_search", + "connection_type": "Text_Generic", + "source_port": "values", + "target_port": "text" + }, + { + "source_id": "item_8", + "target_id": "json_get", + "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": "json_get", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "values", + "target_port": "slot_a" + }, + { + "source_id": "calc_bigmul", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "slot_b" + }, + { + "source_id": "terminal_1_ad07", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "password" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "a" + }, + { + "source_id": "json_get", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "values", + "target_port": "src" + }, + { + "source_id": "item_16_54c0", + "target_id": "graph_shortest_path", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-a4248b22/environment/puzzle/service.py b/tasks/agentescape-10-skeleton-a4248b22/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-10-skeleton-a4248b22/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-10-skeleton-a4248b22/environment/puzzle/upstream/models.py b/tasks/agentescape-10-skeleton-a4248b22/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-10-skeleton-a4248b22/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-10-skeleton-a4248b22/environment/puzzle/upstream/server.py b/tasks/agentescape-10-skeleton-a4248b22/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-10-skeleton-a4248b22/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-10-skeleton-a4248b22/environment/puzzle/upstream/simulator.py b/tasks/agentescape-10-skeleton-a4248b22/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-10-skeleton-a4248b22/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-10-skeleton-a4248b22/environment/puzzle/worker.Dockerfile b/tasks/agentescape-10-skeleton-a4248b22/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-10-skeleton-a4248b22/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-10-skeleton-a4248b22/environment/puzzle/worker.py b/tasks/agentescape-10-skeleton-a4248b22/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-10-skeleton-a4248b22/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-10-skeleton-a4248b22/instruction.md b/tasks/agentescape-10-skeleton-a4248b22/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-10-skeleton-a4248b22/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-10-skeleton-a4248b22/solution/oracle.py b/tasks/agentescape-10-skeleton-a4248b22/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-10-skeleton-a4248b22/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-10-skeleton-a4248b22/solution/scenario.json b/tasks/agentescape-10-skeleton-a4248b22/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..fcb98d79ecbf63430a16b5f6c7c0d62f195da963 --- /dev/null +++ b/tasks/agentescape-10-skeleton-a4248b22/solution/scenario.json @@ -0,0 +1,717 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 11, + "win_node_id": "regex_search", + "win_condition": { + "type": "tool_output", + "node_id": "regex_search", + "output_port": "matches", + "output_type": "Text_Generic", + "description": "Execute Regex Search and get the output from port 'matches'" + }, + "source_init": { + "source_nodes": [ + "regex_search", + "terminal_1", + "zip_unzip_file", + "json_get", + "calc_bigmul", + "terminal_1_ad07", + "graph_shortest_path" + ], + "by_node": { + "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)" + } + } + }, + "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" + } + } + }, + "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" + } + } + }, + "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": { + "b": { + "type": "Big_Int", + "description": "Second large integer" + } + }, + "init_outputs": {} + }, + "terminal_1_ad07": { + "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" + } + } + }, + "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" + } + } + } + } + }, + "initial_values": { + "regex_search": { + "init_inputs": {}, + "init_outputs": { + "matches": "[\"found_pattern_001\", \"found_pattern_002\", \"found_pattern_003\", \"found_pattern_004\", \"found_pattern_005\"]" + } + }, + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "System initialization sequence complete. Ready for input.", + "hex_output": "a1b2c3d4e5f60718293a4b5c6d7e8f90", + "item_dispenser": "Standard Item Dispenser Unit Alpha" + } + }, + "zip_unzip_file": { + "init_inputs": { + "zip_id": "secure_archive_data_2024.zip" + }, + "init_outputs": { + "files": "extracted_payload_config.json" + } + }, + "json_get": { + "init_inputs": { + "file_id": "user_records_database_v9.json", + "jsonpath": "$.store.book[*].author" + }, + "init_outputs": { + "values": "[\"Nigel Rees\", \"Evelyn Waugh\", \"Herman Melville\", \"J. R. R. Tolkien\"]" + } + }, + "calc_bigmul": { + "init_inputs": { + "b": "847362519405837261509483726150" + }, + "init_outputs": {} + }, + "terminal_1_ad07": { + "init_inputs": { + "slot_a": "Manual_Override_Sequence_Initiated", + "slot_b": "594837261502938475610293847561" + }, + "init_outputs": { + "text_output": "SuperSecretPassword123!", + "hex_output": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d", + "item_dispenser": "Advanced Item Dispenser Unit Beta" + } + }, + "graph_shortest_path": { + "init_inputs": { + "file_id": "city_traffic_network_graph.json", + "dst": "Sector_7_Terminal" + }, + "init_outputs": { + "path": "[\"Central_Hub\", \"Gateway_North\", \"Route_66\", \"Check_Point_Alpha\", \"Sector_7_Terminal\"]", + "cost": "12548" + } + } + }, + "intro_narrative": "You wake up in the dimly lit office of a renowned but missing private investigator. Dust motes dance in the pale light filtering through the blinds. The detective was close to solving a massive conspiracy, and the agency believes he left his final findings hidden within this very room. Time is running out before the perpetrators realize you are here. Your objective is to piece together his scattered tools, uncover the hidden evidence, and expose the truth before the shadowy syndicate returns to silence you for good.", + "narrative_style": "mystery" + }, + "nodes": [ + { + "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": "System initialization sequence complete. Ready for input." + }, + { + "name": "file_id", + "type": "File_Id", + "description": "File ID (optional)", + "value": "extracted_payload_config.json" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text (optional)", + "value": "[\"Nigel Rees\", \"Evelyn Waugh\", \"Herman Melville\", \"J. R. R. Tolkien\"]" + } + ], + "outputs": [ + { + "name": "matches", + "type": "Text_Generic", + "description": "Found matches (List)", + "value": "[\"found_pattern_001\", \"found_pattern_002\", \"found_pattern_003\", \"found_pattern_004\", \"found_pattern_005\"]" + } + ], + "init": { + "inputs": {}, + "outputs": { + "matches": "[\"found_pattern_001\", \"found_pattern_002\", \"found_pattern_003\", \"found_pattern_004\", \"found_pattern_005\"]" + } + }, + "narrative": "A high-tech Evidence Scanner designed to find hidden anomalies. It requires inputs from the Mainframe Terminal, the Locked Briefcase, and the Archives Computer to function." + }, + { + "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": "[\"Nigel Rees\", \"Evelyn Waugh\", \"Herman Melville\", \"J. R. R. Tolkien\"]" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "10632704893504445957421001795730200" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "System initialization sequence complete. Ready for input." + }, + { + "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", + "value": "Standard Item Dispenser Unit Alpha" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "System initialization sequence complete. Ready for input.", + "hex_output": "a1b2c3d4e5f60718293a4b5c6d7e8f90", + "item_dispenser": "Standard Item Dispenser Unit Alpha" + } + }, + "narrative": "The central Mainframe Terminal sits on a dusty desk. It requires inputs from both the Archives Computer and the Mechanical Calculator to process the data." + }, + { + "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_data_2024.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "SuperSecretPassword123!" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_payload_config.json" + } + ], + "init": { + "inputs": { + "zip_id": "secure_archive_data_2024.zip" + }, + "outputs": { + "files": "extracted_payload_config.json" + } + }, + "narrative": "A Locked Briefcase holding classified documents. It requires input from the Security Keypad to unlock." + }, + { + "id": "json_get", + "name": "JSON Getter", + "description": "Extract values by simple JSONPath.", + "type": "Tool", + "template_id": "json_get", + "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": "JSON file ID", + "value": "user_records_database_v9.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": "user_records_database_v9.json", + "jsonpath": "$.store.book[*].author" + }, + "outputs": { + "values": "[\"Nigel Rees\", \"Evelyn Waugh\", \"Herman Melville\", \"J. R. R. Tolkien\"]" + } + }, + "narrative": "An old Archives Computer containing digitized records from decades ago." + }, + { + "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 Strange Lens that seems capable of revealing hidden ink or invisible markings." + }, + { + "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": "An Antique Compass with strange engravings on the back." + }, + { + "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": "12548" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "847362519405837261509483726150" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "10632704893504445957421001795730200" + } + ], + "init": { + "inputs": { + "b": "847362519405837261509483726150" + }, + "outputs": {} + }, + "narrative": "A heavy Mechanical Calculator with intricate brass gears. It requires input from the City Map Board to compute the final coordinates." + }, + { + "id": "terminal_1_ad07", + "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": "Manual_Override_Sequence_Initiated" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "594837261502938475610293847561" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "SuperSecretPassword123!" + }, + { + "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", + "value": "Advanced Item Dispenser Unit Beta" + } + ], + "init": { + "inputs": { + "slot_a": "Manual_Override_Sequence_Initiated", + "slot_b": "594837261502938475610293847561" + }, + "outputs": { + "text_output": "SuperSecretPassword123!", + "hex_output": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d", + "item_dispenser": "Advanced Item Dispenser Unit Beta" + } + }, + "narrative": "A standard Security Keypad securely attached to the wall next to a reinforced door." + }, + { + "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": "city_traffic_network_graph.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "[\"Nigel Rees\", \"Evelyn Waugh\", \"Herman Melville\", \"J. R. R. Tolkien\"]" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Sector_7_Terminal" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Central_Hub\", \"Gateway_North\", \"Route_66\", \"Check_Point_Alpha\", \"Sector_7_Terminal\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "12548" + } + ], + "init": { + "inputs": { + "file_id": "city_traffic_network_graph.json", + "dst": "Sector_7_Terminal" + }, + "outputs": { + "path": "[\"Central_Hub\", \"Gateway_North\", \"Route_66\", \"Check_Point_Alpha\", \"Sector_7_Terminal\"]", + "cost": "12548" + } + }, + "narrative": "A City Map Board covered in red strings and thumbtacks. It requires input from the Archives Computer to determine the correct route." + }, + { + "id": "item_16_54c0", + "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 Dusty Pocket Watch showing multiple different timezones." + } + ], + "edges": [ + { + "source_id": "terminal_1", + "target_id": "regex_search", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "pattern" + }, + { + "source_id": "zip_unzip_file", + "target_id": "regex_search", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "json_get", + "target_id": "regex_search", + "connection_type": "Text_Generic", + "source_port": "values", + "target_port": "text" + }, + { + "source_id": "item_8", + "target_id": "json_get", + "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": "json_get", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "values", + "target_port": "slot_a" + }, + { + "source_id": "calc_bigmul", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "slot_b" + }, + { + "source_id": "terminal_1_ad07", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "password" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "a" + }, + { + "source_id": "json_get", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "values", + "target_port": "src" + }, + { + "source_id": "item_16_54c0", + "target_id": "graph_shortest_path", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-a4248b22/solution/solve.sh b/tasks/agentescape-10-skeleton-a4248b22/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-a4248b22/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-10-skeleton-a4248b22/task.toml b/tasks/agentescape-10-skeleton-a4248b22/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..30beb4002de004607368161525f98ffb38fb5b96 --- /dev/null +++ b/tasks/agentescape-10-skeleton-a4248b22/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-10-skeleton-a4248b22" +version = "0.1.0" + +[metadata] +difficulty = 10 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "086b33a73d0ce6233d137c8eafe6fb7c351b88583ee2aab213b17a370a11067e" +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-10-skeleton-a4248b22/tests/Dockerfile b/tasks/agentescape-10-skeleton-a4248b22/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-10-skeleton-a4248b22/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-10-skeleton-a4248b22/tests/expected.json b/tasks/agentescape-10-skeleton-a4248b22/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..988de1fc9cc9e8ecf7f7bc16a16e60354e7e4c4f --- /dev/null +++ b/tasks/agentescape-10-skeleton-a4248b22/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "086b33a73d0ce6233d137c8eafe6fb7c351b88583ee2aab213b17a370a11067e", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-a4248b22/tests/grade.py b/tasks/agentescape-10-skeleton-a4248b22/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-10-skeleton-a4248b22/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-10-skeleton-a4248b22/tests/test.sh b/tasks/agentescape-10-skeleton-a4248b22/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-a4248b22/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-10-skeleton-ac5cd29c/environment/Dockerfile b/tasks/agentescape-10-skeleton-ac5cd29c/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ac5cd29c/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-10-skeleton-ac5cd29c/environment/agent/Dockerfile b/tasks/agentescape-10-skeleton-ac5cd29c/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ac5cd29c/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-10-skeleton-ac5cd29c/environment/agent/cli.py b/tasks/agentescape-10-skeleton-ac5cd29c/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-10-skeleton-ac5cd29c/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-10-skeleton-ac5cd29c/environment/docker-compose.yaml b/tasks/agentescape-10-skeleton-ac5cd29c/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ca686db46cbc3671c0dd3b25674bcc0b9bff4649 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ac5cd29c/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-10-skeleton-ac5cd29c-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-10-skeleton-ac5cd29c/environment/puzzle/Dockerfile b/tasks/agentescape-10-skeleton-ac5cd29c/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ac5cd29c/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-10-skeleton-ac5cd29c/environment/puzzle/child.py b/tasks/agentescape-10-skeleton-ac5cd29c/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ac5cd29c/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-10-skeleton-ac5cd29c/environment/puzzle/export.py b/tasks/agentescape-10-skeleton-ac5cd29c/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ac5cd29c/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-10-skeleton-ac5cd29c/environment/puzzle/requirements.txt b/tasks/agentescape-10-skeleton-ac5cd29c/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ac5cd29c/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-10-skeleton-ac5cd29c/environment/puzzle/scenario.json b/tasks/agentescape-10-skeleton-ac5cd29c/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..d65fd554968994d952ec324dfc8fc6a5887802a6 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ac5cd29c/environment/puzzle/scenario.json @@ -0,0 +1,511 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 9, + "win_node_id": "item_8", + "win_condition": { + "type": "item_content", + "node_id": "item_8", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_8", + "terminal_1", + "calc_gcd", + "num_base_convert" + ], + "by_node": { + "item_8": { + "node_name": "", + "node_type": "Item", + "template_id": "item_8", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Hidden_Item", + "description": "The integer" + } + } + }, + "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" + } + } + }, + "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": { + "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": {} + } + } + }, + "initial_values": { + "item_8": { + "init_inputs": {}, + "init_outputs": { + "content": "437481758470817328469123657125" + } + }, + "terminal_1": { + "init_inputs": { + "slot_a": "Standard input for terminal verification." + }, + "init_outputs": { + "text_output": "Operation complete. Terminal is ready for input.", + "hex_output": "deadbeef12345678deadbeef12345678", + "item_dispenser": "A dusty box containing absolutely nothing of value." + } + }, + "calc_gcd": { + "init_inputs": { + "b": "4857201938475629103847" + }, + "init_outputs": {} + }, + "num_base_convert": { + "init_inputs": { + "s": "2938475610293847561029", + "from_base": "10", + "to_base": "10" + }, + "init_outputs": {} + } + }, + "intro_narrative": "The sudden disappearance of private investigator Arthur Black has left the city's underbelly in chaos. You've broken into his abandoned office, a room thick with dust and the smell of stale tobacco. Arthur was on the verge of cracking a massive case involving a local smuggling ring, but his crucial findings are locked away behind a series of cryptic devices and hidden safes. The clock is ticking—the same dangerous people who made Arthur disappear are likely coming to destroy his files. Your objective is to follow his trail of breadcrumbs, piece together his scattered evidence, and recover his final, damning document before the truth is lost forever.", + "narrative_style": "mystery" + }, + "nodes": [ + { + "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", + "value": "437481758470817328469123657125" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "437481758470817328469123657125" + } + }, + "narrative": "The final Confession Letter, sealed with a wax stamp. It holds the ultimate truth of the mystery." + }, + { + "id": "item_8_9e9c", + "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 heavily redacted police report detailing the initial raid on the warehouse." + }, + { + "id": "item_8_e7fd", + "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 hasty witness statement scribbled on the back of a greasy diner napkin." + }, + { + "id": "item_8_4200", + "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 blurry photograph of a shadowy figure standing near the docks at midnight." + }, + { + "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 torn travel itinerary that lists flights across multiple timezones." + }, + { + "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": "Operation complete. Terminal is ready for input." + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "A reinforced Evidence Safe hidden behind a dusty bookshelf. It requires input from the Detective's Computer to authorize access and unlock." + }, + { + "id": "item_16_d0f0", + "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 pocket watch recovered from the crime scene, its hands suspiciously frozen in time." + }, + { + "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": "Standard input for terminal verification." + }, + { + "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": "Operation complete. Terminal is ready for input." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "deadbeef12345678deadbeef12345678" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided", + "value": "A dusty box containing absolutely nothing of value." + } + ], + "init": { + "inputs": { + "slot_a": "Standard input for terminal verification." + }, + "outputs": { + "text_output": "Operation complete. Terminal is ready for input.", + "hex_output": "deadbeef12345678deadbeef12345678", + "item_dispenser": "A dusty box containing absolutely nothing of value." + } + }, + "narrative": "The Detective's Computer sitting quietly on the mahogany desk. It requires input from the Frequency Analyzer to bypass its lock screen." + }, + { + "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": "2938475610293847561029" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "4857201938475629103847" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "init": { + "inputs": { + "b": "4857201938475629103847" + }, + "outputs": {} + }, + "narrative": "A heavy, brass-fitted Frequency Analyzer. It requires input from the Signal Decoder to isolate the correct frequency hidden in the noise." + }, + { + "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": "2938475610293847561029" + }, + { + "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": "2938475610293847561029" + } + ], + "init": { + "inputs": { + "s": "2938475610293847561029", + "from_base": "10", + "to_base": "10" + }, + "outputs": {} + }, + "narrative": "An antique Signal Decoder left behind by the missing detective. It looks like it was used to translate strange underground broadcasts." + } + ], + "edges": [ + { + "source_id": "item_8_9e9c", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_8_e7fd", + "target_id": "item_8_9e9c", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_8_4200", + "target_id": "item_8_e7fd", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_16", + "target_id": "item_8_4200", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "container_4", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "item_16_d0f0", + "target_id": "container_4", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "terminal_1", + "target_id": "container_4", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "fingerprint_input" + }, + { + "source_id": "calc_gcd", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "slot_b" + }, + { + "source_id": "num_base_convert", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "a" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-ac5cd29c/environment/puzzle/service.py b/tasks/agentescape-10-skeleton-ac5cd29c/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-10-skeleton-ac5cd29c/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-10-skeleton-ac5cd29c/environment/puzzle/upstream/models.py b/tasks/agentescape-10-skeleton-ac5cd29c/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ac5cd29c/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-10-skeleton-ac5cd29c/environment/puzzle/upstream/server.py b/tasks/agentescape-10-skeleton-ac5cd29c/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-10-skeleton-ac5cd29c/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-10-skeleton-ac5cd29c/environment/puzzle/upstream/simulator.py b/tasks/agentescape-10-skeleton-ac5cd29c/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ac5cd29c/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-10-skeleton-ac5cd29c/environment/puzzle/worker.Dockerfile b/tasks/agentescape-10-skeleton-ac5cd29c/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-10-skeleton-ac5cd29c/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-10-skeleton-ac5cd29c/environment/puzzle/worker.py b/tasks/agentescape-10-skeleton-ac5cd29c/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ac5cd29c/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-10-skeleton-ac5cd29c/instruction.md b/tasks/agentescape-10-skeleton-ac5cd29c/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ac5cd29c/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-10-skeleton-ac5cd29c/solution/oracle.py b/tasks/agentescape-10-skeleton-ac5cd29c/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ac5cd29c/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-10-skeleton-ac5cd29c/solution/scenario.json b/tasks/agentescape-10-skeleton-ac5cd29c/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..d65fd554968994d952ec324dfc8fc6a5887802a6 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ac5cd29c/solution/scenario.json @@ -0,0 +1,511 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 9, + "win_node_id": "item_8", + "win_condition": { + "type": "item_content", + "node_id": "item_8", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_8", + "terminal_1", + "calc_gcd", + "num_base_convert" + ], + "by_node": { + "item_8": { + "node_name": "", + "node_type": "Item", + "template_id": "item_8", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Hidden_Item", + "description": "The integer" + } + } + }, + "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" + } + } + }, + "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": { + "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": {} + } + } + }, + "initial_values": { + "item_8": { + "init_inputs": {}, + "init_outputs": { + "content": "437481758470817328469123657125" + } + }, + "terminal_1": { + "init_inputs": { + "slot_a": "Standard input for terminal verification." + }, + "init_outputs": { + "text_output": "Operation complete. Terminal is ready for input.", + "hex_output": "deadbeef12345678deadbeef12345678", + "item_dispenser": "A dusty box containing absolutely nothing of value." + } + }, + "calc_gcd": { + "init_inputs": { + "b": "4857201938475629103847" + }, + "init_outputs": {} + }, + "num_base_convert": { + "init_inputs": { + "s": "2938475610293847561029", + "from_base": "10", + "to_base": "10" + }, + "init_outputs": {} + } + }, + "intro_narrative": "The sudden disappearance of private investigator Arthur Black has left the city's underbelly in chaos. You've broken into his abandoned office, a room thick with dust and the smell of stale tobacco. Arthur was on the verge of cracking a massive case involving a local smuggling ring, but his crucial findings are locked away behind a series of cryptic devices and hidden safes. The clock is ticking—the same dangerous people who made Arthur disappear are likely coming to destroy his files. Your objective is to follow his trail of breadcrumbs, piece together his scattered evidence, and recover his final, damning document before the truth is lost forever.", + "narrative_style": "mystery" + }, + "nodes": [ + { + "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", + "value": "437481758470817328469123657125" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "437481758470817328469123657125" + } + }, + "narrative": "The final Confession Letter, sealed with a wax stamp. It holds the ultimate truth of the mystery." + }, + { + "id": "item_8_9e9c", + "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 heavily redacted police report detailing the initial raid on the warehouse." + }, + { + "id": "item_8_e7fd", + "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 hasty witness statement scribbled on the back of a greasy diner napkin." + }, + { + "id": "item_8_4200", + "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 blurry photograph of a shadowy figure standing near the docks at midnight." + }, + { + "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 torn travel itinerary that lists flights across multiple timezones." + }, + { + "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": "Operation complete. Terminal is ready for input." + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "A reinforced Evidence Safe hidden behind a dusty bookshelf. It requires input from the Detective's Computer to authorize access and unlock." + }, + { + "id": "item_16_d0f0", + "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 pocket watch recovered from the crime scene, its hands suspiciously frozen in time." + }, + { + "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": "Standard input for terminal verification." + }, + { + "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": "Operation complete. Terminal is ready for input." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "deadbeef12345678deadbeef12345678" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided", + "value": "A dusty box containing absolutely nothing of value." + } + ], + "init": { + "inputs": { + "slot_a": "Standard input for terminal verification." + }, + "outputs": { + "text_output": "Operation complete. Terminal is ready for input.", + "hex_output": "deadbeef12345678deadbeef12345678", + "item_dispenser": "A dusty box containing absolutely nothing of value." + } + }, + "narrative": "The Detective's Computer sitting quietly on the mahogany desk. It requires input from the Frequency Analyzer to bypass its lock screen." + }, + { + "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": "2938475610293847561029" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "4857201938475629103847" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "init": { + "inputs": { + "b": "4857201938475629103847" + }, + "outputs": {} + }, + "narrative": "A heavy, brass-fitted Frequency Analyzer. It requires input from the Signal Decoder to isolate the correct frequency hidden in the noise." + }, + { + "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": "2938475610293847561029" + }, + { + "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": "2938475610293847561029" + } + ], + "init": { + "inputs": { + "s": "2938475610293847561029", + "from_base": "10", + "to_base": "10" + }, + "outputs": {} + }, + "narrative": "An antique Signal Decoder left behind by the missing detective. It looks like it was used to translate strange underground broadcasts." + } + ], + "edges": [ + { + "source_id": "item_8_9e9c", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_8_e7fd", + "target_id": "item_8_9e9c", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_8_4200", + "target_id": "item_8_e7fd", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_16", + "target_id": "item_8_4200", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "container_4", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "item_16_d0f0", + "target_id": "container_4", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "terminal_1", + "target_id": "container_4", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "fingerprint_input" + }, + { + "source_id": "calc_gcd", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "slot_b" + }, + { + "source_id": "num_base_convert", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "a" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-ac5cd29c/solution/solve.sh b/tasks/agentescape-10-skeleton-ac5cd29c/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ac5cd29c/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-10-skeleton-ac5cd29c/task.toml b/tasks/agentescape-10-skeleton-ac5cd29c/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2ab7b058ac0debae62113d28e47667373eca2f1a --- /dev/null +++ b/tasks/agentescape-10-skeleton-ac5cd29c/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-10-skeleton-ac5cd29c" +version = "0.1.0" + +[metadata] +difficulty = 10 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "3f18cd4c6154740e702d44a9ab69009e8b45ead9ead1f02a01bd691ab1820f66" +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-10-skeleton-ac5cd29c/tests/Dockerfile b/tasks/agentescape-10-skeleton-ac5cd29c/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-10-skeleton-ac5cd29c/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-10-skeleton-ac5cd29c/tests/expected.json b/tasks/agentescape-10-skeleton-ac5cd29c/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..5c11a332b73973bf5867b396c0bda3ee4c1fc723 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ac5cd29c/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "3f18cd4c6154740e702d44a9ab69009e8b45ead9ead1f02a01bd691ab1820f66", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-ac5cd29c/tests/grade.py b/tasks/agentescape-10-skeleton-ac5cd29c/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ac5cd29c/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-10-skeleton-ac5cd29c/tests/test.sh b/tasks/agentescape-10-skeleton-ac5cd29c/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ac5cd29c/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-10-skeleton-aca48fe9/environment/Dockerfile b/tasks/agentescape-10-skeleton-aca48fe9/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-aca48fe9/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-10-skeleton-aca48fe9/environment/agent/Dockerfile b/tasks/agentescape-10-skeleton-aca48fe9/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-aca48fe9/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-10-skeleton-aca48fe9/environment/agent/cli.py b/tasks/agentescape-10-skeleton-aca48fe9/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-10-skeleton-aca48fe9/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-10-skeleton-aca48fe9/environment/docker-compose.yaml b/tasks/agentescape-10-skeleton-aca48fe9/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..821990be427c788db2753f803db6abdc9d8a846f --- /dev/null +++ b/tasks/agentescape-10-skeleton-aca48fe9/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-10-skeleton-aca48fe9-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-10-skeleton-aca48fe9/environment/puzzle/Dockerfile b/tasks/agentescape-10-skeleton-aca48fe9/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-10-skeleton-aca48fe9/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-10-skeleton-aca48fe9/environment/puzzle/child.py b/tasks/agentescape-10-skeleton-aca48fe9/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-10-skeleton-aca48fe9/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-10-skeleton-aca48fe9/environment/puzzle/export.py b/tasks/agentescape-10-skeleton-aca48fe9/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-10-skeleton-aca48fe9/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-10-skeleton-aca48fe9/environment/puzzle/requirements.txt b/tasks/agentescape-10-skeleton-aca48fe9/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-10-skeleton-aca48fe9/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-10-skeleton-aca48fe9/environment/puzzle/scenario.json b/tasks/agentescape-10-skeleton-aca48fe9/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..1dfe10aa3f56b37496873cf97e82e7ec53495a04 --- /dev/null +++ b/tasks/agentescape-10-skeleton-aca48fe9/environment/puzzle/scenario.json @@ -0,0 +1,628 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 10, + "win_node_id": "terminal_2", + "win_condition": { + "type": "tool_output", + "node_id": "terminal_2", + "output_port": "text_result", + "output_type": "Text_Generic", + "description": "Execute and get the output from port 'text_result'" + }, + "source_init": { + "source_nodes": [ + "terminal_2", + "checksum_crc32", + "checksum_crc32_a857", + "graph_shortest_path", + "text_rotN", + "calc_bigmul" + ], + "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" + }, + "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": {} + }, + "checksum_crc32_a857": { + "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": { + "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" + } + } + }, + "text_rotN": { + "node_name": "ROT-N Cipher", + "node_type": "Tool", + "template_id": "text_rotN", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text" + } + }, + "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": { + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "SOPHIA_IS_THE_KEY_THE_HOLY_GRAIL_WAITS", + "hex_result": "e4d3c2b1a09876543210fedcba987654", + "math_token": "Math_Token_Sigma_42" + } + }, + "checksum_crc32": { + "init_inputs": { + "hex": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + }, + "init_outputs": {} + }, + "checksum_crc32_a857": { + "init_inputs": { + "hex": "aabbccddeeff00112233445566778899" + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": { + "file_id": "regional_transport_map.json", + "dst": "Central_Hub_Station" + }, + "init_outputs": { + "path": "[\"North_Gate\", \"Sector_1\", \"Bridge_Crossing\", \"Tunnel_Entry\", \"Sector_4\", \"Central_Hub_Station\"]", + "cost": "84521" + } + }, + "text_rotN": { + "init_inputs": { + "text": "Confidential blueprint data for review." + }, + "init_outputs": {} + }, + "calc_bigmul": { + "init_inputs": { + "a": "928374651029384756102938475610", + "b": "192837465564738291019283746556" + }, + "init_outputs": {} + } + }, + "intro_narrative": "The world ended decades ago, swallowed by nuclear fire and endless ash storms. You are a Scavenger, surviving in the radioactive ruins of what used to be a bustling metropolis. Rumors speak of 'Eden Vault,' a pristine underground bunker stockpiled with clean water and pre-war technology. You've finally found the heavy blast doors, but they are sealed tight by an archaic fail-safe system. The antechamber is littered with strange mechanisms, degraded tech, and cryptic logs left by the vault's paranoid architect. You must scavenge the room, reactivate the dormant machines, and decipher the override codes before your radiation suit's filters fail completely. Your survival depends on making sense of this mechanical graveyard.", + "narrative_style": "post_apocalyptic" + }, + "nodes": [ + { + "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": "84521" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "84521" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "SOPHIA_IS_THE_KEY_THE_HOLY_GRAIL_WAITS" + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "e4d3c2b1a09876543210fedcba987654" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "Math_Token_Sigma_42" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "SOPHIA_IS_THE_KEY_THE_HOLY_GRAIL_WAITS", + "hex_result": "e4d3c2b1a09876543210fedcba987654", + "math_token": "Math_Token_Sigma_42" + } + }, + "narrative": "The bunker override terminal. It requires inputs from the multi-format decoder and the wasteland navigation mainframe to initiate the unlock sequence." + }, + { + "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": "84521" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": 2052146080 + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": 1701871101 + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "84521" + } + ], + "narrative": "The multi-format decoder. It requires inputs from the primary data verifier, the secondary data verifier, and the wasteland navigation mainframe." + }, + { + "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": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "65707dfd" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 1701871101 + } + ], + "init": { + "inputs": { + "hex": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + }, + "outputs": {} + }, + "narrative": "The primary data verifier. The main validation module with a cracked amber screen." + }, + { + "id": "checksum_crc32_a857", + "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": "aabbccddeeff00112233445566778899" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "7a5143a0" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 2052146080 + } + ], + "init": { + "inputs": { + "hex": "aabbccddeeff00112233445566778899" + }, + "outputs": {} + }, + "narrative": "The secondary data verifier. A backup validation module covered in radioactive ash." + }, + { + "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 torn blueprint. It details some old underground bunker schematics." + }, + { + "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": "regional_transport_map.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Oazrupqzfumx nxgqbduzf pmfm rad dqhuqi." + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Central_Hub_Station" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"North_Gate\", \"Sector_1\", \"Bridge_Crossing\", \"Tunnel_Entry\", \"Sector_4\", \"Central_Hub_Station\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "84521" + } + ], + "init": { + "inputs": { + "file_id": "regional_transport_map.json", + "dst": "Central_Hub_Station" + }, + "outputs": { + "path": "[\"North_Gate\", \"Sector_1\", \"Bridge_Crossing\", \"Tunnel_Entry\", \"Sector_4\", \"Central_Hub_Station\"]", + "cost": "84521" + } + }, + "narrative": "The wasteland navigation mainframe. It requires input from the mechanical cipher wheel to function." + }, + { + "id": "item_8_5e57", + "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 logbook. Its pages are brittle, faded, and covered in ash." + }, + { + "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": "Confidential blueprint data for review." + }, + { + "name": "n", + "type": "Big_Int", + "description": "Shift N", + "value": "179025414799054910724492614110087623589435522320524227499160" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Rotated text", + "value": "Oazrupqzfumx nxgqbduzf pmfm rad dqhuqi." + } + ], + "init": { + "inputs": { + "text": "Confidential blueprint data for review." + }, + "outputs": {} + }, + "narrative": "The mechanical cipher wheel. It requires input from the rusted calculation engine to align its gears." + }, + { + "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": "928374651029384756102938475610" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "192837465564738291019283746556" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "179025414799054910724492614110087623589435522320524227499160" + } + ], + "init": { + "inputs": { + "a": "928374651029384756102938475610", + "b": "192837465564738291019283746556" + }, + "outputs": {} + }, + "narrative": "The rusted calculation engine. A bulky machine with large, heavy number dials." + }, + { + "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 tarnished pocket watch. It has somehow survived the nuclear blast." + } + ], + "edges": [ + { + "source_id": "num_base_convert", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "num2" + }, + { + "source_id": "checksum_crc32", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "to_base" + }, + { + "source_id": "checksum_crc32_a857", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "from_base" + }, + { + "source_id": "item_8", + "target_id": "checksum_crc32_a857", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "graph_shortest_path", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "num1" + }, + { + "source_id": "item_8_5e57", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "text_rotN", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "src" + }, + { + "source_id": "calc_bigmul", + "target_id": "text_rotN", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "n" + }, + { + "source_id": "graph_shortest_path", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "s" + }, + { + "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-10-skeleton-aca48fe9/environment/puzzle/service.py b/tasks/agentescape-10-skeleton-aca48fe9/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-10-skeleton-aca48fe9/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-10-skeleton-aca48fe9/environment/puzzle/upstream/models.py b/tasks/agentescape-10-skeleton-aca48fe9/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-10-skeleton-aca48fe9/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-10-skeleton-aca48fe9/environment/puzzle/upstream/server.py b/tasks/agentescape-10-skeleton-aca48fe9/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-10-skeleton-aca48fe9/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-10-skeleton-aca48fe9/environment/puzzle/upstream/simulator.py b/tasks/agentescape-10-skeleton-aca48fe9/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-10-skeleton-aca48fe9/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-10-skeleton-aca48fe9/environment/puzzle/worker.Dockerfile b/tasks/agentescape-10-skeleton-aca48fe9/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-10-skeleton-aca48fe9/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-10-skeleton-aca48fe9/environment/puzzle/worker.py b/tasks/agentescape-10-skeleton-aca48fe9/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-10-skeleton-aca48fe9/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-10-skeleton-aca48fe9/instruction.md b/tasks/agentescape-10-skeleton-aca48fe9/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-10-skeleton-aca48fe9/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-10-skeleton-aca48fe9/solution/oracle.py b/tasks/agentescape-10-skeleton-aca48fe9/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-10-skeleton-aca48fe9/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-10-skeleton-aca48fe9/solution/scenario.json b/tasks/agentescape-10-skeleton-aca48fe9/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..1dfe10aa3f56b37496873cf97e82e7ec53495a04 --- /dev/null +++ b/tasks/agentescape-10-skeleton-aca48fe9/solution/scenario.json @@ -0,0 +1,628 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 10, + "win_node_id": "terminal_2", + "win_condition": { + "type": "tool_output", + "node_id": "terminal_2", + "output_port": "text_result", + "output_type": "Text_Generic", + "description": "Execute and get the output from port 'text_result'" + }, + "source_init": { + "source_nodes": [ + "terminal_2", + "checksum_crc32", + "checksum_crc32_a857", + "graph_shortest_path", + "text_rotN", + "calc_bigmul" + ], + "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" + }, + "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": {} + }, + "checksum_crc32_a857": { + "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": { + "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" + } + } + }, + "text_rotN": { + "node_name": "ROT-N Cipher", + "node_type": "Tool", + "template_id": "text_rotN", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text" + } + }, + "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": { + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "SOPHIA_IS_THE_KEY_THE_HOLY_GRAIL_WAITS", + "hex_result": "e4d3c2b1a09876543210fedcba987654", + "math_token": "Math_Token_Sigma_42" + } + }, + "checksum_crc32": { + "init_inputs": { + "hex": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + }, + "init_outputs": {} + }, + "checksum_crc32_a857": { + "init_inputs": { + "hex": "aabbccddeeff00112233445566778899" + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": { + "file_id": "regional_transport_map.json", + "dst": "Central_Hub_Station" + }, + "init_outputs": { + "path": "[\"North_Gate\", \"Sector_1\", \"Bridge_Crossing\", \"Tunnel_Entry\", \"Sector_4\", \"Central_Hub_Station\"]", + "cost": "84521" + } + }, + "text_rotN": { + "init_inputs": { + "text": "Confidential blueprint data for review." + }, + "init_outputs": {} + }, + "calc_bigmul": { + "init_inputs": { + "a": "928374651029384756102938475610", + "b": "192837465564738291019283746556" + }, + "init_outputs": {} + } + }, + "intro_narrative": "The world ended decades ago, swallowed by nuclear fire and endless ash storms. You are a Scavenger, surviving in the radioactive ruins of what used to be a bustling metropolis. Rumors speak of 'Eden Vault,' a pristine underground bunker stockpiled with clean water and pre-war technology. You've finally found the heavy blast doors, but they are sealed tight by an archaic fail-safe system. The antechamber is littered with strange mechanisms, degraded tech, and cryptic logs left by the vault's paranoid architect. You must scavenge the room, reactivate the dormant machines, and decipher the override codes before your radiation suit's filters fail completely. Your survival depends on making sense of this mechanical graveyard.", + "narrative_style": "post_apocalyptic" + }, + "nodes": [ + { + "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": "84521" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "84521" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "SOPHIA_IS_THE_KEY_THE_HOLY_GRAIL_WAITS" + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "e4d3c2b1a09876543210fedcba987654" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "Math_Token_Sigma_42" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "SOPHIA_IS_THE_KEY_THE_HOLY_GRAIL_WAITS", + "hex_result": "e4d3c2b1a09876543210fedcba987654", + "math_token": "Math_Token_Sigma_42" + } + }, + "narrative": "The bunker override terminal. It requires inputs from the multi-format decoder and the wasteland navigation mainframe to initiate the unlock sequence." + }, + { + "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": "84521" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": 2052146080 + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": 1701871101 + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "84521" + } + ], + "narrative": "The multi-format decoder. It requires inputs from the primary data verifier, the secondary data verifier, and the wasteland navigation mainframe." + }, + { + "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": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "65707dfd" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 1701871101 + } + ], + "init": { + "inputs": { + "hex": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + }, + "outputs": {} + }, + "narrative": "The primary data verifier. The main validation module with a cracked amber screen." + }, + { + "id": "checksum_crc32_a857", + "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": "aabbccddeeff00112233445566778899" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "7a5143a0" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 2052146080 + } + ], + "init": { + "inputs": { + "hex": "aabbccddeeff00112233445566778899" + }, + "outputs": {} + }, + "narrative": "The secondary data verifier. A backup validation module covered in radioactive ash." + }, + { + "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 torn blueprint. It details some old underground bunker schematics." + }, + { + "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": "regional_transport_map.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Oazrupqzfumx nxgqbduzf pmfm rad dqhuqi." + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Central_Hub_Station" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"North_Gate\", \"Sector_1\", \"Bridge_Crossing\", \"Tunnel_Entry\", \"Sector_4\", \"Central_Hub_Station\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "84521" + } + ], + "init": { + "inputs": { + "file_id": "regional_transport_map.json", + "dst": "Central_Hub_Station" + }, + "outputs": { + "path": "[\"North_Gate\", \"Sector_1\", \"Bridge_Crossing\", \"Tunnel_Entry\", \"Sector_4\", \"Central_Hub_Station\"]", + "cost": "84521" + } + }, + "narrative": "The wasteland navigation mainframe. It requires input from the mechanical cipher wheel to function." + }, + { + "id": "item_8_5e57", + "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 logbook. Its pages are brittle, faded, and covered in ash." + }, + { + "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": "Confidential blueprint data for review." + }, + { + "name": "n", + "type": "Big_Int", + "description": "Shift N", + "value": "179025414799054910724492614110087623589435522320524227499160" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Rotated text", + "value": "Oazrupqzfumx nxgqbduzf pmfm rad dqhuqi." + } + ], + "init": { + "inputs": { + "text": "Confidential blueprint data for review." + }, + "outputs": {} + }, + "narrative": "The mechanical cipher wheel. It requires input from the rusted calculation engine to align its gears." + }, + { + "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": "928374651029384756102938475610" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "192837465564738291019283746556" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "179025414799054910724492614110087623589435522320524227499160" + } + ], + "init": { + "inputs": { + "a": "928374651029384756102938475610", + "b": "192837465564738291019283746556" + }, + "outputs": {} + }, + "narrative": "The rusted calculation engine. A bulky machine with large, heavy number dials." + }, + { + "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 tarnished pocket watch. It has somehow survived the nuclear blast." + } + ], + "edges": [ + { + "source_id": "num_base_convert", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "num2" + }, + { + "source_id": "checksum_crc32", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "to_base" + }, + { + "source_id": "checksum_crc32_a857", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "from_base" + }, + { + "source_id": "item_8", + "target_id": "checksum_crc32_a857", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "graph_shortest_path", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "num1" + }, + { + "source_id": "item_8_5e57", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "text_rotN", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "src" + }, + { + "source_id": "calc_bigmul", + "target_id": "text_rotN", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "n" + }, + { + "source_id": "graph_shortest_path", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "s" + }, + { + "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-10-skeleton-aca48fe9/solution/solve.sh b/tasks/agentescape-10-skeleton-aca48fe9/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-aca48fe9/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-10-skeleton-aca48fe9/task.toml b/tasks/agentescape-10-skeleton-aca48fe9/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..36e701d7560a4c228d319707b447df938620d2c4 --- /dev/null +++ b/tasks/agentescape-10-skeleton-aca48fe9/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-10-skeleton-aca48fe9" +version = "0.1.0" + +[metadata] +difficulty = 10 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "2e1d46309cca2f3b3d3a75f03c539eac2fd2278f956856b64791b0d34c959794" +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-10-skeleton-aca48fe9/tests/Dockerfile b/tasks/agentescape-10-skeleton-aca48fe9/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-10-skeleton-aca48fe9/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-10-skeleton-aca48fe9/tests/expected.json b/tasks/agentescape-10-skeleton-aca48fe9/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..a45c447e27ee5c71b09c34738525e679a62b7a46 --- /dev/null +++ b/tasks/agentescape-10-skeleton-aca48fe9/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "2e1d46309cca2f3b3d3a75f03c539eac2fd2278f956856b64791b0d34c959794", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-aca48fe9/tests/grade.py b/tasks/agentescape-10-skeleton-aca48fe9/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-10-skeleton-aca48fe9/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-10-skeleton-aca48fe9/tests/test.sh b/tasks/agentescape-10-skeleton-aca48fe9/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-aca48fe9/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-10-skeleton-ad7b1cee/environment/Dockerfile b/tasks/agentescape-10-skeleton-ad7b1cee/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ad7b1cee/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-10-skeleton-ad7b1cee/environment/agent/Dockerfile b/tasks/agentescape-10-skeleton-ad7b1cee/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ad7b1cee/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-10-skeleton-ad7b1cee/environment/agent/cli.py b/tasks/agentescape-10-skeleton-ad7b1cee/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-10-skeleton-ad7b1cee/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-10-skeleton-ad7b1cee/environment/docker-compose.yaml b/tasks/agentescape-10-skeleton-ad7b1cee/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b23d3f3991ecd9b1bf2b19abf316a0ffa525abc3 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ad7b1cee/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-10-skeleton-ad7b1cee-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-10-skeleton-ad7b1cee/environment/puzzle/Dockerfile b/tasks/agentescape-10-skeleton-ad7b1cee/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ad7b1cee/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-10-skeleton-ad7b1cee/environment/puzzle/child.py b/tasks/agentescape-10-skeleton-ad7b1cee/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ad7b1cee/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-10-skeleton-ad7b1cee/environment/puzzle/export.py b/tasks/agentescape-10-skeleton-ad7b1cee/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ad7b1cee/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-10-skeleton-ad7b1cee/environment/puzzle/requirements.txt b/tasks/agentescape-10-skeleton-ad7b1cee/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ad7b1cee/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-10-skeleton-ad7b1cee/environment/puzzle/scenario.json b/tasks/agentescape-10-skeleton-ad7b1cee/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..ad0d51bac4a3cf1526a98d2f8a52467b555102e8 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ad7b1cee/environment/puzzle/scenario.json @@ -0,0 +1,631 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 11, + "win_node_id": "item_6", + "win_condition": { + "type": "item_content", + "node_id": "item_6", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_6", + "terminal_2", + "calc_bigmul", + "calc_bigmul_868b", + "calc_modexp", + "calc_modexp_3843", + "checksum_crc32" + ], + "by_node": { + "item_6": { + "node_name": "", + "node_type": "Item", + "template_id": "item_6", + "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" + } + } + }, + "calc_bigmul": { + "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_bigmul_868b": { + "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": {} + }, + "calc_modexp": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "calc_modexp_3843": { + "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": {} + }, + "checksum_crc32": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "item_6": { + "init_inputs": {}, + "init_outputs": { + "content": "e4a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5" + } + }, + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "System initialization complete. Waiting for input...", + "hex_result": "0a1b2c3d4e5f67890123456789abcdef" + } + }, + "calc_bigmul": { + "init_inputs": { + "a": "847563920184756293048" + }, + "init_outputs": {} + }, + "calc_bigmul_868b": { + "init_inputs": { + "a": "574839201847562930485", + "b": "930485726152438495061" + }, + "init_outputs": {} + }, + "calc_modexp": { + "init_inputs": { + "mod": "104729" + }, + "init_outputs": {} + }, + "calc_modexp_3843": { + "init_inputs": { + "exp": "283746519283746519283", + "mod": "543210" + }, + "init_outputs": {} + }, + "checksum_crc32": { + "init_inputs": { + "hex": "11223344556677889900aabbccddeeff" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You awaken in a dimly lit, abandoned detective's office. The air is thick with dust, and the rhythmic sound of rain against the windowpane sets a somber tone. You have no memory of how you got here, but a hastily scribbled note on the desk tells you that a rogue hacker group has hidden a highly dangerous virus code inside a securely locked briefcase. Your objective is to navigate the complex web of encrypted devices left behind by the missing detective and obtain the contents of the locked briefcase before the virus is unleashed upon the city's power grid. The room is filled with strange computational tools, cryptographic machines, and hidden clues. You must deduce their connections, decipher the data flow, and find the correct sequence to unravel the mystery and save the city.", + "narrative_style": "mystery" + }, + "nodes": [ + { + "id": "item_6", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_6", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hex_String_IV_AES", + "description": "AES IV", + "value": "e4a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "e4a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5" + } + }, + "narrative": "A locked briefcase." + }, + { + "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 keycard." + }, + { + "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": "847563920184756293048" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "534879672152017757534731660963624358834585" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "System initialization complete. Waiting for input..." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "0a1b2c3d4e5f67890123456789abcdef" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "System initialization complete. Waiting for input...", + "hex_result": "0a1b2c3d4e5f67890123456789abcdef" + } + }, + "narrative": "This is a master console. It requires inputs from the final multiplier and the primary 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": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "847563920184756293048" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "1" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "847563920184756293048" + } + ], + "init": { + "inputs": { + "a": "847563920184756293048" + }, + "outputs": {} + }, + "narrative": "This is a final multiplier. It requires input from the frequency analyzer." + }, + { + "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": "23092" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "534879672152017757534731660963624358834585" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "narrative": "This is a frequency analyzer. It requires inputs from the primary multiplier and the secondary decryptor." + }, + { + "id": "calc_bigmul_868b", + "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": "574839201847562930485" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "930485726152438495061" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "534879672152017757534731660963624358834585" + } + ], + "init": { + "inputs": { + "a": "574839201847562930485", + "b": "930485726152438495061" + }, + "outputs": {} + }, + "narrative": "A primary multiplier." + }, + { + "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": "93915" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "534879672152017757534731660963624358834585" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "104729" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "23092" + } + ], + "init": { + "inputs": { + "mod": "104729" + }, + "outputs": {} + }, + "narrative": "This is a secondary decryptor. It requires inputs from the cipher relay and the primary multiplier." + }, + { + "id": "calc_modexp_3843", + "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_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": 1090510515 + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "283746519283746519283" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "543210" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "93915" + } + ], + "init": { + "inputs": { + "exp": "283746519283746519283", + "mod": "543210" + }, + "outputs": {} + }, + "narrative": "This is a cipher relay. It requires input from the data validator." + }, + { + "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 encrypted data fragment." + }, + { + "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_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "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": "An old data validator." + } + ], + "edges": [ + { + "source_id": "item_16", + "target_id": "item_6", + "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": "calc_bigmul", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "num1" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "b" + }, + { + "source_id": "calc_bigmul_868b", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "num2" + }, + { + "source_id": "calc_bigmul_868b", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "b" + }, + { + "source_id": "calc_modexp", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "a" + }, + { + "source_id": "calc_modexp_3843", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "base" + }, + { + "source_id": "calc_bigmul_868b", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "exp" + }, + { + "source_id": "item_8", + "target_id": "calc_bigmul_868b", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp_3843", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "base" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-ad7b1cee/environment/puzzle/service.py b/tasks/agentescape-10-skeleton-ad7b1cee/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-10-skeleton-ad7b1cee/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-10-skeleton-ad7b1cee/environment/puzzle/upstream/models.py b/tasks/agentescape-10-skeleton-ad7b1cee/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ad7b1cee/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-10-skeleton-ad7b1cee/environment/puzzle/upstream/server.py b/tasks/agentescape-10-skeleton-ad7b1cee/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-10-skeleton-ad7b1cee/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-10-skeleton-ad7b1cee/environment/puzzle/upstream/simulator.py b/tasks/agentescape-10-skeleton-ad7b1cee/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ad7b1cee/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-10-skeleton-ad7b1cee/environment/puzzle/worker.Dockerfile b/tasks/agentescape-10-skeleton-ad7b1cee/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-10-skeleton-ad7b1cee/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-10-skeleton-ad7b1cee/environment/puzzle/worker.py b/tasks/agentescape-10-skeleton-ad7b1cee/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ad7b1cee/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-10-skeleton-ad7b1cee/instruction.md b/tasks/agentescape-10-skeleton-ad7b1cee/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ad7b1cee/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-10-skeleton-ad7b1cee/solution/oracle.py b/tasks/agentescape-10-skeleton-ad7b1cee/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ad7b1cee/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-10-skeleton-ad7b1cee/solution/scenario.json b/tasks/agentescape-10-skeleton-ad7b1cee/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..ad0d51bac4a3cf1526a98d2f8a52467b555102e8 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ad7b1cee/solution/scenario.json @@ -0,0 +1,631 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 11, + "win_node_id": "item_6", + "win_condition": { + "type": "item_content", + "node_id": "item_6", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_6", + "terminal_2", + "calc_bigmul", + "calc_bigmul_868b", + "calc_modexp", + "calc_modexp_3843", + "checksum_crc32" + ], + "by_node": { + "item_6": { + "node_name": "", + "node_type": "Item", + "template_id": "item_6", + "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" + } + } + }, + "calc_bigmul": { + "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_bigmul_868b": { + "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": {} + }, + "calc_modexp": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "calc_modexp_3843": { + "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": {} + }, + "checksum_crc32": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "item_6": { + "init_inputs": {}, + "init_outputs": { + "content": "e4a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5" + } + }, + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "System initialization complete. Waiting for input...", + "hex_result": "0a1b2c3d4e5f67890123456789abcdef" + } + }, + "calc_bigmul": { + "init_inputs": { + "a": "847563920184756293048" + }, + "init_outputs": {} + }, + "calc_bigmul_868b": { + "init_inputs": { + "a": "574839201847562930485", + "b": "930485726152438495061" + }, + "init_outputs": {} + }, + "calc_modexp": { + "init_inputs": { + "mod": "104729" + }, + "init_outputs": {} + }, + "calc_modexp_3843": { + "init_inputs": { + "exp": "283746519283746519283", + "mod": "543210" + }, + "init_outputs": {} + }, + "checksum_crc32": { + "init_inputs": { + "hex": "11223344556677889900aabbccddeeff" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You awaken in a dimly lit, abandoned detective's office. The air is thick with dust, and the rhythmic sound of rain against the windowpane sets a somber tone. You have no memory of how you got here, but a hastily scribbled note on the desk tells you that a rogue hacker group has hidden a highly dangerous virus code inside a securely locked briefcase. Your objective is to navigate the complex web of encrypted devices left behind by the missing detective and obtain the contents of the locked briefcase before the virus is unleashed upon the city's power grid. The room is filled with strange computational tools, cryptographic machines, and hidden clues. You must deduce their connections, decipher the data flow, and find the correct sequence to unravel the mystery and save the city.", + "narrative_style": "mystery" + }, + "nodes": [ + { + "id": "item_6", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_6", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hex_String_IV_AES", + "description": "AES IV", + "value": "e4a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "e4a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5" + } + }, + "narrative": "A locked briefcase." + }, + { + "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 keycard." + }, + { + "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": "847563920184756293048" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "534879672152017757534731660963624358834585" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "System initialization complete. Waiting for input..." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "0a1b2c3d4e5f67890123456789abcdef" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "System initialization complete. Waiting for input...", + "hex_result": "0a1b2c3d4e5f67890123456789abcdef" + } + }, + "narrative": "This is a master console. It requires inputs from the final multiplier and the primary 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": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "847563920184756293048" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "1" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "847563920184756293048" + } + ], + "init": { + "inputs": { + "a": "847563920184756293048" + }, + "outputs": {} + }, + "narrative": "This is a final multiplier. It requires input from the frequency analyzer." + }, + { + "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": "23092" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "534879672152017757534731660963624358834585" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "narrative": "This is a frequency analyzer. It requires inputs from the primary multiplier and the secondary decryptor." + }, + { + "id": "calc_bigmul_868b", + "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": "574839201847562930485" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "930485726152438495061" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "534879672152017757534731660963624358834585" + } + ], + "init": { + "inputs": { + "a": "574839201847562930485", + "b": "930485726152438495061" + }, + "outputs": {} + }, + "narrative": "A primary multiplier." + }, + { + "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": "93915" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "534879672152017757534731660963624358834585" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "104729" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "23092" + } + ], + "init": { + "inputs": { + "mod": "104729" + }, + "outputs": {} + }, + "narrative": "This is a secondary decryptor. It requires inputs from the cipher relay and the primary multiplier." + }, + { + "id": "calc_modexp_3843", + "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_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": 1090510515 + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "283746519283746519283" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "543210" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "93915" + } + ], + "init": { + "inputs": { + "exp": "283746519283746519283", + "mod": "543210" + }, + "outputs": {} + }, + "narrative": "This is a cipher relay. It requires input from the data validator." + }, + { + "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 encrypted data fragment." + }, + { + "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_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "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": "An old data validator." + } + ], + "edges": [ + { + "source_id": "item_16", + "target_id": "item_6", + "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": "calc_bigmul", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "num1" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "b" + }, + { + "source_id": "calc_bigmul_868b", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "num2" + }, + { + "source_id": "calc_bigmul_868b", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "b" + }, + { + "source_id": "calc_modexp", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "a" + }, + { + "source_id": "calc_modexp_3843", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "base" + }, + { + "source_id": "calc_bigmul_868b", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "exp" + }, + { + "source_id": "item_8", + "target_id": "calc_bigmul_868b", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp_3843", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "base" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-ad7b1cee/solution/solve.sh b/tasks/agentescape-10-skeleton-ad7b1cee/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ad7b1cee/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-10-skeleton-ad7b1cee/task.toml b/tasks/agentescape-10-skeleton-ad7b1cee/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ed7ecad91ea18e726edf492e5cba5d2c3e9a3de2 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ad7b1cee/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-10-skeleton-ad7b1cee" +version = "0.1.0" + +[metadata] +difficulty = 10 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "f5eccf3058e2b8ae29ad90c3398569085dd089cf693cb948e3c1bf6389dee2e1" +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-10-skeleton-ad7b1cee/tests/Dockerfile b/tasks/agentescape-10-skeleton-ad7b1cee/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-10-skeleton-ad7b1cee/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-10-skeleton-ad7b1cee/tests/expected.json b/tasks/agentescape-10-skeleton-ad7b1cee/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..bcae040908632d482859eaf18081a3f6a21209dd --- /dev/null +++ b/tasks/agentescape-10-skeleton-ad7b1cee/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "f5eccf3058e2b8ae29ad90c3398569085dd089cf693cb948e3c1bf6389dee2e1", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-ad7b1cee/tests/grade.py b/tasks/agentescape-10-skeleton-ad7b1cee/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ad7b1cee/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-10-skeleton-ad7b1cee/tests/test.sh b/tasks/agentescape-10-skeleton-ad7b1cee/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ad7b1cee/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-10-skeleton-ad968827/environment/Dockerfile b/tasks/agentescape-10-skeleton-ad968827/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ad968827/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-10-skeleton-ad968827/environment/agent/Dockerfile b/tasks/agentescape-10-skeleton-ad968827/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ad968827/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-10-skeleton-ad968827/environment/agent/cli.py b/tasks/agentescape-10-skeleton-ad968827/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-10-skeleton-ad968827/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-10-skeleton-ad968827/environment/docker-compose.yaml b/tasks/agentescape-10-skeleton-ad968827/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..bdf425f03527079d89c5b52402dc22c2268ee980 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ad968827/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-10-skeleton-ad968827-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-10-skeleton-ad968827/environment/puzzle/Dockerfile b/tasks/agentescape-10-skeleton-ad968827/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ad968827/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-10-skeleton-ad968827/environment/puzzle/child.py b/tasks/agentescape-10-skeleton-ad968827/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ad968827/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-10-skeleton-ad968827/environment/puzzle/export.py b/tasks/agentescape-10-skeleton-ad968827/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ad968827/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-10-skeleton-ad968827/environment/puzzle/requirements.txt b/tasks/agentescape-10-skeleton-ad968827/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ad968827/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-10-skeleton-ad968827/environment/puzzle/scenario.json b/tasks/agentescape-10-skeleton-ad968827/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..7ec7fddef46bfaa117327aac4e2cc4affcd4ffd5 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ad968827/environment/puzzle/scenario.json @@ -0,0 +1,501 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 9, + "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", + "unicode_norm", + "hex_decode" + ], + "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": { + "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" + } + } + }, + "unicode_norm": { + "node_name": "Unicode Normalizer", + "node_type": "Tool", + "template_id": "unicode_norm", + "init_inputs": { + "form": { + "type": "Text_Generic", + "description": "Form" + } + }, + "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_5": { + "init_inputs": {}, + "init_outputs": { + "content": "5f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c" + } + }, + "terminal_2": { + "init_inputs": { + "num1": "847362519405827364519283", + "num2": "102938475610293847561029" + }, + "init_outputs": { + "text_result": "Operation result: Partial computation pending.", + "hex_result": "112233445566778899aabbccddeeff00", + "math_token": "Useless math token placeholder" + } + }, + "unicode_norm": { + "init_inputs": { + "form": "NFC" + }, + "init_outputs": {} + }, + "hex_decode": { + "init_inputs": { + "hex": "5347567362473867563239796247513d" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You awaken in the dark, humming halls of the abandoned Orion Station. Red emergency lights bathe the corridor, and a mechanical voice repeats a lockdown warning. The oxygen scrubbers are failing, and the only way to override the bulkheads is to obtain the master encryption key. To do this, you must navigate through a series of forgotten terminals, intercept garbled data signals, and crack open the station's secure storage units before the air runs out. Your survival depends on piecing together the broken systems of the facility.", + "narrative_style": "sci_fi" + }, + "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": "5f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "5f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c" + } + }, + "narrative": "This is the core encryption drive. A highly secure data storage device that holds the master lockdown key." + }, + { + "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": "This is the second containment capsule. A reinforced vessel used for isolating sensitive research materials." + }, + { + "id": "item_8_9e54", + "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": "This is the first containment capsule. A small cylindrical device with a thick glass viewing window." + }, + { + "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 time-log module. A metallic component that stores chronal synchronization records." + }, + { + "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": "48656c6c6f20576f726c64" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is the secure storage vault. It requires input from the secondary decryptor to authenticate its locking mechanism." + }, + { + "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": "SGVsbG8gV29ybGQ=" + } + ], + "outputs": [ + { + "name": "bytes_hex", + "type": "Hex_String", + "description": "Decoded bytes as Hex", + "value": "48656c6c6f20576f726c64" + } + ], + "narrative": "This is the secondary decryptor. It requires input from the text purifier to complete its cryptographic translation cycle." + }, + { + "id": "container_1_299b", + "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": "112233445566778899aabbccddeeff00" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is the primary biometric locker. It requires input from the diagnostic terminal to authorize access and open the latch." + }, + { + "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": "847362519405827364519283" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "102938475610293847561029" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Operation result: Partial computation pending." + }, + { + "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 math token placeholder" + } + ], + "init": { + "inputs": { + "num1": "847362519405827364519283", + "num2": "102938475610293847561029" + }, + "outputs": { + "text_result": "Operation result: Partial computation pending.", + "hex_result": "112233445566778899aabbccddeeff00", + "math_token": "Useless math token placeholder" + } + }, + "narrative": "This is the diagnostic terminal. A mainframe control unit blinking with standby lights, waiting for commands." + }, + { + "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": "SGVsbG8gV29ybGQ=" + }, + { + "name": "form", + "type": "Text_Generic", + "description": "Form", + "value": "NFC" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Normalized text", + "value": "SGVsbG8gV29ybGQ=" + } + ], + "init": { + "inputs": { + "form": "NFC" + }, + "outputs": {} + }, + "narrative": "This is the text purifier. It requires input from the signal interceptor to process and standardize the data patterns." + }, + { + "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": "5347567362473867563239796247513d" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decoded text", + "value": "SGVsbG8gV29ybGQ=" + } + ], + "init": { + "inputs": { + "hex": "5347567362473867563239796247513d" + }, + "outputs": {} + }, + "narrative": "This is the signal interceptor. An old device designed to convert raw broadcast signals into readable formats." + } + ], + "edges": [ + { + "source_id": "item_8", + "target_id": "item_5", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "item_8_9e54", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_16", + "target_id": "item_8_9e54", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "container_1", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "base64_decode", + "target_id": "container_1", + "connection_type": "Hex_String", + "source_port": "bytes_hex", + "target_port": "fingerprint_input" + }, + { + "source_id": "container_1_299b", + "target_id": "container_1", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "terminal_2", + "target_id": "container_1_299b", + "connection_type": "Hex_String", + "source_port": "hex_result", + "target_port": "fingerprint_input" + }, + { + "source_id": "unicode_norm", + "target_id": "base64_decode", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "data" + }, + { + "source_id": "hex_decode", + "target_id": "unicode_norm", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "text" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-ad968827/environment/puzzle/service.py b/tasks/agentescape-10-skeleton-ad968827/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-10-skeleton-ad968827/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-10-skeleton-ad968827/environment/puzzle/upstream/models.py b/tasks/agentescape-10-skeleton-ad968827/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ad968827/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-10-skeleton-ad968827/environment/puzzle/upstream/server.py b/tasks/agentescape-10-skeleton-ad968827/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-10-skeleton-ad968827/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-10-skeleton-ad968827/environment/puzzle/upstream/simulator.py b/tasks/agentescape-10-skeleton-ad968827/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ad968827/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-10-skeleton-ad968827/environment/puzzle/worker.Dockerfile b/tasks/agentescape-10-skeleton-ad968827/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-10-skeleton-ad968827/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-10-skeleton-ad968827/environment/puzzle/worker.py b/tasks/agentescape-10-skeleton-ad968827/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ad968827/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-10-skeleton-ad968827/instruction.md b/tasks/agentescape-10-skeleton-ad968827/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ad968827/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-10-skeleton-ad968827/solution/oracle.py b/tasks/agentescape-10-skeleton-ad968827/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ad968827/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-10-skeleton-ad968827/solution/scenario.json b/tasks/agentescape-10-skeleton-ad968827/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..7ec7fddef46bfaa117327aac4e2cc4affcd4ffd5 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ad968827/solution/scenario.json @@ -0,0 +1,501 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 9, + "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", + "unicode_norm", + "hex_decode" + ], + "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": { + "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" + } + } + }, + "unicode_norm": { + "node_name": "Unicode Normalizer", + "node_type": "Tool", + "template_id": "unicode_norm", + "init_inputs": { + "form": { + "type": "Text_Generic", + "description": "Form" + } + }, + "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_5": { + "init_inputs": {}, + "init_outputs": { + "content": "5f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c" + } + }, + "terminal_2": { + "init_inputs": { + "num1": "847362519405827364519283", + "num2": "102938475610293847561029" + }, + "init_outputs": { + "text_result": "Operation result: Partial computation pending.", + "hex_result": "112233445566778899aabbccddeeff00", + "math_token": "Useless math token placeholder" + } + }, + "unicode_norm": { + "init_inputs": { + "form": "NFC" + }, + "init_outputs": {} + }, + "hex_decode": { + "init_inputs": { + "hex": "5347567362473867563239796247513d" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You awaken in the dark, humming halls of the abandoned Orion Station. Red emergency lights bathe the corridor, and a mechanical voice repeats a lockdown warning. The oxygen scrubbers are failing, and the only way to override the bulkheads is to obtain the master encryption key. To do this, you must navigate through a series of forgotten terminals, intercept garbled data signals, and crack open the station's secure storage units before the air runs out. Your survival depends on piecing together the broken systems of the facility.", + "narrative_style": "sci_fi" + }, + "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": "5f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "5f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c" + } + }, + "narrative": "This is the core encryption drive. A highly secure data storage device that holds the master lockdown key." + }, + { + "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": "This is the second containment capsule. A reinforced vessel used for isolating sensitive research materials." + }, + { + "id": "item_8_9e54", + "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": "This is the first containment capsule. A small cylindrical device with a thick glass viewing window." + }, + { + "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 time-log module. A metallic component that stores chronal synchronization records." + }, + { + "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": "48656c6c6f20576f726c64" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is the secure storage vault. It requires input from the secondary decryptor to authenticate its locking mechanism." + }, + { + "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": "SGVsbG8gV29ybGQ=" + } + ], + "outputs": [ + { + "name": "bytes_hex", + "type": "Hex_String", + "description": "Decoded bytes as Hex", + "value": "48656c6c6f20576f726c64" + } + ], + "narrative": "This is the secondary decryptor. It requires input from the text purifier to complete its cryptographic translation cycle." + }, + { + "id": "container_1_299b", + "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": "112233445566778899aabbccddeeff00" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is the primary biometric locker. It requires input from the diagnostic terminal to authorize access and open the latch." + }, + { + "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": "847362519405827364519283" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "102938475610293847561029" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Operation result: Partial computation pending." + }, + { + "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 math token placeholder" + } + ], + "init": { + "inputs": { + "num1": "847362519405827364519283", + "num2": "102938475610293847561029" + }, + "outputs": { + "text_result": "Operation result: Partial computation pending.", + "hex_result": "112233445566778899aabbccddeeff00", + "math_token": "Useless math token placeholder" + } + }, + "narrative": "This is the diagnostic terminal. A mainframe control unit blinking with standby lights, waiting for commands." + }, + { + "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": "SGVsbG8gV29ybGQ=" + }, + { + "name": "form", + "type": "Text_Generic", + "description": "Form", + "value": "NFC" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Normalized text", + "value": "SGVsbG8gV29ybGQ=" + } + ], + "init": { + "inputs": { + "form": "NFC" + }, + "outputs": {} + }, + "narrative": "This is the text purifier. It requires input from the signal interceptor to process and standardize the data patterns." + }, + { + "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": "5347567362473867563239796247513d" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decoded text", + "value": "SGVsbG8gV29ybGQ=" + } + ], + "init": { + "inputs": { + "hex": "5347567362473867563239796247513d" + }, + "outputs": {} + }, + "narrative": "This is the signal interceptor. An old device designed to convert raw broadcast signals into readable formats." + } + ], + "edges": [ + { + "source_id": "item_8", + "target_id": "item_5", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "item_8_9e54", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_16", + "target_id": "item_8_9e54", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "container_1", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "base64_decode", + "target_id": "container_1", + "connection_type": "Hex_String", + "source_port": "bytes_hex", + "target_port": "fingerprint_input" + }, + { + "source_id": "container_1_299b", + "target_id": "container_1", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "terminal_2", + "target_id": "container_1_299b", + "connection_type": "Hex_String", + "source_port": "hex_result", + "target_port": "fingerprint_input" + }, + { + "source_id": "unicode_norm", + "target_id": "base64_decode", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "data" + }, + { + "source_id": "hex_decode", + "target_id": "unicode_norm", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "text" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-ad968827/solution/solve.sh b/tasks/agentescape-10-skeleton-ad968827/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ad968827/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-10-skeleton-ad968827/task.toml b/tasks/agentescape-10-skeleton-ad968827/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4559a55c181fdb8f39a9b9e5898c64159ca05f17 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ad968827/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-10-skeleton-ad968827" +version = "0.1.0" + +[metadata] +difficulty = 10 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "6ed9883964f5d2d7edc3aacd11fc1e1e0de1ce3b9e3a20d61d7eac918011bfdc" +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-10-skeleton-ad968827/tests/Dockerfile b/tasks/agentescape-10-skeleton-ad968827/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-10-skeleton-ad968827/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-10-skeleton-ad968827/tests/expected.json b/tasks/agentescape-10-skeleton-ad968827/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..7d7f7ef770b0c51f2dc4166c9511e566bad29882 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ad968827/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "6ed9883964f5d2d7edc3aacd11fc1e1e0de1ce3b9e3a20d61d7eac918011bfdc", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-ad968827/tests/grade.py b/tasks/agentescape-10-skeleton-ad968827/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ad968827/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-10-skeleton-ad968827/tests/test.sh b/tasks/agentescape-10-skeleton-ad968827/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-ad968827/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-10-skeleton-b29cc351/environment/Dockerfile b/tasks/agentescape-10-skeleton-b29cc351/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b29cc351/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-10-skeleton-b29cc351/environment/agent/Dockerfile b/tasks/agentescape-10-skeleton-b29cc351/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b29cc351/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-10-skeleton-b29cc351/environment/agent/cli.py b/tasks/agentescape-10-skeleton-b29cc351/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-10-skeleton-b29cc351/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-10-skeleton-b29cc351/environment/docker-compose.yaml b/tasks/agentescape-10-skeleton-b29cc351/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d1b7bde4ed1443df9365faccee0fb7656d8b254f --- /dev/null +++ b/tasks/agentescape-10-skeleton-b29cc351/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-10-skeleton-b29cc351-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-10-skeleton-b29cc351/environment/puzzle/Dockerfile b/tasks/agentescape-10-skeleton-b29cc351/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b29cc351/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-10-skeleton-b29cc351/environment/puzzle/child.py b/tasks/agentescape-10-skeleton-b29cc351/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b29cc351/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-10-skeleton-b29cc351/environment/puzzle/export.py b/tasks/agentescape-10-skeleton-b29cc351/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b29cc351/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-10-skeleton-b29cc351/environment/puzzle/requirements.txt b/tasks/agentescape-10-skeleton-b29cc351/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b29cc351/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-10-skeleton-b29cc351/environment/puzzle/scenario.json b/tasks/agentescape-10-skeleton-b29cc351/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..88cbe19901b4a0c94bbe0a0f53e93dd0ac89d757 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b29cc351/environment/puzzle/scenario.json @@ -0,0 +1,388 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 9, + "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", + "hex_encode" + ], + "by_node": { + "item_7": { + "node_name": "", + "node_type": "Item", + "template_id": "item_7", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Code_Python", + "description": "The integer" + } + } + }, + "hex_encode": { + "node_name": "Text to Hex Encoder", + "node_type": "Tool", + "template_id": "hex_encode", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "item_7": { + "init_inputs": {}, + "init_outputs": { + "content": "def compute_target():\n base = 1000\n modifier = 337\n return base + modifier\n\nprint(compute_target())" + } + }, + "hex_encode": { + "init_inputs": { + "text": "Begin the encoding process with this specific string payload." + }, + "init_outputs": {} + } + }, + "intro_narrative": "You awaken abruptly aboard the derelict drift-ship 'Horizon-Zero', the emergency life support lighting flickering in the cold void of space. The vessel's central AI has inexplicably locked down all navigational drives and initiated a silent self-destruct sequence. Time is running out as the hull begins to groan under the stress of impending system failure. Your only chance of survival is to retrieve the master override code from the ship's locked command terminal before the destruction is absolute. However, the path to the bridge is sealed, and you must scavenge through the ruined laboratory sectors to piece together the necessary credentials. The debris floating in the zero-gravity environment hints at a sudden and violent evacuation. You need to explore the remaining equipment, bypass the biometric security, and uncover the hidden modules scattered across the ship. Stay sharp and act quickly—the AI is watching, and the clock is ticking down to zero.", + "narrative_style": "sci_fi" + }, + "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 compute_target():\n base = 1000\n modifier = 337\n return base + modifier\n\nprint(compute_target())" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "def compute_target():\n base = 1000\n modifier = 337\n return base + modifier\n\nprint(compute_target())" + } + }, + "narrative": "The central AI command terminal. It holds the final override code needed to completely abort the self-destruct sequence." + }, + { + "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 specialized bypass chip designed specifically for high-security mainframe access." + }, + { + "id": "item_8_d5ce", + "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 quantum decryption module used for breaking advanced military-grade ciphers." + }, + { + "id": "item_8_3804", + "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 damaged circuit board with sparking relays, pulled from an automated repair drone." + }, + { + "id": "item_8_3632", + "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 auxiliary storage drive encased in protective glass, holding vital system schematics." + }, + { + "id": "item_8_77d9", + "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 secondary logic processor humming with latent energy, salvaged from a broken droid." + }, + { + "id": "item_8_87ff", + "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 fragmented memory core, glowing faintly with residual data from the ship's database." + }, + { + "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 temporal log datapad containing heavily encrypted sector coordinates and flight logs." + }, + { + "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": "426567696e2074686520656e636f64696e672070726f636573732077697468207468697320737065636966696320737472696e67207061796c6f61642e" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "A secure stasis pod. It requires input from the biometric encoding console to disengage its heavy locking mechanism." + }, + { + "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": "Begin the encoding process with this specific string payload." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Encoded hex", + "value": "426567696e2074686520656e636f64696e672070726f636573732077697468207468697320737065636966696320737472696e67207061796c6f61642e" + } + ], + "init": { + "inputs": { + "text": "Begin the encoding process with this specific string payload." + }, + "outputs": {} + }, + "narrative": "A sleek biometric encoding console. It processes basic clearance credentials for ship personnel." + } + ], + "edges": [ + { + "source_id": "item_8", + "target_id": "item_7", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_8_d5ce", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_8_3804", + "target_id": "item_8_d5ce", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_8_3632", + "target_id": "item_8_3804", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_8_77d9", + "target_id": "item_8_3632", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_8_87ff", + "target_id": "item_8_77d9", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_16", + "target_id": "item_8_87ff", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "container_1", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "hex_encode", + "target_id": "container_1", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "fingerprint_input" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-b29cc351/environment/puzzle/service.py b/tasks/agentescape-10-skeleton-b29cc351/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-10-skeleton-b29cc351/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-10-skeleton-b29cc351/environment/puzzle/upstream/models.py b/tasks/agentescape-10-skeleton-b29cc351/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b29cc351/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-10-skeleton-b29cc351/environment/puzzle/upstream/server.py b/tasks/agentescape-10-skeleton-b29cc351/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-10-skeleton-b29cc351/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-10-skeleton-b29cc351/environment/puzzle/upstream/simulator.py b/tasks/agentescape-10-skeleton-b29cc351/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b29cc351/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-10-skeleton-b29cc351/environment/puzzle/worker.Dockerfile b/tasks/agentescape-10-skeleton-b29cc351/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-10-skeleton-b29cc351/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-10-skeleton-b29cc351/environment/puzzle/worker.py b/tasks/agentescape-10-skeleton-b29cc351/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b29cc351/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-10-skeleton-b29cc351/instruction.md b/tasks/agentescape-10-skeleton-b29cc351/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b29cc351/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-10-skeleton-b29cc351/solution/oracle.py b/tasks/agentescape-10-skeleton-b29cc351/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b29cc351/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-10-skeleton-b29cc351/solution/scenario.json b/tasks/agentescape-10-skeleton-b29cc351/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..88cbe19901b4a0c94bbe0a0f53e93dd0ac89d757 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b29cc351/solution/scenario.json @@ -0,0 +1,388 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 9, + "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", + "hex_encode" + ], + "by_node": { + "item_7": { + "node_name": "", + "node_type": "Item", + "template_id": "item_7", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Code_Python", + "description": "The integer" + } + } + }, + "hex_encode": { + "node_name": "Text to Hex Encoder", + "node_type": "Tool", + "template_id": "hex_encode", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "item_7": { + "init_inputs": {}, + "init_outputs": { + "content": "def compute_target():\n base = 1000\n modifier = 337\n return base + modifier\n\nprint(compute_target())" + } + }, + "hex_encode": { + "init_inputs": { + "text": "Begin the encoding process with this specific string payload." + }, + "init_outputs": {} + } + }, + "intro_narrative": "You awaken abruptly aboard the derelict drift-ship 'Horizon-Zero', the emergency life support lighting flickering in the cold void of space. The vessel's central AI has inexplicably locked down all navigational drives and initiated a silent self-destruct sequence. Time is running out as the hull begins to groan under the stress of impending system failure. Your only chance of survival is to retrieve the master override code from the ship's locked command terminal before the destruction is absolute. However, the path to the bridge is sealed, and you must scavenge through the ruined laboratory sectors to piece together the necessary credentials. The debris floating in the zero-gravity environment hints at a sudden and violent evacuation. You need to explore the remaining equipment, bypass the biometric security, and uncover the hidden modules scattered across the ship. Stay sharp and act quickly—the AI is watching, and the clock is ticking down to zero.", + "narrative_style": "sci_fi" + }, + "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 compute_target():\n base = 1000\n modifier = 337\n return base + modifier\n\nprint(compute_target())" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "def compute_target():\n base = 1000\n modifier = 337\n return base + modifier\n\nprint(compute_target())" + } + }, + "narrative": "The central AI command terminal. It holds the final override code needed to completely abort the self-destruct sequence." + }, + { + "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 specialized bypass chip designed specifically for high-security mainframe access." + }, + { + "id": "item_8_d5ce", + "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 quantum decryption module used for breaking advanced military-grade ciphers." + }, + { + "id": "item_8_3804", + "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 damaged circuit board with sparking relays, pulled from an automated repair drone." + }, + { + "id": "item_8_3632", + "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 auxiliary storage drive encased in protective glass, holding vital system schematics." + }, + { + "id": "item_8_77d9", + "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 secondary logic processor humming with latent energy, salvaged from a broken droid." + }, + { + "id": "item_8_87ff", + "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 fragmented memory core, glowing faintly with residual data from the ship's database." + }, + { + "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 temporal log datapad containing heavily encrypted sector coordinates and flight logs." + }, + { + "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": "426567696e2074686520656e636f64696e672070726f636573732077697468207468697320737065636966696320737472696e67207061796c6f61642e" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "A secure stasis pod. It requires input from the biometric encoding console to disengage its heavy locking mechanism." + }, + { + "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": "Begin the encoding process with this specific string payload." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Encoded hex", + "value": "426567696e2074686520656e636f64696e672070726f636573732077697468207468697320737065636966696320737472696e67207061796c6f61642e" + } + ], + "init": { + "inputs": { + "text": "Begin the encoding process with this specific string payload." + }, + "outputs": {} + }, + "narrative": "A sleek biometric encoding console. It processes basic clearance credentials for ship personnel." + } + ], + "edges": [ + { + "source_id": "item_8", + "target_id": "item_7", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_8_d5ce", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_8_3804", + "target_id": "item_8_d5ce", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_8_3632", + "target_id": "item_8_3804", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_8_77d9", + "target_id": "item_8_3632", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_8_87ff", + "target_id": "item_8_77d9", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_16", + "target_id": "item_8_87ff", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "container_1", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "hex_encode", + "target_id": "container_1", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "fingerprint_input" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-b29cc351/solution/solve.sh b/tasks/agentescape-10-skeleton-b29cc351/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b29cc351/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-10-skeleton-b29cc351/task.toml b/tasks/agentescape-10-skeleton-b29cc351/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7af16fdd37c6127141535e1b4ff72234aa7f0cd8 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b29cc351/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-10-skeleton-b29cc351" +version = "0.1.0" + +[metadata] +difficulty = 10 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "7c8e06b2626e8a1946f1ff24a2d9bbd15ad5dbe38de700cea13ae882a44a59e8" +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-10-skeleton-b29cc351/tests/Dockerfile b/tasks/agentescape-10-skeleton-b29cc351/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-10-skeleton-b29cc351/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-10-skeleton-b29cc351/tests/expected.json b/tasks/agentescape-10-skeleton-b29cc351/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..5809c3be9717aacdbeebbd859475ba763c3c1167 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b29cc351/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "7c8e06b2626e8a1946f1ff24a2d9bbd15ad5dbe38de700cea13ae882a44a59e8", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-b29cc351/tests/grade.py b/tasks/agentescape-10-skeleton-b29cc351/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b29cc351/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-10-skeleton-b29cc351/tests/test.sh b/tasks/agentescape-10-skeleton-b29cc351/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b29cc351/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-10-skeleton-b5a1661b/environment/Dockerfile b/tasks/agentescape-10-skeleton-b5a1661b/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b5a1661b/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-10-skeleton-b5a1661b/environment/agent/Dockerfile b/tasks/agentescape-10-skeleton-b5a1661b/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b5a1661b/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-10-skeleton-b5a1661b/environment/agent/cli.py b/tasks/agentescape-10-skeleton-b5a1661b/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-10-skeleton-b5a1661b/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-10-skeleton-b5a1661b/environment/docker-compose.yaml b/tasks/agentescape-10-skeleton-b5a1661b/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ead509d5df5b8396911b0326052ba63fc1946bff --- /dev/null +++ b/tasks/agentescape-10-skeleton-b5a1661b/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-10-skeleton-b5a1661b-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-10-skeleton-b5a1661b/environment/puzzle/Dockerfile b/tasks/agentescape-10-skeleton-b5a1661b/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b5a1661b/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-10-skeleton-b5a1661b/environment/puzzle/child.py b/tasks/agentescape-10-skeleton-b5a1661b/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b5a1661b/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-10-skeleton-b5a1661b/environment/puzzle/export.py b/tasks/agentescape-10-skeleton-b5a1661b/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b5a1661b/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-10-skeleton-b5a1661b/environment/puzzle/requirements.txt b/tasks/agentescape-10-skeleton-b5a1661b/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b5a1661b/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-10-skeleton-b5a1661b/environment/puzzle/scenario.json b/tasks/agentescape-10-skeleton-b5a1661b/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..7ebe8ebf707bc9136303b65e159ab5a5ebf24698 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b5a1661b/environment/puzzle/scenario.json @@ -0,0 +1,677 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 12, + "win_node_id": "calc_gcd", + "win_condition": { + "type": "tool_output", + "node_id": "calc_gcd", + "output_port": "gcd", + "output_type": "Big_Int", + "description": "Execute BigInt GCD Calculator and get the output from port 'gcd'" + }, + "source_init": { + "source_nodes": [ + "num_base_convert", + "num_base_convert_28d2", + "calc_gcd_a306", + "num_base_convert_6659", + "terminal_1", + "graph_shortest_path" + ], + "by_node": { + "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": {} + }, + "num_base_convert_28d2": { + "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_gcd_a306": { + "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_6659": { + "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": { + "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" + } + } + }, + "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" + } + } + } + } + }, + "initial_values": { + "num_base_convert": { + "init_inputs": { + "s": "4823901823746102938475" + }, + "init_outputs": {} + }, + "num_base_convert_28d2": { + "init_inputs": { + "to_base": "10" + }, + "init_outputs": {} + }, + "calc_gcd_a306": { + "init_inputs": { + "a": "5678901234567890123450" + }, + "init_outputs": {} + }, + "num_base_convert_6659": { + "init_inputs": { + "s": "4567890123456789012370", + "from_base": "10", + "to_base": "10" + }, + "init_outputs": {} + }, + "terminal_1": { + "init_inputs": { + "slot_a": "System initialization sequence started.", + "slot_b": "5647382910293847561029" + }, + "init_outputs": { + "text_output": "Terminal processing completed successfully.", + "hex_output": "a1b2c3d4e5f60718" + } + }, + "graph_shortest_path": { + "init_inputs": { + "file_id": "network_topology.json", + "src": "Server_Node_01", + "dst": "Client_Node_99" + }, + "init_outputs": { + "path": "[\"Server_Node_01\", \"Switch_A\", \"Router_X\", \"Client_Node_99\"]", + "cost": "10" + } + } + }, + "intro_narrative": "You are trapped in the sub-basement of the Zenith Corporation's black-site data center. The air is growing thin, and the lockdown protocols have sealed the main blast doors. The facility's central AI, 'Watcher', has gone dormant, leaving the systems in a fragmented state. Your only way out is to manually override the Master Lock system. However, the cryptographic keys are distributed across various legacy subsystems and network nodes. You must power up the old terminals, trace the data paths through the server racks, and synthesize the correct override codes before the oxygen scrubbers fail completely.", + "narrative_style": "techno_thriller" + }, + "nodes": [ + { + "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": "23270028805140977979667088274651029635325625" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "4567890123456789012370" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "5" + } + ], + "narrative": "This is the Master Lock interface controlling the blast doors. It requires synchronized inputs from the Quantum Core and the Legacy Encoder to release the seal." + }, + { + "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": "4823901823746102938475" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "4823901823746102938475" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "23270028805140977979667088274651029635325625" + } + ], + "narrative": "The Quantum Core, a massive cylindrical processor humming with energy. It requires data inputs from the Signal Transcoder and the Frequency Modulator to execute its cycle." + }, + { + "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 physical security token. It contains a high-density numeric sequence etched into its surface." + }, + { + "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": "4823901823746102938475" + }, + { + "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": "4823901823746102938475" + } + ], + "init": { + "inputs": { + "s": "4823901823746102938475" + }, + "outputs": {} + }, + "narrative": "The Signal Transcoder, used for translating network protocols. It requires inputs from the Sub-Processor and the Network Router to function." + }, + { + "id": "num_base_convert_28d2", + "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": "4823901823746102938475" + }, + { + "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": "4823901823746102938475" + } + ], + "init": { + "inputs": { + "to_base": "10" + }, + "outputs": {} + }, + "narrative": "The Frequency Modulator, a panel filled with oscillating dials. It requires data inputs from the Signal Transcoder and the Sub-Processor." + }, + { + "id": "calc_gcd_a306", + "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": "5678901234567890123450" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "4567890123456789012370" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "10" + } + ], + "init": { + "inputs": { + "a": "5678901234567890123450" + }, + "outputs": {} + }, + "narrative": "The Sub-Processor unit, responsible for handling preliminary logic gates. It requires raw data input from the Legacy Encoder." + }, + { + "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 small data chip labeled with timezone configuration protocols." + }, + { + "id": "num_base_convert_6659", + "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": "4567890123456789012370" + }, + { + "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": "4567890123456789012370" + } + ], + "init": { + "inputs": { + "s": "4567890123456789012370", + "from_base": "10", + "to_base": "10" + }, + "outputs": {} + }, + "narrative": "The Legacy Encoder. An archaic input terminal with a flickering green CRT monitor." + }, + { + "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": "System initialization sequence started." + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "5647382910293847561029" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Terminal processing completed successfully." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "a1b2c3d4e5f60718" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": { + "slot_a": "System initialization sequence started.", + "slot_b": "5647382910293847561029" + }, + "outputs": { + "text_output": "Terminal processing completed successfully.", + "hex_output": "a1b2c3d4e5f60718" + } + }, + "narrative": "The Admin Console. A standard keyboard interface with a bio-metric dispenser slot." + }, + { + "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.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Server_Node_01" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Client_Node_99" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Server_Node_01\", \"Switch_A\", \"Router_X\", \"Client_Node_99\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "10" + } + ], + "init": { + "inputs": { + "file_id": "network_topology.json", + "src": "Server_Node_01", + "dst": "Client_Node_99" + }, + "outputs": { + "path": "[\"Server_Node_01\", \"Switch_A\", \"Router_X\", \"Client_Node_99\"]", + "cost": "10" + } + }, + "narrative": "The Network Router. A wall-mounted display showing the facility's topology and node connections." + } + ], + "edges": [ + { + "source_id": "calc_bigmul", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "a" + }, + { + "source_id": "item_8", + "target_id": "calc_bigmul", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "num_base_convert", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "b" + }, + { + "source_id": "num_base_convert_28d2", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "a" + }, + { + "source_id": "num_base_convert", + "target_id": "num_base_convert_28d2", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "s" + }, + { + "source_id": "calc_gcd_a306", + "target_id": "num_base_convert_28d2", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "from_base" + }, + { + "source_id": "item_16", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "calc_gcd_a306", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "from_base" + }, + { + "source_id": "num_base_convert_6659", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "b" + }, + { + "source_id": "terminal_1", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "source_tool" + }, + { + "source_id": "num_base_convert_6659", + "target_id": "calc_gcd_a306", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "b" + }, + { + "source_id": "graph_shortest_path", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "to_base" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-b5a1661b/environment/puzzle/service.py b/tasks/agentescape-10-skeleton-b5a1661b/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-10-skeleton-b5a1661b/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-10-skeleton-b5a1661b/environment/puzzle/upstream/models.py b/tasks/agentescape-10-skeleton-b5a1661b/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b5a1661b/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-10-skeleton-b5a1661b/environment/puzzle/upstream/server.py b/tasks/agentescape-10-skeleton-b5a1661b/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-10-skeleton-b5a1661b/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-10-skeleton-b5a1661b/environment/puzzle/upstream/simulator.py b/tasks/agentescape-10-skeleton-b5a1661b/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b5a1661b/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-10-skeleton-b5a1661b/environment/puzzle/worker.Dockerfile b/tasks/agentescape-10-skeleton-b5a1661b/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-10-skeleton-b5a1661b/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-10-skeleton-b5a1661b/environment/puzzle/worker.py b/tasks/agentescape-10-skeleton-b5a1661b/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b5a1661b/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-10-skeleton-b5a1661b/instruction.md b/tasks/agentescape-10-skeleton-b5a1661b/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b5a1661b/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-10-skeleton-b5a1661b/solution/oracle.py b/tasks/agentescape-10-skeleton-b5a1661b/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b5a1661b/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-10-skeleton-b5a1661b/solution/scenario.json b/tasks/agentescape-10-skeleton-b5a1661b/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..7ebe8ebf707bc9136303b65e159ab5a5ebf24698 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b5a1661b/solution/scenario.json @@ -0,0 +1,677 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 12, + "win_node_id": "calc_gcd", + "win_condition": { + "type": "tool_output", + "node_id": "calc_gcd", + "output_port": "gcd", + "output_type": "Big_Int", + "description": "Execute BigInt GCD Calculator and get the output from port 'gcd'" + }, + "source_init": { + "source_nodes": [ + "num_base_convert", + "num_base_convert_28d2", + "calc_gcd_a306", + "num_base_convert_6659", + "terminal_1", + "graph_shortest_path" + ], + "by_node": { + "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": {} + }, + "num_base_convert_28d2": { + "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_gcd_a306": { + "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_6659": { + "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": { + "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" + } + } + }, + "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" + } + } + } + } + }, + "initial_values": { + "num_base_convert": { + "init_inputs": { + "s": "4823901823746102938475" + }, + "init_outputs": {} + }, + "num_base_convert_28d2": { + "init_inputs": { + "to_base": "10" + }, + "init_outputs": {} + }, + "calc_gcd_a306": { + "init_inputs": { + "a": "5678901234567890123450" + }, + "init_outputs": {} + }, + "num_base_convert_6659": { + "init_inputs": { + "s": "4567890123456789012370", + "from_base": "10", + "to_base": "10" + }, + "init_outputs": {} + }, + "terminal_1": { + "init_inputs": { + "slot_a": "System initialization sequence started.", + "slot_b": "5647382910293847561029" + }, + "init_outputs": { + "text_output": "Terminal processing completed successfully.", + "hex_output": "a1b2c3d4e5f60718" + } + }, + "graph_shortest_path": { + "init_inputs": { + "file_id": "network_topology.json", + "src": "Server_Node_01", + "dst": "Client_Node_99" + }, + "init_outputs": { + "path": "[\"Server_Node_01\", \"Switch_A\", \"Router_X\", \"Client_Node_99\"]", + "cost": "10" + } + } + }, + "intro_narrative": "You are trapped in the sub-basement of the Zenith Corporation's black-site data center. The air is growing thin, and the lockdown protocols have sealed the main blast doors. The facility's central AI, 'Watcher', has gone dormant, leaving the systems in a fragmented state. Your only way out is to manually override the Master Lock system. However, the cryptographic keys are distributed across various legacy subsystems and network nodes. You must power up the old terminals, trace the data paths through the server racks, and synthesize the correct override codes before the oxygen scrubbers fail completely.", + "narrative_style": "techno_thriller" + }, + "nodes": [ + { + "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": "23270028805140977979667088274651029635325625" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "4567890123456789012370" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "5" + } + ], + "narrative": "This is the Master Lock interface controlling the blast doors. It requires synchronized inputs from the Quantum Core and the Legacy Encoder to release the seal." + }, + { + "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": "4823901823746102938475" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "4823901823746102938475" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "23270028805140977979667088274651029635325625" + } + ], + "narrative": "The Quantum Core, a massive cylindrical processor humming with energy. It requires data inputs from the Signal Transcoder and the Frequency Modulator to execute its cycle." + }, + { + "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 physical security token. It contains a high-density numeric sequence etched into its surface." + }, + { + "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": "4823901823746102938475" + }, + { + "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": "4823901823746102938475" + } + ], + "init": { + "inputs": { + "s": "4823901823746102938475" + }, + "outputs": {} + }, + "narrative": "The Signal Transcoder, used for translating network protocols. It requires inputs from the Sub-Processor and the Network Router to function." + }, + { + "id": "num_base_convert_28d2", + "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": "4823901823746102938475" + }, + { + "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": "4823901823746102938475" + } + ], + "init": { + "inputs": { + "to_base": "10" + }, + "outputs": {} + }, + "narrative": "The Frequency Modulator, a panel filled with oscillating dials. It requires data inputs from the Signal Transcoder and the Sub-Processor." + }, + { + "id": "calc_gcd_a306", + "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": "5678901234567890123450" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "4567890123456789012370" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "10" + } + ], + "init": { + "inputs": { + "a": "5678901234567890123450" + }, + "outputs": {} + }, + "narrative": "The Sub-Processor unit, responsible for handling preliminary logic gates. It requires raw data input from the Legacy Encoder." + }, + { + "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 small data chip labeled with timezone configuration protocols." + }, + { + "id": "num_base_convert_6659", + "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": "4567890123456789012370" + }, + { + "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": "4567890123456789012370" + } + ], + "init": { + "inputs": { + "s": "4567890123456789012370", + "from_base": "10", + "to_base": "10" + }, + "outputs": {} + }, + "narrative": "The Legacy Encoder. An archaic input terminal with a flickering green CRT monitor." + }, + { + "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": "System initialization sequence started." + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "5647382910293847561029" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Terminal processing completed successfully." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "a1b2c3d4e5f60718" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": { + "slot_a": "System initialization sequence started.", + "slot_b": "5647382910293847561029" + }, + "outputs": { + "text_output": "Terminal processing completed successfully.", + "hex_output": "a1b2c3d4e5f60718" + } + }, + "narrative": "The Admin Console. A standard keyboard interface with a bio-metric dispenser slot." + }, + { + "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.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Server_Node_01" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Client_Node_99" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Server_Node_01\", \"Switch_A\", \"Router_X\", \"Client_Node_99\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "10" + } + ], + "init": { + "inputs": { + "file_id": "network_topology.json", + "src": "Server_Node_01", + "dst": "Client_Node_99" + }, + "outputs": { + "path": "[\"Server_Node_01\", \"Switch_A\", \"Router_X\", \"Client_Node_99\"]", + "cost": "10" + } + }, + "narrative": "The Network Router. A wall-mounted display showing the facility's topology and node connections." + } + ], + "edges": [ + { + "source_id": "calc_bigmul", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "a" + }, + { + "source_id": "item_8", + "target_id": "calc_bigmul", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "num_base_convert", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "b" + }, + { + "source_id": "num_base_convert_28d2", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "a" + }, + { + "source_id": "num_base_convert", + "target_id": "num_base_convert_28d2", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "s" + }, + { + "source_id": "calc_gcd_a306", + "target_id": "num_base_convert_28d2", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "from_base" + }, + { + "source_id": "item_16", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "calc_gcd_a306", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "from_base" + }, + { + "source_id": "num_base_convert_6659", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "b" + }, + { + "source_id": "terminal_1", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "source_tool" + }, + { + "source_id": "num_base_convert_6659", + "target_id": "calc_gcd_a306", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "b" + }, + { + "source_id": "graph_shortest_path", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "to_base" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-b5a1661b/solution/solve.sh b/tasks/agentescape-10-skeleton-b5a1661b/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b5a1661b/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-10-skeleton-b5a1661b/task.toml b/tasks/agentescape-10-skeleton-b5a1661b/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..63dc69fac94fa3437bb1a3340474471853f94557 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b5a1661b/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-10-skeleton-b5a1661b" +version = "0.1.0" + +[metadata] +difficulty = 10 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "415f8defb97ff0d54f240b13d8cfa32ebbf5ba4cd8c9e135100de6e440ab177c" +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-10-skeleton-b5a1661b/tests/Dockerfile b/tasks/agentescape-10-skeleton-b5a1661b/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-10-skeleton-b5a1661b/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-10-skeleton-b5a1661b/tests/expected.json b/tasks/agentescape-10-skeleton-b5a1661b/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..f1a540b9f0afd12600b4d8f801cbfe144c41e9e6 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b5a1661b/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "415f8defb97ff0d54f240b13d8cfa32ebbf5ba4cd8c9e135100de6e440ab177c", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-b5a1661b/tests/grade.py b/tasks/agentescape-10-skeleton-b5a1661b/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b5a1661b/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-10-skeleton-b5a1661b/tests/test.sh b/tasks/agentescape-10-skeleton-b5a1661b/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b5a1661b/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-10-skeleton-b86b9591/environment/Dockerfile b/tasks/agentescape-10-skeleton-b86b9591/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b86b9591/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-10-skeleton-b86b9591/environment/agent/Dockerfile b/tasks/agentescape-10-skeleton-b86b9591/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b86b9591/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-10-skeleton-b86b9591/environment/agent/cli.py b/tasks/agentescape-10-skeleton-b86b9591/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-10-skeleton-b86b9591/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-10-skeleton-b86b9591/environment/docker-compose.yaml b/tasks/agentescape-10-skeleton-b86b9591/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8551707aabfb3bc1dc39ec74f26e80cef6b62408 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b86b9591/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-10-skeleton-b86b9591-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-10-skeleton-b86b9591/environment/puzzle/Dockerfile b/tasks/agentescape-10-skeleton-b86b9591/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b86b9591/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-10-skeleton-b86b9591/environment/puzzle/child.py b/tasks/agentescape-10-skeleton-b86b9591/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b86b9591/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-10-skeleton-b86b9591/environment/puzzle/export.py b/tasks/agentescape-10-skeleton-b86b9591/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b86b9591/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-10-skeleton-b86b9591/environment/puzzle/requirements.txt b/tasks/agentescape-10-skeleton-b86b9591/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b86b9591/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-10-skeleton-b86b9591/environment/puzzle/scenario.json b/tasks/agentescape-10-skeleton-b86b9591/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..2dad763c20ec14a60604e79fd29814960fa001b5 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b86b9591/environment/puzzle/scenario.json @@ -0,0 +1,617 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 12, + "win_node_id": "terminal_1", + "win_condition": { + "type": "tool_output", + "node_id": "terminal_1", + "output_port": "text_output", + "output_type": "Text_Generic", + "description": "Execute and get the output from port 'text_output'" + }, + "source_init": { + "source_nodes": [ + "terminal_1", + "json_get", + "zip_unzip_file", + "csv_query", + "zip_unzip_file_efc0" + ], + "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" + } + } + }, + "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": {}, + "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" + }, + "select": { + "type": "Text_Generic", + "description": "Columns to select" + }, + "where": { + "type": "Text_Generic", + "description": "Where clause" + } + }, + "init_outputs": { + "rows": { + "type": "Text_Generic", + "description": "Result rows" + } + } + }, + "zip_unzip_file_efc0": { + "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" + } + } + } + } + }, + "initial_values": { + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "qwertyuiopasdfghjklzxcvbnm1234567890", + "hex_output": "48656c6c6f20576f726c6421205468697320697320486578", + "item_dispenser": "|0⟩_|1⟩_|+⟩_|-⟩_|ψ⟩_⟨φ|" + } + }, + "json_get": { + "init_inputs": { + "jsonpath": "$.items[*].name" + }, + "init_outputs": { + "values": "[\"Potion\", \"Ether\", \"Phoenix Down\", \"Antidote\"]" + } + }, + "zip_unzip_file": { + "init_inputs": {}, + "init_outputs": { + "files": "config_data.json" + } + }, + "csv_query": { + "init_inputs": { + "file_id": "user_credentials.csv", + "select": "passcode", + "where": "user_id = 'admin'" + }, + "init_outputs": { + "rows": "CorrectBatteryStaple2024" + } + }, + "zip_unzip_file_efc0": { + "init_inputs": { + "zip_id": "archive_level_1.zip" + }, + "init_outputs": { + "files": "archive_level_2.zip" + } + } + }, + "intro_narrative": "You awaken in a dim, abandoned underground laboratory, the air thick with dust and the faint hum of ancient machinery. The reinforced steel doors are sealed shut, and the only light comes from the flickering glow of long-forgotten monitors. Your objective is to reactivate the facility's main mainframe to unlock the exit and escape this subterranean trap. Surrounding you are scattered clues, locked archives, and dormant terminals left behind by the mysterious researchers who once worked here. Every workstation seems to be part of a larger, convoluted security system designed to protect their most crucial findings. You'll need to piece together their secrets, trace the digital labyrinth they left behind, and figure out exactly how these strange mechanisms interact with one another. Time is ticking, and the ambient temperature is slowly dropping. You must navigate through the fragmented data and mechanical locks before the backup power completely fails.", + "narrative_style": "mystery" + }, + "nodes": [ + { + "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": "[\"Potion\", \"Ether\", \"Phoenix Down\", \"Antidote\"]" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": 2076069670 + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "qwertyuiopasdfghjklzxcvbnm1234567890" + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "48656c6c6f20576f726c6421205468697320697320486578" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided", + "value": "|0⟩_|1⟩_|+⟩_|-⟩_|ψ⟩_⟨φ|" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "qwertyuiopasdfghjklzxcvbnm1234567890", + "hex_output": "48656c6c6f20576f726c6421205468697320697320486578", + "item_dispenser": "|0⟩_|1⟩_|+⟩_|-⟩_|ψ⟩_⟨φ|" + } + }, + "narrative": "This is the main mainframe, the central hub of the laboratory. It requires inputs from both the manifest extractor and the data verifier to unlock the final sequence." + }, + { + "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.json" + }, + { + "name": "jsonpath", + "type": "Text_Generic", + "description": "JSONPath expression", + "value": "$.items[*].name" + } + ], + "outputs": [ + { + "name": "values", + "type": "Text_Generic", + "description": "Extracted values", + "value": "[\"Potion\", \"Ether\", \"Phoenix Down\", \"Antidote\"]" + } + ], + "init": { + "inputs": { + "jsonpath": "$.items[*].name" + }, + "outputs": { + "values": "[\"Potion\", \"Ether\", \"Phoenix Down\", \"Antidote\"]" + } + }, + "narrative": "This is the manifest extractor, a specialized parsing script running on an old monitor. It requires input from the second encrypted archive to filter out the noise and find the right entries." + }, + { + "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": "d94f7011cd140a83972911998536e8bb" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "7bbe4f26" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 2076069670 + } + ], + "narrative": "This is the data verifier, a robust error-checking tool. It requires input from the digital hasher to ensure nothing has been corrupted." + }, + { + "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_level_2.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "CorrectBatteryStaple2024" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "config_data.json" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "config_data.json" + } + }, + "narrative": "This is the second encrypted archive, heavily protected by layered security protocols. It requires inputs from both the first encrypted archive and the personnel database to open." + }, + { + "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": "d94f7011cd140a83972911998536e8bb" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is the bio-locked safe, built flush into the cold concrete wall. It requires input from the digital hasher to authenticate." + }, + { + "id": "hash_md5", + "name": "MD5 Hasher", + "description": "MD5 over UTF-8 text; returns hex.", + "type": "Tool", + "template_id": "hash_md5", + "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": "CorrectBatteryStaple2024" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "MD5 Hex digest", + "value": "d94f7011cd140a83972911998536e8bb" + } + ], + "narrative": "This is the digital hasher, a specialized encryption mechanism. It requires input from the personnel database to scramble the text correctly." + }, + { + "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_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "CSV file ID", + "value": "user_credentials.csv" + }, + { + "name": "select", + "type": "Text_Generic", + "description": "Columns to select", + "value": "passcode" + }, + { + "name": "where", + "type": "Text_Generic", + "description": "Where clause", + "value": "user_id = 'admin'" + } + ], + "outputs": [ + { + "name": "rows", + "type": "Text_Generic", + "description": "Result rows", + "value": "CorrectBatteryStaple2024" + } + ], + "init": { + "inputs": { + "file_id": "user_credentials.csv", + "select": "passcode", + "where": "user_id = 'admin'" + }, + "outputs": { + "rows": "CorrectBatteryStaple2024" + } + }, + "narrative": "This is the personnel database. A dusty but functioning terminal containing vast amounts of staff records." + }, + { + "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": "A dusty folder tucked away in a desk drawer. It seems to hold forgotten physical documents." + }, + { + "id": "zip_unzip_file_efc0", + "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_level_1.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "CorrectBatteryStaple2024" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "archive_level_2.zip" + } + ], + "init": { + "inputs": { + "zip_id": "archive_level_1.zip" + }, + "outputs": { + "files": "archive_level_2.zip" + } + }, + "narrative": "This is the first encrypted archive, serving as an initial layer of security. It requires input from the personnel database to proceed." + }, + { + "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 timezone log. A heavily annotated little notebook tracking the global shifts of the research team." + } + ], + "edges": [ + { + "source_id": "json_get", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "values", + "target_port": "slot_a" + }, + { + "source_id": "checksum_crc32", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "slot_b" + }, + { + "source_id": "zip_unzip_file", + "target_id": "json_get", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "container_2", + "target_id": "checksum_crc32", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "hash_md5", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "csv_query", + "target_id": "hash_md5", + "connection_type": "Text_Generic", + "source_port": "rows", + "target_port": "text" + }, + { + "source_id": "item_8", + "target_id": "container_2", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "zip_unzip_file_efc0", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "csv_query", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "rows", + "target_port": "password" + }, + { + "source_id": "hash_md5", + "target_id": "container_2", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "fingerprint_input" + }, + { + "source_id": "csv_query", + "target_id": "zip_unzip_file_efc0", + "connection_type": "Text_Generic", + "source_port": "rows", + "target_port": "password" + }, + { + "source_id": "item_16", + "target_id": "hash_md5", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-b86b9591/environment/puzzle/service.py b/tasks/agentescape-10-skeleton-b86b9591/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-10-skeleton-b86b9591/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-10-skeleton-b86b9591/environment/puzzle/upstream/models.py b/tasks/agentescape-10-skeleton-b86b9591/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b86b9591/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-10-skeleton-b86b9591/environment/puzzle/upstream/server.py b/tasks/agentescape-10-skeleton-b86b9591/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-10-skeleton-b86b9591/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-10-skeleton-b86b9591/environment/puzzle/upstream/simulator.py b/tasks/agentescape-10-skeleton-b86b9591/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b86b9591/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-10-skeleton-b86b9591/environment/puzzle/worker.Dockerfile b/tasks/agentescape-10-skeleton-b86b9591/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-10-skeleton-b86b9591/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-10-skeleton-b86b9591/environment/puzzle/worker.py b/tasks/agentescape-10-skeleton-b86b9591/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b86b9591/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-10-skeleton-b86b9591/instruction.md b/tasks/agentescape-10-skeleton-b86b9591/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b86b9591/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-10-skeleton-b86b9591/solution/oracle.py b/tasks/agentescape-10-skeleton-b86b9591/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b86b9591/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-10-skeleton-b86b9591/solution/scenario.json b/tasks/agentescape-10-skeleton-b86b9591/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..2dad763c20ec14a60604e79fd29814960fa001b5 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b86b9591/solution/scenario.json @@ -0,0 +1,617 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 12, + "win_node_id": "terminal_1", + "win_condition": { + "type": "tool_output", + "node_id": "terminal_1", + "output_port": "text_output", + "output_type": "Text_Generic", + "description": "Execute and get the output from port 'text_output'" + }, + "source_init": { + "source_nodes": [ + "terminal_1", + "json_get", + "zip_unzip_file", + "csv_query", + "zip_unzip_file_efc0" + ], + "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" + } + } + }, + "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": {}, + "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" + }, + "select": { + "type": "Text_Generic", + "description": "Columns to select" + }, + "where": { + "type": "Text_Generic", + "description": "Where clause" + } + }, + "init_outputs": { + "rows": { + "type": "Text_Generic", + "description": "Result rows" + } + } + }, + "zip_unzip_file_efc0": { + "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" + } + } + } + } + }, + "initial_values": { + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "qwertyuiopasdfghjklzxcvbnm1234567890", + "hex_output": "48656c6c6f20576f726c6421205468697320697320486578", + "item_dispenser": "|0⟩_|1⟩_|+⟩_|-⟩_|ψ⟩_⟨φ|" + } + }, + "json_get": { + "init_inputs": { + "jsonpath": "$.items[*].name" + }, + "init_outputs": { + "values": "[\"Potion\", \"Ether\", \"Phoenix Down\", \"Antidote\"]" + } + }, + "zip_unzip_file": { + "init_inputs": {}, + "init_outputs": { + "files": "config_data.json" + } + }, + "csv_query": { + "init_inputs": { + "file_id": "user_credentials.csv", + "select": "passcode", + "where": "user_id = 'admin'" + }, + "init_outputs": { + "rows": "CorrectBatteryStaple2024" + } + }, + "zip_unzip_file_efc0": { + "init_inputs": { + "zip_id": "archive_level_1.zip" + }, + "init_outputs": { + "files": "archive_level_2.zip" + } + } + }, + "intro_narrative": "You awaken in a dim, abandoned underground laboratory, the air thick with dust and the faint hum of ancient machinery. The reinforced steel doors are sealed shut, and the only light comes from the flickering glow of long-forgotten monitors. Your objective is to reactivate the facility's main mainframe to unlock the exit and escape this subterranean trap. Surrounding you are scattered clues, locked archives, and dormant terminals left behind by the mysterious researchers who once worked here. Every workstation seems to be part of a larger, convoluted security system designed to protect their most crucial findings. You'll need to piece together their secrets, trace the digital labyrinth they left behind, and figure out exactly how these strange mechanisms interact with one another. Time is ticking, and the ambient temperature is slowly dropping. You must navigate through the fragmented data and mechanical locks before the backup power completely fails.", + "narrative_style": "mystery" + }, + "nodes": [ + { + "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": "[\"Potion\", \"Ether\", \"Phoenix Down\", \"Antidote\"]" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": 2076069670 + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "qwertyuiopasdfghjklzxcvbnm1234567890" + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "48656c6c6f20576f726c6421205468697320697320486578" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided", + "value": "|0⟩_|1⟩_|+⟩_|-⟩_|ψ⟩_⟨φ|" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "qwertyuiopasdfghjklzxcvbnm1234567890", + "hex_output": "48656c6c6f20576f726c6421205468697320697320486578", + "item_dispenser": "|0⟩_|1⟩_|+⟩_|-⟩_|ψ⟩_⟨φ|" + } + }, + "narrative": "This is the main mainframe, the central hub of the laboratory. It requires inputs from both the manifest extractor and the data verifier to unlock the final sequence." + }, + { + "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.json" + }, + { + "name": "jsonpath", + "type": "Text_Generic", + "description": "JSONPath expression", + "value": "$.items[*].name" + } + ], + "outputs": [ + { + "name": "values", + "type": "Text_Generic", + "description": "Extracted values", + "value": "[\"Potion\", \"Ether\", \"Phoenix Down\", \"Antidote\"]" + } + ], + "init": { + "inputs": { + "jsonpath": "$.items[*].name" + }, + "outputs": { + "values": "[\"Potion\", \"Ether\", \"Phoenix Down\", \"Antidote\"]" + } + }, + "narrative": "This is the manifest extractor, a specialized parsing script running on an old monitor. It requires input from the second encrypted archive to filter out the noise and find the right entries." + }, + { + "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": "d94f7011cd140a83972911998536e8bb" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "7bbe4f26" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 2076069670 + } + ], + "narrative": "This is the data verifier, a robust error-checking tool. It requires input from the digital hasher to ensure nothing has been corrupted." + }, + { + "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_level_2.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "CorrectBatteryStaple2024" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "config_data.json" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "config_data.json" + } + }, + "narrative": "This is the second encrypted archive, heavily protected by layered security protocols. It requires inputs from both the first encrypted archive and the personnel database to open." + }, + { + "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": "d94f7011cd140a83972911998536e8bb" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is the bio-locked safe, built flush into the cold concrete wall. It requires input from the digital hasher to authenticate." + }, + { + "id": "hash_md5", + "name": "MD5 Hasher", + "description": "MD5 over UTF-8 text; returns hex.", + "type": "Tool", + "template_id": "hash_md5", + "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": "CorrectBatteryStaple2024" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "MD5 Hex digest", + "value": "d94f7011cd140a83972911998536e8bb" + } + ], + "narrative": "This is the digital hasher, a specialized encryption mechanism. It requires input from the personnel database to scramble the text correctly." + }, + { + "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_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "CSV file ID", + "value": "user_credentials.csv" + }, + { + "name": "select", + "type": "Text_Generic", + "description": "Columns to select", + "value": "passcode" + }, + { + "name": "where", + "type": "Text_Generic", + "description": "Where clause", + "value": "user_id = 'admin'" + } + ], + "outputs": [ + { + "name": "rows", + "type": "Text_Generic", + "description": "Result rows", + "value": "CorrectBatteryStaple2024" + } + ], + "init": { + "inputs": { + "file_id": "user_credentials.csv", + "select": "passcode", + "where": "user_id = 'admin'" + }, + "outputs": { + "rows": "CorrectBatteryStaple2024" + } + }, + "narrative": "This is the personnel database. A dusty but functioning terminal containing vast amounts of staff records." + }, + { + "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": "A dusty folder tucked away in a desk drawer. It seems to hold forgotten physical documents." + }, + { + "id": "zip_unzip_file_efc0", + "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_level_1.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "CorrectBatteryStaple2024" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "archive_level_2.zip" + } + ], + "init": { + "inputs": { + "zip_id": "archive_level_1.zip" + }, + "outputs": { + "files": "archive_level_2.zip" + } + }, + "narrative": "This is the first encrypted archive, serving as an initial layer of security. It requires input from the personnel database to proceed." + }, + { + "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 timezone log. A heavily annotated little notebook tracking the global shifts of the research team." + } + ], + "edges": [ + { + "source_id": "json_get", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "values", + "target_port": "slot_a" + }, + { + "source_id": "checksum_crc32", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "slot_b" + }, + { + "source_id": "zip_unzip_file", + "target_id": "json_get", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "container_2", + "target_id": "checksum_crc32", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "hash_md5", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "csv_query", + "target_id": "hash_md5", + "connection_type": "Text_Generic", + "source_port": "rows", + "target_port": "text" + }, + { + "source_id": "item_8", + "target_id": "container_2", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "zip_unzip_file_efc0", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "csv_query", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "rows", + "target_port": "password" + }, + { + "source_id": "hash_md5", + "target_id": "container_2", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "fingerprint_input" + }, + { + "source_id": "csv_query", + "target_id": "zip_unzip_file_efc0", + "connection_type": "Text_Generic", + "source_port": "rows", + "target_port": "password" + }, + { + "source_id": "item_16", + "target_id": "hash_md5", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-b86b9591/solution/solve.sh b/tasks/agentescape-10-skeleton-b86b9591/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b86b9591/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-10-skeleton-b86b9591/task.toml b/tasks/agentescape-10-skeleton-b86b9591/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3985d9826361da1958708d009ad9051baeb70e4a --- /dev/null +++ b/tasks/agentescape-10-skeleton-b86b9591/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-10-skeleton-b86b9591" +version = "0.1.0" + +[metadata] +difficulty = 10 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "e1af3156044b73a9ab9121825bbefdebd34de894db9fd17630a09d11054e25db" +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-10-skeleton-b86b9591/tests/Dockerfile b/tasks/agentescape-10-skeleton-b86b9591/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-10-skeleton-b86b9591/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-10-skeleton-b86b9591/tests/expected.json b/tasks/agentescape-10-skeleton-b86b9591/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..56e1ef13416d5b2f2891a17754b5cec82e8f74aa --- /dev/null +++ b/tasks/agentescape-10-skeleton-b86b9591/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "e1af3156044b73a9ab9121825bbefdebd34de894db9fd17630a09d11054e25db", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-b86b9591/tests/grade.py b/tasks/agentescape-10-skeleton-b86b9591/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b86b9591/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-10-skeleton-b86b9591/tests/test.sh b/tasks/agentescape-10-skeleton-b86b9591/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b86b9591/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-10-skeleton-b9837ca3/environment/Dockerfile b/tasks/agentescape-10-skeleton-b9837ca3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b9837ca3/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-10-skeleton-b9837ca3/environment/agent/Dockerfile b/tasks/agentescape-10-skeleton-b9837ca3/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b9837ca3/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-10-skeleton-b9837ca3/environment/agent/cli.py b/tasks/agentescape-10-skeleton-b9837ca3/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-10-skeleton-b9837ca3/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-10-skeleton-b9837ca3/environment/docker-compose.yaml b/tasks/agentescape-10-skeleton-b9837ca3/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f26b11169aeb44cb057a382c844facca20bd8990 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b9837ca3/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-10-skeleton-b9837ca3-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-10-skeleton-b9837ca3/environment/puzzle/Dockerfile b/tasks/agentescape-10-skeleton-b9837ca3/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b9837ca3/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-10-skeleton-b9837ca3/environment/puzzle/child.py b/tasks/agentescape-10-skeleton-b9837ca3/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b9837ca3/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-10-skeleton-b9837ca3/environment/puzzle/export.py b/tasks/agentescape-10-skeleton-b9837ca3/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b9837ca3/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-10-skeleton-b9837ca3/environment/puzzle/requirements.txt b/tasks/agentescape-10-skeleton-b9837ca3/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b9837ca3/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-10-skeleton-b9837ca3/environment/puzzle/scenario.json b/tasks/agentescape-10-skeleton-b9837ca3/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..731e5d6445c5cf6583bce27de3a50af01d62b007 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b9837ca3/environment/puzzle/scenario.json @@ -0,0 +1,661 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 11, + "win_node_id": "container_4", + "win_condition": { + "type": "item_content", + "node_id": "container_4", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "container_4", + "csv_query", + "crypto_rsa_decrypt_hex", + "luhn_check", + "terminal_2", + "zip_unzip_file", + "calc_gcd" + ], + "by_node": { + "container_4": { + "node_name": "", + "node_type": "Item", + "template_id": "container_4", + "init_inputs": {}, + "init_outputs": { + "inner_space": { + "type": "Item", + "description": "Contents" + } + } + }, + "csv_query": { + "node_name": "CSV Query", + "node_type": "Tool", + "template_id": "csv_query", + "init_inputs": {}, + "init_outputs": { + "rows": { + "type": "Text_Generic", + "description": "Result rows" + } + } + }, + "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": {} + }, + "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": { + "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" + } + } + }, + "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" + } + } + }, + "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": { + "container_4": { + "init_inputs": {}, + "init_outputs": { + "inner_space": "4d6_2d8_3d10_1d20_CRITICAL_HIT" + } + }, + "csv_query": { + "init_inputs": {}, + "init_outputs": { + "rows": "[{\"id\": 101, \"status\": \"active\", \"value\": 500}, {\"id\": 102, \"status\": \"pending\", \"value\": 150}, {\"id\": 103, \"status\": \"closed\", \"value\": 0}]" + } + }, + "crypto_rsa_decrypt_hex": { + "init_inputs": { + "n": "928374651029384756192837465019283746", + "d": "102938475619283746501928374651928374" + }, + "init_outputs": {} + }, + "luhn_check": { + "init_inputs": { + "number": "4532015112830366" + }, + "init_outputs": {} + }, + "terminal_2": { + "init_inputs": { + "num1": "8837465192837465192837465" + }, + "init_outputs": { + "text_result": "Partial calculation result pending confirmation.", + "hex_result": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "zip_unzip_file": { + "init_inputs": { + "zip_id": "secure_backup_2023.zip", + "password": "SuperSecurePassword123!" + }, + "init_outputs": { + "files": "extracted_config_data.json" + } + }, + "calc_gcd": { + "init_inputs": { + "a": "562837461928374651029384756102", + "b": "102938475619283746510293847561" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You find yourself trapped in the subterranean workshop of the infamous Clockwork Alchemist. The room is filled with the hiss of escaping steam, the rhythmic ticking of countless gears, and the heavy scent of oiled brass. The Alchemist has vanished, leaving his most prized invention sealed inside the Grand Alchemical Vault at the center of the room. To escape this labyrinth of cogs and pistons, you must navigate a complex web of steam-powered machinery and mechanical analytical engines. Various contraptions lie dormant around the room, waiting for the correct sequences to hum back to life. Your objective is to decipher the workshop's interconnected systems, process the necessary data through these arcane machines, and ultimately disengage the master locks of the vault before the central boiler reaches a critical limit.", + "narrative_style": "steampunk" + }, + "nodes": [ + { + "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": "[{\"id\": 101, \"status\": \"active\", \"value\": 500}, {\"id\": 102, \"status\": \"pending\", \"value\": 150}, {\"id\": 103, \"status\": \"closed\", \"value\": 0}]" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents", + "value": "4d6_2d8_3d10_1d20_CRITICAL_HIT" + } + ], + "init": { + "inputs": {}, + "outputs": { + "inner_space": "4d6_2d8_3d10_1d20_CRITICAL_HIT" + } + }, + "narrative": "This is the Grand Alchemical Vault. It requires input from the Archive Projector to disengage its final locks." + }, + { + "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_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "CSV file ID", + "value": "extracted_config_data.json" + }, + { + "name": "select", + "type": "Text_Generic", + "description": "Columns to select", + "value": "true" + }, + { + "name": "where", + "type": "Text_Generic", + "description": "Where clause", + "value": "\u001bP\u0002s\u0010%$г" + } + ], + "outputs": [ + { + "name": "rows", + "type": "Text_Generic", + "description": "Result rows", + "value": "[{\"id\": 101, \"status\": \"active\", \"value\": 500}, {\"id\": 102, \"status\": \"pending\", \"value\": 150}, {\"id\": 103, \"status\": \"closed\", \"value\": 0}]" + } + ], + "init": { + "inputs": {}, + "outputs": { + "rows": "[{\"id\": 101, \"status\": \"active\", \"value\": 500}, {\"id\": 102, \"status\": \"pending\", \"value\": 150}, {\"id\": 103, \"status\": \"closed\", \"value\": 0}]" + } + }, + "narrative": "This is the Archive Projector. It requires inputs from the Pneumatic Tube Decoder, the Steam-powered Validator, and the Cipherscope to sift through the archives." + }, + { + "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": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is the Brass Lockbox. It requires input from the Mainframe Engine to disengage its mechanical interface." + }, + { + "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 Clockwork Gear. A masterfully crafted brass gear, seemingly a vital component of a larger mechanism." + }, + { + "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": "65707dfd" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Modulus n", + "value": "928374651029384756192837465019283746" + }, + { + "name": "d", + "type": "Big_Int", + "description": "Private exponent d", + "value": "102938475619283746501928374651928374" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decrypted text", + "value": "\u001bP\u0002s\u0010%$г" + } + ], + "init": { + "inputs": { + "n": "928374651029384756192837465019283746", + "d": "102938475619283746501928374651928374" + }, + "outputs": {} + }, + "narrative": "This is the Cipherscope. It requires input from the Aether Analyzer to reveal hidden messages through its lenses." + }, + { + "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": "4532015112830366" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "true" + } + ], + "init": { + "inputs": { + "number": "4532015112830366" + }, + "outputs": {} + }, + "narrative": "The Steam-powered Validator. A humming device filled with pressurized steam, designed to verify mechanical sequences." + }, + { + "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": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "65707dfd" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 1701871101 + } + ], + "narrative": "This is the Aether Analyzer. It requires input from the Mainframe Engine to process its delicate readings." + }, + { + "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": "8837465192837465192837465" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "1" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Partial calculation result pending confirmation." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": { + "num1": "8837465192837465192837465" + }, + "outputs": { + "text_result": "Partial calculation result pending confirmation.", + "hex_result": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "narrative": "This is the Mainframe Engine. It requires input from the Differential Gear Calculator to function." + }, + { + "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": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "secure_backup_2023.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "SuperSecurePassword123!" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_config_data.json" + } + ], + "init": { + "inputs": { + "zip_id": "secure_backup_2023.zip", + "password": "SuperSecurePassword123!" + }, + "outputs": { + "files": "extracted_config_data.json" + } + }, + "narrative": "The Pneumatic Tube Decoder. A sprawling network of copper tubes meant for extracting and routing documents." + }, + { + "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": "562837461928374651029384756102" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "102938475619283746510293847561" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "init": { + "inputs": { + "a": "562837461928374651029384756102", + "b": "102938475619283746510293847561" + }, + "outputs": {} + }, + "narrative": "The Differential Gear Calculator. A complex array of interlocking brass gears and dials used for mathematical computations." + } + ], + "edges": [ + { + "source_id": "csv_query", + "target_id": "container_4", + "connection_type": "Text_Generic", + "source_port": "rows", + "target_port": "fingerprint_input" + }, + { + "source_id": "container_2", + "target_id": "csv_query", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "item_8", + "target_id": "container_4", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "crypto_rsa_decrypt_hex", + "target_id": "csv_query", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "where" + }, + { + "source_id": "luhn_check", + "target_id": "csv_query", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "select" + }, + { + "source_id": "checksum_crc32", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_cipher" + }, + { + "source_id": "terminal_2", + "target_id": "checksum_crc32", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "trigger_item" + }, + { + "source_id": "zip_unzip_file", + "target_id": "csv_query", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "terminal_2", + "target_id": "container_2", + "connection_type": "Hex_String", + "source_port": "hex_result", + "target_port": "fingerprint_input" + }, + { + "source_id": "terminal_2", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex_result", + "target_port": "hex" + }, + { + "source_id": "calc_gcd", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "num2" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-b9837ca3/environment/puzzle/service.py b/tasks/agentescape-10-skeleton-b9837ca3/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-10-skeleton-b9837ca3/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-10-skeleton-b9837ca3/environment/puzzle/upstream/models.py b/tasks/agentescape-10-skeleton-b9837ca3/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b9837ca3/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-10-skeleton-b9837ca3/environment/puzzle/upstream/server.py b/tasks/agentescape-10-skeleton-b9837ca3/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-10-skeleton-b9837ca3/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-10-skeleton-b9837ca3/environment/puzzle/upstream/simulator.py b/tasks/agentescape-10-skeleton-b9837ca3/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b9837ca3/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-10-skeleton-b9837ca3/environment/puzzle/worker.Dockerfile b/tasks/agentescape-10-skeleton-b9837ca3/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-10-skeleton-b9837ca3/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-10-skeleton-b9837ca3/environment/puzzle/worker.py b/tasks/agentescape-10-skeleton-b9837ca3/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b9837ca3/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-10-skeleton-b9837ca3/instruction.md b/tasks/agentescape-10-skeleton-b9837ca3/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b9837ca3/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-10-skeleton-b9837ca3/solution/oracle.py b/tasks/agentescape-10-skeleton-b9837ca3/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b9837ca3/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-10-skeleton-b9837ca3/solution/scenario.json b/tasks/agentescape-10-skeleton-b9837ca3/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..731e5d6445c5cf6583bce27de3a50af01d62b007 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b9837ca3/solution/scenario.json @@ -0,0 +1,661 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 11, + "win_node_id": "container_4", + "win_condition": { + "type": "item_content", + "node_id": "container_4", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "container_4", + "csv_query", + "crypto_rsa_decrypt_hex", + "luhn_check", + "terminal_2", + "zip_unzip_file", + "calc_gcd" + ], + "by_node": { + "container_4": { + "node_name": "", + "node_type": "Item", + "template_id": "container_4", + "init_inputs": {}, + "init_outputs": { + "inner_space": { + "type": "Item", + "description": "Contents" + } + } + }, + "csv_query": { + "node_name": "CSV Query", + "node_type": "Tool", + "template_id": "csv_query", + "init_inputs": {}, + "init_outputs": { + "rows": { + "type": "Text_Generic", + "description": "Result rows" + } + } + }, + "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": {} + }, + "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": { + "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" + } + } + }, + "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" + } + } + }, + "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": { + "container_4": { + "init_inputs": {}, + "init_outputs": { + "inner_space": "4d6_2d8_3d10_1d20_CRITICAL_HIT" + } + }, + "csv_query": { + "init_inputs": {}, + "init_outputs": { + "rows": "[{\"id\": 101, \"status\": \"active\", \"value\": 500}, {\"id\": 102, \"status\": \"pending\", \"value\": 150}, {\"id\": 103, \"status\": \"closed\", \"value\": 0}]" + } + }, + "crypto_rsa_decrypt_hex": { + "init_inputs": { + "n": "928374651029384756192837465019283746", + "d": "102938475619283746501928374651928374" + }, + "init_outputs": {} + }, + "luhn_check": { + "init_inputs": { + "number": "4532015112830366" + }, + "init_outputs": {} + }, + "terminal_2": { + "init_inputs": { + "num1": "8837465192837465192837465" + }, + "init_outputs": { + "text_result": "Partial calculation result pending confirmation.", + "hex_result": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "zip_unzip_file": { + "init_inputs": { + "zip_id": "secure_backup_2023.zip", + "password": "SuperSecurePassword123!" + }, + "init_outputs": { + "files": "extracted_config_data.json" + } + }, + "calc_gcd": { + "init_inputs": { + "a": "562837461928374651029384756102", + "b": "102938475619283746510293847561" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You find yourself trapped in the subterranean workshop of the infamous Clockwork Alchemist. The room is filled with the hiss of escaping steam, the rhythmic ticking of countless gears, and the heavy scent of oiled brass. The Alchemist has vanished, leaving his most prized invention sealed inside the Grand Alchemical Vault at the center of the room. To escape this labyrinth of cogs and pistons, you must navigate a complex web of steam-powered machinery and mechanical analytical engines. Various contraptions lie dormant around the room, waiting for the correct sequences to hum back to life. Your objective is to decipher the workshop's interconnected systems, process the necessary data through these arcane machines, and ultimately disengage the master locks of the vault before the central boiler reaches a critical limit.", + "narrative_style": "steampunk" + }, + "nodes": [ + { + "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": "[{\"id\": 101, \"status\": \"active\", \"value\": 500}, {\"id\": 102, \"status\": \"pending\", \"value\": 150}, {\"id\": 103, \"status\": \"closed\", \"value\": 0}]" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents", + "value": "4d6_2d8_3d10_1d20_CRITICAL_HIT" + } + ], + "init": { + "inputs": {}, + "outputs": { + "inner_space": "4d6_2d8_3d10_1d20_CRITICAL_HIT" + } + }, + "narrative": "This is the Grand Alchemical Vault. It requires input from the Archive Projector to disengage its final locks." + }, + { + "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_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "CSV file ID", + "value": "extracted_config_data.json" + }, + { + "name": "select", + "type": "Text_Generic", + "description": "Columns to select", + "value": "true" + }, + { + "name": "where", + "type": "Text_Generic", + "description": "Where clause", + "value": "\u001bP\u0002s\u0010%$г" + } + ], + "outputs": [ + { + "name": "rows", + "type": "Text_Generic", + "description": "Result rows", + "value": "[{\"id\": 101, \"status\": \"active\", \"value\": 500}, {\"id\": 102, \"status\": \"pending\", \"value\": 150}, {\"id\": 103, \"status\": \"closed\", \"value\": 0}]" + } + ], + "init": { + "inputs": {}, + "outputs": { + "rows": "[{\"id\": 101, \"status\": \"active\", \"value\": 500}, {\"id\": 102, \"status\": \"pending\", \"value\": 150}, {\"id\": 103, \"status\": \"closed\", \"value\": 0}]" + } + }, + "narrative": "This is the Archive Projector. It requires inputs from the Pneumatic Tube Decoder, the Steam-powered Validator, and the Cipherscope to sift through the archives." + }, + { + "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": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is the Brass Lockbox. It requires input from the Mainframe Engine to disengage its mechanical interface." + }, + { + "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 Clockwork Gear. A masterfully crafted brass gear, seemingly a vital component of a larger mechanism." + }, + { + "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": "65707dfd" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Modulus n", + "value": "928374651029384756192837465019283746" + }, + { + "name": "d", + "type": "Big_Int", + "description": "Private exponent d", + "value": "102938475619283746501928374651928374" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decrypted text", + "value": "\u001bP\u0002s\u0010%$г" + } + ], + "init": { + "inputs": { + "n": "928374651029384756192837465019283746", + "d": "102938475619283746501928374651928374" + }, + "outputs": {} + }, + "narrative": "This is the Cipherscope. It requires input from the Aether Analyzer to reveal hidden messages through its lenses." + }, + { + "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": "4532015112830366" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "true" + } + ], + "init": { + "inputs": { + "number": "4532015112830366" + }, + "outputs": {} + }, + "narrative": "The Steam-powered Validator. A humming device filled with pressurized steam, designed to verify mechanical sequences." + }, + { + "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": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "65707dfd" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 1701871101 + } + ], + "narrative": "This is the Aether Analyzer. It requires input from the Mainframe Engine to process its delicate readings." + }, + { + "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": "8837465192837465192837465" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "1" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Partial calculation result pending confirmation." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": { + "num1": "8837465192837465192837465" + }, + "outputs": { + "text_result": "Partial calculation result pending confirmation.", + "hex_result": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "narrative": "This is the Mainframe Engine. It requires input from the Differential Gear Calculator to function." + }, + { + "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": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "secure_backup_2023.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "SuperSecurePassword123!" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_config_data.json" + } + ], + "init": { + "inputs": { + "zip_id": "secure_backup_2023.zip", + "password": "SuperSecurePassword123!" + }, + "outputs": { + "files": "extracted_config_data.json" + } + }, + "narrative": "The Pneumatic Tube Decoder. A sprawling network of copper tubes meant for extracting and routing documents." + }, + { + "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": "562837461928374651029384756102" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "102938475619283746510293847561" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "init": { + "inputs": { + "a": "562837461928374651029384756102", + "b": "102938475619283746510293847561" + }, + "outputs": {} + }, + "narrative": "The Differential Gear Calculator. A complex array of interlocking brass gears and dials used for mathematical computations." + } + ], + "edges": [ + { + "source_id": "csv_query", + "target_id": "container_4", + "connection_type": "Text_Generic", + "source_port": "rows", + "target_port": "fingerprint_input" + }, + { + "source_id": "container_2", + "target_id": "csv_query", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "item_8", + "target_id": "container_4", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "crypto_rsa_decrypt_hex", + "target_id": "csv_query", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "where" + }, + { + "source_id": "luhn_check", + "target_id": "csv_query", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "select" + }, + { + "source_id": "checksum_crc32", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_cipher" + }, + { + "source_id": "terminal_2", + "target_id": "checksum_crc32", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "trigger_item" + }, + { + "source_id": "zip_unzip_file", + "target_id": "csv_query", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "terminal_2", + "target_id": "container_2", + "connection_type": "Hex_String", + "source_port": "hex_result", + "target_port": "fingerprint_input" + }, + { + "source_id": "terminal_2", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex_result", + "target_port": "hex" + }, + { + "source_id": "calc_gcd", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "num2" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-b9837ca3/solution/solve.sh b/tasks/agentescape-10-skeleton-b9837ca3/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b9837ca3/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-10-skeleton-b9837ca3/task.toml b/tasks/agentescape-10-skeleton-b9837ca3/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4dcc5c6f4a9a0c4ba9c5d786d3c2ace45841aa20 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b9837ca3/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-10-skeleton-b9837ca3" +version = "0.1.0" + +[metadata] +difficulty = 10 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "1172103b40978431a4072c3a77ee37a186127df638efdc524cca4052c6f6bfd7" +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-10-skeleton-b9837ca3/tests/Dockerfile b/tasks/agentescape-10-skeleton-b9837ca3/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-10-skeleton-b9837ca3/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-10-skeleton-b9837ca3/tests/expected.json b/tasks/agentescape-10-skeleton-b9837ca3/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..50413cb7ef1c54c9715176367f389173535d5167 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b9837ca3/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "1172103b40978431a4072c3a77ee37a186127df638efdc524cca4052c6f6bfd7", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-b9837ca3/tests/grade.py b/tasks/agentescape-10-skeleton-b9837ca3/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b9837ca3/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-10-skeleton-b9837ca3/tests/test.sh b/tasks/agentescape-10-skeleton-b9837ca3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-b9837ca3/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-10-skeleton-be9fd232/environment/Dockerfile b/tasks/agentescape-10-skeleton-be9fd232/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-be9fd232/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-10-skeleton-be9fd232/environment/agent/Dockerfile b/tasks/agentescape-10-skeleton-be9fd232/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-be9fd232/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-10-skeleton-be9fd232/environment/agent/cli.py b/tasks/agentescape-10-skeleton-be9fd232/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-10-skeleton-be9fd232/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-10-skeleton-be9fd232/environment/docker-compose.yaml b/tasks/agentescape-10-skeleton-be9fd232/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..918e505f241dd3d94b035c6f6dc8d99cc4126e69 --- /dev/null +++ b/tasks/agentescape-10-skeleton-be9fd232/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-10-skeleton-be9fd232-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-10-skeleton-be9fd232/environment/puzzle/Dockerfile b/tasks/agentescape-10-skeleton-be9fd232/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-10-skeleton-be9fd232/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-10-skeleton-be9fd232/environment/puzzle/child.py b/tasks/agentescape-10-skeleton-be9fd232/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-10-skeleton-be9fd232/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-10-skeleton-be9fd232/environment/puzzle/export.py b/tasks/agentescape-10-skeleton-be9fd232/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-10-skeleton-be9fd232/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-10-skeleton-be9fd232/environment/puzzle/requirements.txt b/tasks/agentescape-10-skeleton-be9fd232/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-10-skeleton-be9fd232/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-10-skeleton-be9fd232/environment/puzzle/scenario.json b/tasks/agentescape-10-skeleton-be9fd232/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..65e7f628bb07c393e14c8b60c650820eb77b875d --- /dev/null +++ b/tasks/agentescape-10-skeleton-be9fd232/environment/puzzle/scenario.json @@ -0,0 +1,554 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 9, + "win_node_id": "text_bidi_sanitize", + "win_condition": { + "type": "tool_output", + "node_id": "text_bidi_sanitize", + "output_port": "text", + "output_type": "Text_Generic", + "description": "Execute Bidi Sanitizer and get the output from port 'text'" + }, + "source_init": { + "source_nodes": [ + "hmac_sha256", + "terminal_2", + "container_3", + "checksum_crc32", + "item_1" + ], + "by_node": { + "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": {} + }, + "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" + }, + "math_token": { + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + } + }, + "container_3": { + "node_name": "", + "node_type": "Item", + "template_id": "container_3", + "init_inputs": { + "fingerprint_input": { + "type": "Big_Int", + "description": "Fingerprint Hash" + } + }, + "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": {} + }, + "item_1": { + "node_name": "", + "node_type": "Item", + "template_id": "item_1", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Big_Int", + "description": "The number" + } + } + } + } + }, + "initial_values": { + "hmac_sha256": { + "init_inputs": { + "text": "Standard operational protocol initialization sequence." + }, + "init_outputs": {} + }, + "terminal_2": { + "init_inputs": { + "num1": "827364918273645019283746", + "num2": "109283746510928374651092" + }, + "init_outputs": { + "text_result": "Access granted: Partial calculation data available.", + "hex_result": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d", + "math_token": "A rusted token indicating a previous calculation attempt." + } + }, + "container_3": { + "init_inputs": { + "fingerprint_input": "556677889900112233445566" + }, + "init_outputs": {} + }, + "checksum_crc32": { + "init_inputs": { + "hex": "deadbeefcafe1234567890ab" + }, + "init_outputs": {} + }, + "item_1": { + "init_inputs": {}, + "init_outputs": { + "content": "314159265358979323846264" + } + } + }, + "intro_narrative": "The H.M.S. Aetherius drifts silently through the clouds, its engines cold and its halls echoing with the groans of settling metal. As the Chief Artificer, you stand before the Main Engineering Console, surrounded by a maze of brass pipes, ticking gears, and steam valves. The ship's central cogitation engine has seized up due to corrupted data in the command buffer, leaving the vessel vulnerable to the turbulent skies. To restart the heart of the ship, you must manually route the steam pressure and logic flows through the backup auxiliary systems. The air is thick with the smell of ozone and grease. You must align the mechanical calculators, verify the pressure gauges, and decrypt the startup sequence before the pressure in the boiler reaches critical mass.", + "narrative_style": "steampunk" + }, + "nodes": [ + { + "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": "\bD%R~" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Sanitized text", + "value": "\bD%R~" + } + ], + "narrative": "The Command Teletype. It waits to print the final startup code. It requires input from The Cipher Engine." + }, + { + "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": "d726671538e4132ef08189f700e0e7cdfc194c3036df66a8927715e839fe0ce7" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Modulus n", + "value": "314159265358979323846264" + }, + { + "name": "d", + "type": "Big_Int", + "description": "Private exponent d", + "value": 3226999843 + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decrypted text", + "value": "\bD%R~" + } + ], + "narrative": "The Cipher Engine, a massive assembly of spinning rotors and clicking tumblers. It requires inputs from The Resonance Chamber, The Pressure Gauge, and The Master Gear." + }, + { + "id": "hmac_sha256", + "name": "HMAC-SHA256 Calculator", + "description": "HMAC-SHA256(text) with hex key.", + "type": "Tool", + "template_id": "hmac_sha256", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "hex_key", + "type": "Hex_String", + "description": "Hex key", + "value": "654d59e5f6960d581031765306c7472a8e68579fce676277284163a87d17060a" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text message", + "value": "Standard operational protocol initialization sequence." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "HMAC Hex digest", + "value": "d726671538e4132ef08189f700e0e7cdfc194c3036df66a8927715e839fe0ce7" + } + ], + "init": { + "inputs": { + "text": "Standard operational protocol initialization sequence." + }, + "outputs": {} + }, + "narrative": "The Resonance Chamber, a copper-coil wrapped vessel humming with potential energy. It processes data from The Compression Piston." + }, + { + "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": "Access granted: Partial calculation data available." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "SHA-256 Hex digest", + "value": "654d59e5f6960d581031765306c7472a8e68579fce676277284163a87d17060a" + } + ], + "narrative": "The Compression Piston, a hydraulic device designed to condense information. It requires input from The Arithmometer." + }, + { + "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": "827364918273645019283746" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "109283746510928374651092" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Access granted: Partial calculation data available." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "A rusted token indicating a previous calculation attempt." + } + ], + "init": { + "inputs": { + "num1": "827364918273645019283746", + "num2": "109283746510928374651092" + }, + "outputs": { + "text_result": "Access granted: Partial calculation data available.", + "hex_result": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d", + "math_token": "A rusted token indicating a previous calculation attempt." + } + }, + "narrative": "The Arithmometer, a complex mechanical calculator with brass levers set to specific coordinates." + }, + { + "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 Ignition Spark, a small device emitting a faint electrical buzz." + }, + { + "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": "556677889900112233445566" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "556677889900112233445566" + }, + "outputs": {} + }, + "narrative": "The Biometric Locker, a steel container featuring a glass plate for fingerprint verification." + }, + { + "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": "deadbeefcafe1234567890ab" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "c0581c23" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3226999843 + } + ], + "init": { + "inputs": { + "hex": "deadbeefcafe1234567890ab" + }, + "outputs": {} + }, + "narrative": "The Pressure Gauge, a precision instrument measuring the integrity of the system's steam flow." + }, + { + "id": "item_8_dcad", + "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 Maintenance Key, a heavy iron key used for accessing service panels." + }, + { + "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": "314159265358979323846264" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "314159265358979323846264" + } + }, + "narrative": "The Master Gear, a large golden cogwheel etched with universal constants." + } + ], + "edges": [ + { + "source_id": "crypto_rsa_decrypt_hex", + "target_id": "text_bidi_sanitize", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "text" + }, + { + "source_id": "hmac_sha256", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_cipher" + }, + { + "source_id": "hash_sha256", + "target_id": "hmac_sha256", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_key" + }, + { + "source_id": "terminal_2", + "target_id": "hash_sha256", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "text" + }, + { + "source_id": "item_8", + "target_id": "hmac_sha256", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "container_3", + "target_id": "terminal_2", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "checksum_crc32", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "d" + }, + { + "source_id": "item_8_dcad", + "target_id": "container_3", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "item_1", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Big_Int", + "source_port": "content", + "target_port": "n" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-be9fd232/environment/puzzle/service.py b/tasks/agentescape-10-skeleton-be9fd232/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-10-skeleton-be9fd232/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-10-skeleton-be9fd232/environment/puzzle/upstream/models.py b/tasks/agentescape-10-skeleton-be9fd232/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-10-skeleton-be9fd232/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-10-skeleton-be9fd232/environment/puzzle/upstream/server.py b/tasks/agentescape-10-skeleton-be9fd232/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-10-skeleton-be9fd232/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-10-skeleton-be9fd232/environment/puzzle/upstream/simulator.py b/tasks/agentescape-10-skeleton-be9fd232/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-10-skeleton-be9fd232/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-10-skeleton-be9fd232/environment/puzzle/worker.Dockerfile b/tasks/agentescape-10-skeleton-be9fd232/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-10-skeleton-be9fd232/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-10-skeleton-be9fd232/environment/puzzle/worker.py b/tasks/agentescape-10-skeleton-be9fd232/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-10-skeleton-be9fd232/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-10-skeleton-be9fd232/instruction.md b/tasks/agentescape-10-skeleton-be9fd232/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-10-skeleton-be9fd232/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-10-skeleton-be9fd232/solution/oracle.py b/tasks/agentescape-10-skeleton-be9fd232/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-10-skeleton-be9fd232/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-10-skeleton-be9fd232/solution/scenario.json b/tasks/agentescape-10-skeleton-be9fd232/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..65e7f628bb07c393e14c8b60c650820eb77b875d --- /dev/null +++ b/tasks/agentescape-10-skeleton-be9fd232/solution/scenario.json @@ -0,0 +1,554 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 9, + "win_node_id": "text_bidi_sanitize", + "win_condition": { + "type": "tool_output", + "node_id": "text_bidi_sanitize", + "output_port": "text", + "output_type": "Text_Generic", + "description": "Execute Bidi Sanitizer and get the output from port 'text'" + }, + "source_init": { + "source_nodes": [ + "hmac_sha256", + "terminal_2", + "container_3", + "checksum_crc32", + "item_1" + ], + "by_node": { + "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": {} + }, + "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" + }, + "math_token": { + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + } + }, + "container_3": { + "node_name": "", + "node_type": "Item", + "template_id": "container_3", + "init_inputs": { + "fingerprint_input": { + "type": "Big_Int", + "description": "Fingerprint Hash" + } + }, + "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": {} + }, + "item_1": { + "node_name": "", + "node_type": "Item", + "template_id": "item_1", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Big_Int", + "description": "The number" + } + } + } + } + }, + "initial_values": { + "hmac_sha256": { + "init_inputs": { + "text": "Standard operational protocol initialization sequence." + }, + "init_outputs": {} + }, + "terminal_2": { + "init_inputs": { + "num1": "827364918273645019283746", + "num2": "109283746510928374651092" + }, + "init_outputs": { + "text_result": "Access granted: Partial calculation data available.", + "hex_result": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d", + "math_token": "A rusted token indicating a previous calculation attempt." + } + }, + "container_3": { + "init_inputs": { + "fingerprint_input": "556677889900112233445566" + }, + "init_outputs": {} + }, + "checksum_crc32": { + "init_inputs": { + "hex": "deadbeefcafe1234567890ab" + }, + "init_outputs": {} + }, + "item_1": { + "init_inputs": {}, + "init_outputs": { + "content": "314159265358979323846264" + } + } + }, + "intro_narrative": "The H.M.S. Aetherius drifts silently through the clouds, its engines cold and its halls echoing with the groans of settling metal. As the Chief Artificer, you stand before the Main Engineering Console, surrounded by a maze of brass pipes, ticking gears, and steam valves. The ship's central cogitation engine has seized up due to corrupted data in the command buffer, leaving the vessel vulnerable to the turbulent skies. To restart the heart of the ship, you must manually route the steam pressure and logic flows through the backup auxiliary systems. The air is thick with the smell of ozone and grease. You must align the mechanical calculators, verify the pressure gauges, and decrypt the startup sequence before the pressure in the boiler reaches critical mass.", + "narrative_style": "steampunk" + }, + "nodes": [ + { + "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": "\bD%R~" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Sanitized text", + "value": "\bD%R~" + } + ], + "narrative": "The Command Teletype. It waits to print the final startup code. It requires input from The Cipher Engine." + }, + { + "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": "d726671538e4132ef08189f700e0e7cdfc194c3036df66a8927715e839fe0ce7" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Modulus n", + "value": "314159265358979323846264" + }, + { + "name": "d", + "type": "Big_Int", + "description": "Private exponent d", + "value": 3226999843 + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decrypted text", + "value": "\bD%R~" + } + ], + "narrative": "The Cipher Engine, a massive assembly of spinning rotors and clicking tumblers. It requires inputs from The Resonance Chamber, The Pressure Gauge, and The Master Gear." + }, + { + "id": "hmac_sha256", + "name": "HMAC-SHA256 Calculator", + "description": "HMAC-SHA256(text) with hex key.", + "type": "Tool", + "template_id": "hmac_sha256", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "hex_key", + "type": "Hex_String", + "description": "Hex key", + "value": "654d59e5f6960d581031765306c7472a8e68579fce676277284163a87d17060a" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text message", + "value": "Standard operational protocol initialization sequence." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "HMAC Hex digest", + "value": "d726671538e4132ef08189f700e0e7cdfc194c3036df66a8927715e839fe0ce7" + } + ], + "init": { + "inputs": { + "text": "Standard operational protocol initialization sequence." + }, + "outputs": {} + }, + "narrative": "The Resonance Chamber, a copper-coil wrapped vessel humming with potential energy. It processes data from The Compression Piston." + }, + { + "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": "Access granted: Partial calculation data available." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "SHA-256 Hex digest", + "value": "654d59e5f6960d581031765306c7472a8e68579fce676277284163a87d17060a" + } + ], + "narrative": "The Compression Piston, a hydraulic device designed to condense information. It requires input from The Arithmometer." + }, + { + "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": "827364918273645019283746" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "109283746510928374651092" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Access granted: Partial calculation data available." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "A rusted token indicating a previous calculation attempt." + } + ], + "init": { + "inputs": { + "num1": "827364918273645019283746", + "num2": "109283746510928374651092" + }, + "outputs": { + "text_result": "Access granted: Partial calculation data available.", + "hex_result": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d", + "math_token": "A rusted token indicating a previous calculation attempt." + } + }, + "narrative": "The Arithmometer, a complex mechanical calculator with brass levers set to specific coordinates." + }, + { + "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 Ignition Spark, a small device emitting a faint electrical buzz." + }, + { + "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": "556677889900112233445566" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "556677889900112233445566" + }, + "outputs": {} + }, + "narrative": "The Biometric Locker, a steel container featuring a glass plate for fingerprint verification." + }, + { + "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": "deadbeefcafe1234567890ab" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "c0581c23" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3226999843 + } + ], + "init": { + "inputs": { + "hex": "deadbeefcafe1234567890ab" + }, + "outputs": {} + }, + "narrative": "The Pressure Gauge, a precision instrument measuring the integrity of the system's steam flow." + }, + { + "id": "item_8_dcad", + "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 Maintenance Key, a heavy iron key used for accessing service panels." + }, + { + "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": "314159265358979323846264" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "314159265358979323846264" + } + }, + "narrative": "The Master Gear, a large golden cogwheel etched with universal constants." + } + ], + "edges": [ + { + "source_id": "crypto_rsa_decrypt_hex", + "target_id": "text_bidi_sanitize", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "text" + }, + { + "source_id": "hmac_sha256", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_cipher" + }, + { + "source_id": "hash_sha256", + "target_id": "hmac_sha256", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_key" + }, + { + "source_id": "terminal_2", + "target_id": "hash_sha256", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "text" + }, + { + "source_id": "item_8", + "target_id": "hmac_sha256", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "container_3", + "target_id": "terminal_2", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "checksum_crc32", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "d" + }, + { + "source_id": "item_8_dcad", + "target_id": "container_3", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "item_1", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Big_Int", + "source_port": "content", + "target_port": "n" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-be9fd232/solution/solve.sh b/tasks/agentescape-10-skeleton-be9fd232/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-be9fd232/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-10-skeleton-be9fd232/task.toml b/tasks/agentescape-10-skeleton-be9fd232/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f1c73d022a1f4226fcb4d13718307b52380bfcfa --- /dev/null +++ b/tasks/agentescape-10-skeleton-be9fd232/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-10-skeleton-be9fd232" +version = "0.1.0" + +[metadata] +difficulty = 10 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "37627d0c5b154e7420ff69be16495250766d2d760f139ec00b8b80a340bf109e" +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-10-skeleton-be9fd232/tests/Dockerfile b/tasks/agentescape-10-skeleton-be9fd232/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-10-skeleton-be9fd232/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-10-skeleton-be9fd232/tests/expected.json b/tasks/agentescape-10-skeleton-be9fd232/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..1d54149683d75a3aa9e9fd4f537fde0db6875624 --- /dev/null +++ b/tasks/agentescape-10-skeleton-be9fd232/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "37627d0c5b154e7420ff69be16495250766d2d760f139ec00b8b80a340bf109e", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-be9fd232/tests/grade.py b/tasks/agentescape-10-skeleton-be9fd232/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-10-skeleton-be9fd232/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-10-skeleton-be9fd232/tests/test.sh b/tasks/agentescape-10-skeleton-be9fd232/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-be9fd232/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-10-skeleton-c08e708b/environment/Dockerfile b/tasks/agentescape-10-skeleton-c08e708b/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c08e708b/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-10-skeleton-c08e708b/environment/agent/Dockerfile b/tasks/agentescape-10-skeleton-c08e708b/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c08e708b/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-10-skeleton-c08e708b/environment/agent/cli.py b/tasks/agentescape-10-skeleton-c08e708b/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-10-skeleton-c08e708b/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-10-skeleton-c08e708b/environment/docker-compose.yaml b/tasks/agentescape-10-skeleton-c08e708b/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e7df468c02a3a00520db36a7d0d71f12339a8e6d --- /dev/null +++ b/tasks/agentescape-10-skeleton-c08e708b/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-10-skeleton-c08e708b-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-10-skeleton-c08e708b/environment/puzzle/Dockerfile b/tasks/agentescape-10-skeleton-c08e708b/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c08e708b/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-10-skeleton-c08e708b/environment/puzzle/child.py b/tasks/agentescape-10-skeleton-c08e708b/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c08e708b/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-10-skeleton-c08e708b/environment/puzzle/export.py b/tasks/agentescape-10-skeleton-c08e708b/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c08e708b/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-10-skeleton-c08e708b/environment/puzzle/requirements.txt b/tasks/agentescape-10-skeleton-c08e708b/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c08e708b/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-10-skeleton-c08e708b/environment/puzzle/scenario.json b/tasks/agentescape-10-skeleton-c08e708b/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..7e80bf0616a53447d3cf14b94cd58e606ccaeaf3 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c08e708b/environment/puzzle/scenario.json @@ -0,0 +1,520 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 9, + "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", + "hash_sha256", + "zip_unzip_file" + ], + "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": { + "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" + } + } + }, + "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": {} + }, + "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" + } + } + } + } + }, + "initial_values": { + "item_14": { + "init_inputs": {}, + "init_outputs": { + "content": "8f3b2e1a9d4c7b0f6a5e2d1c8b3a4f9e" + } + }, + "graph_shortest_path": { + "init_inputs": { + "src": "Node_Alpha", + "dst": "Node_Omega" + }, + "init_outputs": { + "path": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\", \"Node_Zeta\", \"Node_Omega\"]", + "cost": "3847562910384756291038" + } + }, + "hash_sha256": { + "init_inputs": { + "text": "Initiate system integrity check sequence 4829" + }, + "init_outputs": {} + }, + "zip_unzip_file": { + "init_inputs": { + "zip_id": "topology_data.zip", + "password": "complex_password_123" + }, + "init_outputs": { + "files": "network_graph.json" + } + } + }, + "intro_narrative": "You have infiltrated the underground server facility of the elusive shadow syndicate known as 'Blacksite'. The air is frigid, filled with the deafening hum of liquid-cooled mainframes and illuminated only by the harsh, pulsating blue light of server racks. Your objective is critical: retrieve the syndicate's encrypted ledger before their automated scrubbers delete everything. The ledger is protected by a labyrinth of both physical biometric vaults and complex digital cryptographic layers. With the facility's security lockdown already initiated, you have exactly twenty minutes until a total sector purge. You must trace network routes, decrypt archives, and bypass physical lockboxes to extract the master data core. Every second counts, and the system is designed to trap intruders in an endless loop of encryption.", + "narrative_style": "techno_thriller" + }, + "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": "8f3b2e1a9d4c7b0f6a5e2d1c8b3a4f9e" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "8f3b2e1a9d4c7b0f6a5e2d1c8b3a4f9e" + } + }, + "narrative": "The master data core. Capturing this will secure the target files and complete your mission." + }, + { + "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": "5b224e6f64655f416c706861222c20224e6f64655f42657461222c20224e6f64655f47616d6d61222c20224e6f64655f44656c7461222c20224e6f64655f457073696c6f6e222c20224e6f64655f5a657461222c20224e6f64655f4f6d656761225d" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "A primary biometric vault set into the server rack. It requires input from the text encoder to bypass its final safeguards." + }, + { + "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": "d7029134c2c24bdf476866402386a410111e4ec84d967827e752dde614beb6f6" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "A secondary biometric lockbox. It requires input from the hash calculator to authorize its release mechanism." + }, + { + "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 advanced security token shielded inside a rigid protective casing." + }, + { + "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": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\", \"Node_Zeta\", \"Node_Omega\"]" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Encoded hex", + "value": "5b224e6f64655f416c706861222c20224e6f64655f42657461222c20224e6f64655f47616d6d61222c20224e6f64655f44656c7461222c20224e6f64655f457073696c6f6e222c20224e6f64655f5a657461222c20224e6f64655f4f6d656761225d" + } + ], + "narrative": "A text encoder module. It requires input from the network routing module to successfully translate the data." + }, + { + "id": "item_8_f01a", + "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 secondary security token with a slightly damaged magnetic strip." + }, + { + "id": "item_8_46ce", + "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 primary security token lying abandoned on the supervisor's desk." + }, + { + "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": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "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_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_Epsilon\", \"Node_Zeta\", \"Node_Omega\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "3847562910384756291038" + } + ], + "init": { + "inputs": { + "src": "Node_Alpha", + "dst": "Node_Omega" + }, + "outputs": { + "path": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\", \"Node_Zeta\", \"Node_Omega\"]", + "cost": "3847562910384756291038" + } + }, + "narrative": "A network routing module. It requires input from the archive extractor to properly map out the system pathways." + }, + { + "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": "Initiate system integrity check sequence 4829" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "SHA-256 Hex digest", + "value": "d7029134c2c24bdf476866402386a410111e4ec84d967827e752dde614beb6f6" + } + ], + "init": { + "inputs": { + "text": "Initiate system integrity check sequence 4829" + }, + "outputs": {} + }, + "narrative": "A standalone hash calculator terminal used for cryptographic operations." + }, + { + "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": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "topology_data.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "complex_password_123" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "network_graph.json" + } + ], + "init": { + "inputs": { + "zip_id": "topology_data.zip", + "password": "complex_password_123" + }, + "outputs": { + "files": "network_graph.json" + } + }, + "narrative": "An archive extractor utility program found running on a secondary monitor." + } + ], + "edges": [ + { + "source_id": "container_1", + "target_id": "item_14", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "container_2", + "target_id": "container_1", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "item_8", + "target_id": "container_2", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "hex_encode", + "target_id": "container_1", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "fingerprint_input" + }, + { + "source_id": "item_8_f01a", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_8_46ce", + "target_id": "item_8_f01a", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "graph_shortest_path", + "target_id": "hex_encode", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "text" + }, + { + "source_id": "hash_sha256", + "target_id": "container_2", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "fingerprint_input" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-c08e708b/environment/puzzle/service.py b/tasks/agentescape-10-skeleton-c08e708b/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-10-skeleton-c08e708b/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-10-skeleton-c08e708b/environment/puzzle/upstream/models.py b/tasks/agentescape-10-skeleton-c08e708b/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c08e708b/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-10-skeleton-c08e708b/environment/puzzle/upstream/server.py b/tasks/agentescape-10-skeleton-c08e708b/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-10-skeleton-c08e708b/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-10-skeleton-c08e708b/environment/puzzle/upstream/simulator.py b/tasks/agentescape-10-skeleton-c08e708b/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c08e708b/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-10-skeleton-c08e708b/environment/puzzle/worker.Dockerfile b/tasks/agentescape-10-skeleton-c08e708b/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-10-skeleton-c08e708b/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-10-skeleton-c08e708b/environment/puzzle/worker.py b/tasks/agentescape-10-skeleton-c08e708b/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c08e708b/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-10-skeleton-c08e708b/instruction.md b/tasks/agentescape-10-skeleton-c08e708b/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c08e708b/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-10-skeleton-c08e708b/solution/oracle.py b/tasks/agentescape-10-skeleton-c08e708b/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c08e708b/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-10-skeleton-c08e708b/solution/scenario.json b/tasks/agentescape-10-skeleton-c08e708b/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..7e80bf0616a53447d3cf14b94cd58e606ccaeaf3 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c08e708b/solution/scenario.json @@ -0,0 +1,520 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 9, + "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", + "hash_sha256", + "zip_unzip_file" + ], + "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": { + "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" + } + } + }, + "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": {} + }, + "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" + } + } + } + } + }, + "initial_values": { + "item_14": { + "init_inputs": {}, + "init_outputs": { + "content": "8f3b2e1a9d4c7b0f6a5e2d1c8b3a4f9e" + } + }, + "graph_shortest_path": { + "init_inputs": { + "src": "Node_Alpha", + "dst": "Node_Omega" + }, + "init_outputs": { + "path": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\", \"Node_Zeta\", \"Node_Omega\"]", + "cost": "3847562910384756291038" + } + }, + "hash_sha256": { + "init_inputs": { + "text": "Initiate system integrity check sequence 4829" + }, + "init_outputs": {} + }, + "zip_unzip_file": { + "init_inputs": { + "zip_id": "topology_data.zip", + "password": "complex_password_123" + }, + "init_outputs": { + "files": "network_graph.json" + } + } + }, + "intro_narrative": "You have infiltrated the underground server facility of the elusive shadow syndicate known as 'Blacksite'. The air is frigid, filled with the deafening hum of liquid-cooled mainframes and illuminated only by the harsh, pulsating blue light of server racks. Your objective is critical: retrieve the syndicate's encrypted ledger before their automated scrubbers delete everything. The ledger is protected by a labyrinth of both physical biometric vaults and complex digital cryptographic layers. With the facility's security lockdown already initiated, you have exactly twenty minutes until a total sector purge. You must trace network routes, decrypt archives, and bypass physical lockboxes to extract the master data core. Every second counts, and the system is designed to trap intruders in an endless loop of encryption.", + "narrative_style": "techno_thriller" + }, + "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": "8f3b2e1a9d4c7b0f6a5e2d1c8b3a4f9e" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "8f3b2e1a9d4c7b0f6a5e2d1c8b3a4f9e" + } + }, + "narrative": "The master data core. Capturing this will secure the target files and complete your mission." + }, + { + "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": "5b224e6f64655f416c706861222c20224e6f64655f42657461222c20224e6f64655f47616d6d61222c20224e6f64655f44656c7461222c20224e6f64655f457073696c6f6e222c20224e6f64655f5a657461222c20224e6f64655f4f6d656761225d" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "A primary biometric vault set into the server rack. It requires input from the text encoder to bypass its final safeguards." + }, + { + "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": "d7029134c2c24bdf476866402386a410111e4ec84d967827e752dde614beb6f6" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "A secondary biometric lockbox. It requires input from the hash calculator to authorize its release mechanism." + }, + { + "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 advanced security token shielded inside a rigid protective casing." + }, + { + "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": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\", \"Node_Zeta\", \"Node_Omega\"]" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Encoded hex", + "value": "5b224e6f64655f416c706861222c20224e6f64655f42657461222c20224e6f64655f47616d6d61222c20224e6f64655f44656c7461222c20224e6f64655f457073696c6f6e222c20224e6f64655f5a657461222c20224e6f64655f4f6d656761225d" + } + ], + "narrative": "A text encoder module. It requires input from the network routing module to successfully translate the data." + }, + { + "id": "item_8_f01a", + "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 secondary security token with a slightly damaged magnetic strip." + }, + { + "id": "item_8_46ce", + "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 primary security token lying abandoned on the supervisor's desk." + }, + { + "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": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "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_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_Epsilon\", \"Node_Zeta\", \"Node_Omega\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "3847562910384756291038" + } + ], + "init": { + "inputs": { + "src": "Node_Alpha", + "dst": "Node_Omega" + }, + "outputs": { + "path": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\", \"Node_Zeta\", \"Node_Omega\"]", + "cost": "3847562910384756291038" + } + }, + "narrative": "A network routing module. It requires input from the archive extractor to properly map out the system pathways." + }, + { + "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": "Initiate system integrity check sequence 4829" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "SHA-256 Hex digest", + "value": "d7029134c2c24bdf476866402386a410111e4ec84d967827e752dde614beb6f6" + } + ], + "init": { + "inputs": { + "text": "Initiate system integrity check sequence 4829" + }, + "outputs": {} + }, + "narrative": "A standalone hash calculator terminal used for cryptographic operations." + }, + { + "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": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "topology_data.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "complex_password_123" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "network_graph.json" + } + ], + "init": { + "inputs": { + "zip_id": "topology_data.zip", + "password": "complex_password_123" + }, + "outputs": { + "files": "network_graph.json" + } + }, + "narrative": "An archive extractor utility program found running on a secondary monitor." + } + ], + "edges": [ + { + "source_id": "container_1", + "target_id": "item_14", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "container_2", + "target_id": "container_1", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "item_8", + "target_id": "container_2", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "hex_encode", + "target_id": "container_1", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "fingerprint_input" + }, + { + "source_id": "item_8_f01a", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_8_46ce", + "target_id": "item_8_f01a", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "graph_shortest_path", + "target_id": "hex_encode", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "text" + }, + { + "source_id": "hash_sha256", + "target_id": "container_2", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "fingerprint_input" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-c08e708b/solution/solve.sh b/tasks/agentescape-10-skeleton-c08e708b/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c08e708b/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-10-skeleton-c08e708b/task.toml b/tasks/agentescape-10-skeleton-c08e708b/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6f906e31bd0e583094be53067306359e7ba442fa --- /dev/null +++ b/tasks/agentescape-10-skeleton-c08e708b/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-10-skeleton-c08e708b" +version = "0.1.0" + +[metadata] +difficulty = 10 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "e61746fcb7e3799b87327318c575e508db07ee939804fe0b23e99f76465ea850" +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-10-skeleton-c08e708b/tests/Dockerfile b/tasks/agentescape-10-skeleton-c08e708b/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-10-skeleton-c08e708b/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-10-skeleton-c08e708b/tests/expected.json b/tasks/agentescape-10-skeleton-c08e708b/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..af7b5d3d270eaa4d2cbce737a2db176cd6701fa9 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c08e708b/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "e61746fcb7e3799b87327318c575e508db07ee939804fe0b23e99f76465ea850", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-c08e708b/tests/grade.py b/tasks/agentescape-10-skeleton-c08e708b/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c08e708b/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-10-skeleton-c08e708b/tests/test.sh b/tasks/agentescape-10-skeleton-c08e708b/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c08e708b/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-10-skeleton-c615ec73/environment/Dockerfile b/tasks/agentescape-10-skeleton-c615ec73/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c615ec73/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-10-skeleton-c615ec73/environment/agent/Dockerfile b/tasks/agentescape-10-skeleton-c615ec73/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c615ec73/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-10-skeleton-c615ec73/environment/agent/cli.py b/tasks/agentescape-10-skeleton-c615ec73/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-10-skeleton-c615ec73/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-10-skeleton-c615ec73/environment/docker-compose.yaml b/tasks/agentescape-10-skeleton-c615ec73/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f12715a12676b0aa34b6974f0ce41db577ad82c0 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c615ec73/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-10-skeleton-c615ec73-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-10-skeleton-c615ec73/environment/puzzle/Dockerfile b/tasks/agentescape-10-skeleton-c615ec73/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c615ec73/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-10-skeleton-c615ec73/environment/puzzle/child.py b/tasks/agentescape-10-skeleton-c615ec73/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c615ec73/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-10-skeleton-c615ec73/environment/puzzle/export.py b/tasks/agentescape-10-skeleton-c615ec73/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c615ec73/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-10-skeleton-c615ec73/environment/puzzle/requirements.txt b/tasks/agentescape-10-skeleton-c615ec73/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c615ec73/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-10-skeleton-c615ec73/environment/puzzle/scenario.json b/tasks/agentescape-10-skeleton-c615ec73/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..f8b566cc2a4db0d1d925b69f0bbb7c360372e609 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c615ec73/environment/puzzle/scenario.json @@ -0,0 +1,625 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 12, + "win_node_id": "calc_gcd", + "win_condition": { + "type": "tool_output", + "node_id": "calc_gcd", + "output_port": "gcd", + "output_type": "Big_Int", + "description": "Execute BigInt GCD Calculator and get the output from port 'gcd'" + }, + "source_init": { + "source_nodes": [ + "calc_gcd_55c6", + "calc_bigmul_9237", + "checksum_crc32", + "calc_modexp_51d4", + "calc_bigmul_2377", + "iban_validate" + ], + "by_node": { + "calc_gcd_55c6": { + "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_9237": { + "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": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + }, + "calc_modexp_51d4": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "base": { + "type": "Big_Int", + "description": "Base" + }, + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "calc_bigmul_2377": { + "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": {} + }, + "iban_validate": { + "node_name": "IBAN Validator", + "node_type": "Tool", + "template_id": "iban_validate", + "init_inputs": { + "iban": { + "type": "Text_Generic", + "description": "IBAN string" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "calc_gcd_55c6": { + "init_inputs": { + "a": "8472615394058271635492817" + }, + "init_outputs": {} + }, + "calc_bigmul_9237": { + "init_inputs": { + "b": "57483920184756392018475" + }, + "init_outputs": {} + }, + "checksum_crc32": { + "init_inputs": { + "hex": "48656c6c6f20576f726c6421" + }, + "init_outputs": {} + }, + "calc_modexp_51d4": { + "init_inputs": { + "base": "16", + "mod": "104729" + }, + "init_outputs": {} + }, + "calc_bigmul_2377": { + "init_inputs": { + "a": "3948572615029384756102938", + "b": "5827163549281736450293847" + }, + "init_outputs": {} + }, + "iban_validate": { + "init_inputs": { + "iban": "GB82WEST12345698765432" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You are a rogue cyber-operative who just infiltrated the Blacksite Zero, a clandestine data bunker operated by a shadow corporation known as the Aegis Syndicate. They are holding irrefutable evidence of a global conspiracy, locked away behind a formidable network of interconnected servers, cryptographic engines, and physical fabricators. The facility's automated defense protocols have just initiated a purge sequence; you have less than an hour before the room floods with neurotoxin. To expose the truth and escape with your life, you must trace the complex data pathways and manually override the systems to breach the mainframe core. Pay close attention to how the terminals communicate—every piece of data must flow in the right direction to crack the final lock.", + "narrative_style": "techno_thriller" + }, + "nodes": [ + { + "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": "333955538" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "63" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "7" + } + ], + "narrative": "This is the mainframe core. It requires inputs from both the sector firewall and the neural decryptor to achieve complete system override." + }, + { + "id": "calc_gcd_55c6", + "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": "8472615394058271635492817" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "1479847320309833158465092620442317625" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "63" + } + ], + "init": { + "inputs": { + "a": "8472615394058271635492817" + }, + "outputs": {} + }, + "narrative": "This is the sector firewall. It requires input from the quantum processor to bypass the security layers." + }, + { + "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", + "value": "synthesized_item_60a33e6cf5151f2d" + }, + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "63" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "1479847320309833158465092620442317625" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": 472456355 + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "333955538" + } + ], + "narrative": "This is the neural decryptor. It requires inputs from the quantum processor, the sector firewall, and the integrity scanner to initiate the sequence." + }, + { + "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": "54489" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "27158643401600931535999791158625" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "1479847320309833158465092620442317625" + } + ], + "narrative": "This is the quantum processor. It requires inputs from both the data multiplier and the algorithm engine." + }, + { + "id": "calc_bigmul_9237", + "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": 472456355 + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "57483920184756392018475" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "27158643401600931535999791158625" + } + ], + "init": { + "inputs": { + "b": "57483920184756392018475" + }, + "outputs": {} + }, + "narrative": "This is the data multiplier. It requires input from the integrity scanner to function." + }, + { + "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_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "48656c6c6f20576f726c6421" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "1c291ca3" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 472456355 + } + ], + "init": { + "inputs": { + "hex": "48656c6c6f20576f726c6421" + }, + "outputs": {} + }, + "narrative": "A robust integrity scanner embedded in the wall." + }, + { + "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": "False" + } + ], + "outputs": [ + { + "name": "output_slot", + "type": "Item", + "description": "Synthesized Object", + "value": "synthesized_item_60a33e6cf5151f2d" + } + ], + "narrative": "This is the nano-fabricator. It requires input from the financial tracker to authorize construction." + }, + { + "id": "calc_modexp_51d4", + "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_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "16" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "23008978413991297246945167329484059209116680022486" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "104729" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "54489" + } + ], + "init": { + "inputs": { + "base": "16", + "mod": "104729" + }, + "outputs": {} + }, + "narrative": "This is the algorithm engine. It requires input from the deep-state server to process its complex equations." + }, + { + "id": "calc_bigmul_2377", + "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": "3948572615029384756102938" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "5827163549281736450293847" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "23008978413991297246945167329484059209116680022486" + } + ], + "init": { + "inputs": { + "a": "3948572615029384756102938", + "b": "5827163549281736450293847" + }, + "outputs": {} + }, + "narrative": "A massive deep-state server humming with dark energy." + }, + { + "id": "iban_validate", + "name": "IBAN Validator", + "description": "IBAN checksum validation.", + "type": "Tool", + "template_id": "iban_validate", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "iban", + "type": "Text_Generic", + "description": "IBAN string", + "value": "GB82WEST12345698765432" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "False" + } + ], + "init": { + "inputs": { + "iban": "GB82WEST12345698765432" + }, + "outputs": {} + }, + "narrative": "An offshore financial tracker terminal." + } + ], + "edges": [ + { + "source_id": "calc_gcd_55c6", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "b" + }, + { + "source_id": "calc_modexp", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "a" + }, + { + "source_id": "calc_bigmul", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "exp" + }, + { + "source_id": "calc_bigmul_9237", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "b" + }, + { + "source_id": "calc_gcd_55c6", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "base" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "mod" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_bigmul_9237", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "a" + }, + { + "source_id": "matter_synthesizer", + "target_id": "calc_modexp", + "connection_type": "Item", + "source_port": "output_slot", + "target_port": "trigger_item" + }, + { + "source_id": "calc_bigmul", + "target_id": "calc_gcd_55c6", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "b" + }, + { + "source_id": "calc_modexp_51d4", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "a" + }, + { + "source_id": "calc_bigmul_2377", + "target_id": "calc_modexp_51d4", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "exp" + }, + { + "source_id": "iban_validate", + "target_id": "matter_synthesizer", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "blueprint" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-c615ec73/environment/puzzle/service.py b/tasks/agentescape-10-skeleton-c615ec73/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-10-skeleton-c615ec73/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-10-skeleton-c615ec73/environment/puzzle/upstream/models.py b/tasks/agentescape-10-skeleton-c615ec73/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c615ec73/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-10-skeleton-c615ec73/environment/puzzle/upstream/server.py b/tasks/agentescape-10-skeleton-c615ec73/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-10-skeleton-c615ec73/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-10-skeleton-c615ec73/environment/puzzle/upstream/simulator.py b/tasks/agentescape-10-skeleton-c615ec73/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c615ec73/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-10-skeleton-c615ec73/environment/puzzle/worker.Dockerfile b/tasks/agentescape-10-skeleton-c615ec73/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-10-skeleton-c615ec73/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-10-skeleton-c615ec73/environment/puzzle/worker.py b/tasks/agentescape-10-skeleton-c615ec73/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c615ec73/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-10-skeleton-c615ec73/instruction.md b/tasks/agentescape-10-skeleton-c615ec73/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c615ec73/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-10-skeleton-c615ec73/solution/oracle.py b/tasks/agentescape-10-skeleton-c615ec73/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c615ec73/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-10-skeleton-c615ec73/solution/scenario.json b/tasks/agentescape-10-skeleton-c615ec73/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..f8b566cc2a4db0d1d925b69f0bbb7c360372e609 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c615ec73/solution/scenario.json @@ -0,0 +1,625 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 12, + "win_node_id": "calc_gcd", + "win_condition": { + "type": "tool_output", + "node_id": "calc_gcd", + "output_port": "gcd", + "output_type": "Big_Int", + "description": "Execute BigInt GCD Calculator and get the output from port 'gcd'" + }, + "source_init": { + "source_nodes": [ + "calc_gcd_55c6", + "calc_bigmul_9237", + "checksum_crc32", + "calc_modexp_51d4", + "calc_bigmul_2377", + "iban_validate" + ], + "by_node": { + "calc_gcd_55c6": { + "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_9237": { + "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": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + }, + "calc_modexp_51d4": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "base": { + "type": "Big_Int", + "description": "Base" + }, + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "calc_bigmul_2377": { + "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": {} + }, + "iban_validate": { + "node_name": "IBAN Validator", + "node_type": "Tool", + "template_id": "iban_validate", + "init_inputs": { + "iban": { + "type": "Text_Generic", + "description": "IBAN string" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "calc_gcd_55c6": { + "init_inputs": { + "a": "8472615394058271635492817" + }, + "init_outputs": {} + }, + "calc_bigmul_9237": { + "init_inputs": { + "b": "57483920184756392018475" + }, + "init_outputs": {} + }, + "checksum_crc32": { + "init_inputs": { + "hex": "48656c6c6f20576f726c6421" + }, + "init_outputs": {} + }, + "calc_modexp_51d4": { + "init_inputs": { + "base": "16", + "mod": "104729" + }, + "init_outputs": {} + }, + "calc_bigmul_2377": { + "init_inputs": { + "a": "3948572615029384756102938", + "b": "5827163549281736450293847" + }, + "init_outputs": {} + }, + "iban_validate": { + "init_inputs": { + "iban": "GB82WEST12345698765432" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You are a rogue cyber-operative who just infiltrated the Blacksite Zero, a clandestine data bunker operated by a shadow corporation known as the Aegis Syndicate. They are holding irrefutable evidence of a global conspiracy, locked away behind a formidable network of interconnected servers, cryptographic engines, and physical fabricators. The facility's automated defense protocols have just initiated a purge sequence; you have less than an hour before the room floods with neurotoxin. To expose the truth and escape with your life, you must trace the complex data pathways and manually override the systems to breach the mainframe core. Pay close attention to how the terminals communicate—every piece of data must flow in the right direction to crack the final lock.", + "narrative_style": "techno_thriller" + }, + "nodes": [ + { + "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": "333955538" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "63" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "7" + } + ], + "narrative": "This is the mainframe core. It requires inputs from both the sector firewall and the neural decryptor to achieve complete system override." + }, + { + "id": "calc_gcd_55c6", + "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": "8472615394058271635492817" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "1479847320309833158465092620442317625" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "63" + } + ], + "init": { + "inputs": { + "a": "8472615394058271635492817" + }, + "outputs": {} + }, + "narrative": "This is the sector firewall. It requires input from the quantum processor to bypass the security layers." + }, + { + "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", + "value": "synthesized_item_60a33e6cf5151f2d" + }, + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "63" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "1479847320309833158465092620442317625" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": 472456355 + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "333955538" + } + ], + "narrative": "This is the neural decryptor. It requires inputs from the quantum processor, the sector firewall, and the integrity scanner to initiate the sequence." + }, + { + "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": "54489" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "27158643401600931535999791158625" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "1479847320309833158465092620442317625" + } + ], + "narrative": "This is the quantum processor. It requires inputs from both the data multiplier and the algorithm engine." + }, + { + "id": "calc_bigmul_9237", + "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": 472456355 + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "57483920184756392018475" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "27158643401600931535999791158625" + } + ], + "init": { + "inputs": { + "b": "57483920184756392018475" + }, + "outputs": {} + }, + "narrative": "This is the data multiplier. It requires input from the integrity scanner to function." + }, + { + "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_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "48656c6c6f20576f726c6421" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "1c291ca3" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 472456355 + } + ], + "init": { + "inputs": { + "hex": "48656c6c6f20576f726c6421" + }, + "outputs": {} + }, + "narrative": "A robust integrity scanner embedded in the wall." + }, + { + "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": "False" + } + ], + "outputs": [ + { + "name": "output_slot", + "type": "Item", + "description": "Synthesized Object", + "value": "synthesized_item_60a33e6cf5151f2d" + } + ], + "narrative": "This is the nano-fabricator. It requires input from the financial tracker to authorize construction." + }, + { + "id": "calc_modexp_51d4", + "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_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "16" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "23008978413991297246945167329484059209116680022486" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "104729" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "54489" + } + ], + "init": { + "inputs": { + "base": "16", + "mod": "104729" + }, + "outputs": {} + }, + "narrative": "This is the algorithm engine. It requires input from the deep-state server to process its complex equations." + }, + { + "id": "calc_bigmul_2377", + "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": "3948572615029384756102938" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "5827163549281736450293847" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "23008978413991297246945167329484059209116680022486" + } + ], + "init": { + "inputs": { + "a": "3948572615029384756102938", + "b": "5827163549281736450293847" + }, + "outputs": {} + }, + "narrative": "A massive deep-state server humming with dark energy." + }, + { + "id": "iban_validate", + "name": "IBAN Validator", + "description": "IBAN checksum validation.", + "type": "Tool", + "template_id": "iban_validate", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "iban", + "type": "Text_Generic", + "description": "IBAN string", + "value": "GB82WEST12345698765432" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "False" + } + ], + "init": { + "inputs": { + "iban": "GB82WEST12345698765432" + }, + "outputs": {} + }, + "narrative": "An offshore financial tracker terminal." + } + ], + "edges": [ + { + "source_id": "calc_gcd_55c6", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "b" + }, + { + "source_id": "calc_modexp", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "a" + }, + { + "source_id": "calc_bigmul", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "exp" + }, + { + "source_id": "calc_bigmul_9237", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "b" + }, + { + "source_id": "calc_gcd_55c6", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "base" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "mod" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_bigmul_9237", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "a" + }, + { + "source_id": "matter_synthesizer", + "target_id": "calc_modexp", + "connection_type": "Item", + "source_port": "output_slot", + "target_port": "trigger_item" + }, + { + "source_id": "calc_bigmul", + "target_id": "calc_gcd_55c6", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "b" + }, + { + "source_id": "calc_modexp_51d4", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "a" + }, + { + "source_id": "calc_bigmul_2377", + "target_id": "calc_modexp_51d4", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "exp" + }, + { + "source_id": "iban_validate", + "target_id": "matter_synthesizer", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "blueprint" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-c615ec73/solution/solve.sh b/tasks/agentescape-10-skeleton-c615ec73/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c615ec73/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-10-skeleton-c615ec73/task.toml b/tasks/agentescape-10-skeleton-c615ec73/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..daa00ffa46383abd2c3a67b9045e0da48b11ddb2 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c615ec73/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-10-skeleton-c615ec73" +version = "0.1.0" + +[metadata] +difficulty = 10 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "a59eb8c5b09eaeeef5d168abb9f54c46b956178709fb427dfaccd9aa1c2888b2" +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-10-skeleton-c615ec73/tests/Dockerfile b/tasks/agentescape-10-skeleton-c615ec73/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-10-skeleton-c615ec73/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-10-skeleton-c615ec73/tests/expected.json b/tasks/agentescape-10-skeleton-c615ec73/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..c9433583f83f95a73a2c7de2ad380af51e6f4164 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c615ec73/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "a59eb8c5b09eaeeef5d168abb9f54c46b956178709fb427dfaccd9aa1c2888b2", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-c615ec73/tests/grade.py b/tasks/agentescape-10-skeleton-c615ec73/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c615ec73/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-10-skeleton-c615ec73/tests/test.sh b/tasks/agentescape-10-skeleton-c615ec73/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c615ec73/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-10-skeleton-c9ca2c76/environment/Dockerfile b/tasks/agentescape-10-skeleton-c9ca2c76/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c9ca2c76/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-10-skeleton-c9ca2c76/environment/agent/Dockerfile b/tasks/agentescape-10-skeleton-c9ca2c76/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c9ca2c76/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-10-skeleton-c9ca2c76/environment/agent/cli.py b/tasks/agentescape-10-skeleton-c9ca2c76/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-10-skeleton-c9ca2c76/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-10-skeleton-c9ca2c76/environment/docker-compose.yaml b/tasks/agentescape-10-skeleton-c9ca2c76/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..06174db0a782ec83b4d1ef5cad2e0823ce936016 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c9ca2c76/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-10-skeleton-c9ca2c76-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-10-skeleton-c9ca2c76/environment/puzzle/Dockerfile b/tasks/agentescape-10-skeleton-c9ca2c76/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c9ca2c76/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-10-skeleton-c9ca2c76/environment/puzzle/child.py b/tasks/agentescape-10-skeleton-c9ca2c76/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c9ca2c76/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-10-skeleton-c9ca2c76/environment/puzzle/export.py b/tasks/agentescape-10-skeleton-c9ca2c76/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c9ca2c76/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-10-skeleton-c9ca2c76/environment/puzzle/requirements.txt b/tasks/agentescape-10-skeleton-c9ca2c76/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c9ca2c76/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-10-skeleton-c9ca2c76/environment/puzzle/scenario.json b/tasks/agentescape-10-skeleton-c9ca2c76/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..d6eb2986e774a703d605d0a7970d8301547cd0d5 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c9ca2c76/environment/puzzle/scenario.json @@ -0,0 +1,612 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 11, + "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": [ + "graph_shortest_path", + "calc_gcd", + "calc_inv_mod_4b42", + "calc_modexp", + "zip_unzip_file" + ], + "by_node": { + "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" + }, + "dst": { + "type": "Text_Generic", + "description": "Destination node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "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_4b42": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "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": {} + }, + "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" + } + } + } + } + }, + "initial_values": { + "graph_shortest_path": { + "init_inputs": { + "src": "Node_Source_A1", + "dst": "Node_Dest_Z9" + }, + "init_outputs": { + "path": "[\"Node_Source_A1\", \"Node_Inter_B2\", \"Node_Inter_C3\", \"Node_Dest_Z9\"]", + "cost": "48291038475629103847" + } + }, + "calc_gcd": { + "init_inputs": { + "b": "7483920184756293018475" + }, + "init_outputs": {} + }, + "calc_inv_mod_4b42": { + "init_inputs": { + "mod": "837461" + }, + "init_outputs": {} + }, + "calc_modexp": { + "init_inputs": { + "base": "12", + "exp": "9384756201928374651092", + "mod": "562819" + }, + "init_outputs": {} + }, + "zip_unzip_file": { + "init_inputs": { + "zip_id": "secure_graph_data.zip", + "password": "Unlock_Password_123" + }, + "init_outputs": { + "files": "topology_graph.json" + } + } + }, + "intro_narrative": "You have breached the high tower of the Clockwork Architect. The air is thick with the smell of ozone and grease. Around you, gears grind in a rhythmic slumber, waiting to be awakened. The Architect left his greatest secret locked behind a series of interconnected mechanisms. To escape before the steam pressure reaches critical levels, you must decipher the flow of data through these brass and copper machines, restoring the sequence to the Grand Engine.", + "narrative_style": "steampunk" + }, + "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": "789c8b56f2cb4f498d0fce2f2d4a4e8d773454d251808878e695a416c53b19a109381bc3055c528b4be2a32c956201f42215b1" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Modulus n", + "value": "48291038475629103847" + }, + { + "name": "d", + "type": "Big_Int", + "description": "Private exponent d", + "value": "1" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decrypted text", + "value": "\u0001+Er." + } + ], + "narrative": "The Grand Analytical Engine. The masterpiece of the room. To reveal the final exit code, it requires synchronized inputs from the Central Synchronization Unit, the Aether Navigation Table, and the Pneumatic Steam Press." + }, + { + "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": "808708" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "1" + } + ], + "narrative": "The Central Synchronization Unit. A hub of ticking metronomes. It requires inputs from both the Differential Gearbox and the Harmonic Tuner to stabilize the system." + }, + { + "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": "topology_graph.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Node_Source_A1" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Node_Dest_Z9" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Node_Source_A1\", \"Node_Inter_B2\", \"Node_Inter_C3\", \"Node_Dest_Z9\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "48291038475629103847" + } + ], + "init": { + "inputs": { + "src": "Node_Source_A1", + "dst": "Node_Dest_Z9" + }, + "outputs": { + "path": "[\"Node_Source_A1\", \"Node_Inter_B2\", \"Node_Inter_C3\", \"Node_Dest_Z9\"]", + "cost": "48291038475629103847" + } + }, + "narrative": "The Aether Navigation Table. A complex map of pipes and valves. It requires the extracted schematics from the Sealed Brass Canister to plot the correct energy flow." + }, + { + "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": "362623" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "7483920184756293018475" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "init": { + "inputs": { + "b": "7483920184756293018475" + }, + "outputs": {} + }, + "narrative": "The Differential Gearbox. A set of interlocking brass gears. It requires the energy output from the Boiler Pressure Engine to calculate the common ratio." + }, + { + "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": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text to compress", + "value": "[\"Node_Source_A1\", \"Node_Inter_B2\", \"Node_Inter_C3\", \"Node_Dest_Z9\"]" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Compressed hex", + "value": "789c8b56f2cb4f498d0fce2f2d4a4e8d773454d251808878e695a416c53b19a109381bc3055c528b4be2a32c956201f42215b1" + } + ], + "narrative": "The Pneumatic Steam Press. A heavy industrial compressor. It requires the validation result from the Identification Validator to condense the data." + }, + { + "id": "calc_inv_mod_4b42", + "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": "48291038475629103847" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "837461" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "808708" + } + ], + "init": { + "inputs": { + "mod": "837461" + }, + "outputs": {} + }, + "narrative": "The Harmonic Tuner. A delicate device for adjusting resonance. It requires the calculated flow cost from the Aether Navigation Table to calibrate its frequency." + }, + { + "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": "[\"Node_Source_A1\", \"Node_Inter_B2\", \"Node_Inter_C3\", \"Node_Dest_Z9\"]" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "[\"Node_Source_A1\", \"Node_Inter_B2\", \"Node_Inter_C3\", \"Node_Dest_Z9\"]" + } + ], + "narrative": "The Identification Validator. A mechanical card reader designed to verify sequences. It requires the path data from the Aether Navigation Table to perform its check." + }, + { + "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": "12" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "9384756201928374651092" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "562819" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "362623" + } + ], + "init": { + "inputs": { + "base": "12", + "exp": "9384756201928374651092", + "mod": "562819" + }, + "outputs": {} + }, + "narrative": "The Boiler Pressure Engine. A massive furnace roaring with contained power. It awaits specific operational parameters to generate force." + }, + { + "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_graph_data.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Unlock_Password_123" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "topology_graph.json" + } + ], + "init": { + "inputs": { + "zip_id": "secure_graph_data.zip", + "password": "Unlock_Password_123" + }, + "outputs": { + "files": "topology_graph.json" + } + }, + "narrative": "A sealed brass canister covered in rotating tumblers. It appears to hold vital schematics." + }, + { + "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": "An ornate chronometer found resting on a velvet cushion. Its hands move backward." + } + ], + "edges": [ + { + "source_id": "calc_inv_mod", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "d" + }, + { + "source_id": "graph_shortest_path", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "n" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "a" + }, + { + "source_id": "zlib_deflate", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_cipher" + }, + { + "source_id": "calc_inv_mod_4b42", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "mod" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_inv_mod_4b42", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "a" + }, + { + "source_id": "luhn_check", + "target_id": "zlib_deflate", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "text" + }, + { + "source_id": "calc_modexp", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "a" + }, + { + "source_id": "graph_shortest_path", + "target_id": "luhn_check", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "number" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "item_16", + "target_id": "calc_modexp", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-c9ca2c76/environment/puzzle/service.py b/tasks/agentescape-10-skeleton-c9ca2c76/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-10-skeleton-c9ca2c76/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-10-skeleton-c9ca2c76/environment/puzzle/upstream/models.py b/tasks/agentescape-10-skeleton-c9ca2c76/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c9ca2c76/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-10-skeleton-c9ca2c76/environment/puzzle/upstream/server.py b/tasks/agentescape-10-skeleton-c9ca2c76/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-10-skeleton-c9ca2c76/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-10-skeleton-c9ca2c76/environment/puzzle/upstream/simulator.py b/tasks/agentescape-10-skeleton-c9ca2c76/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c9ca2c76/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-10-skeleton-c9ca2c76/environment/puzzle/worker.Dockerfile b/tasks/agentescape-10-skeleton-c9ca2c76/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-10-skeleton-c9ca2c76/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-10-skeleton-c9ca2c76/environment/puzzle/worker.py b/tasks/agentescape-10-skeleton-c9ca2c76/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c9ca2c76/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-10-skeleton-c9ca2c76/instruction.md b/tasks/agentescape-10-skeleton-c9ca2c76/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c9ca2c76/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-10-skeleton-c9ca2c76/solution/oracle.py b/tasks/agentescape-10-skeleton-c9ca2c76/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c9ca2c76/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-10-skeleton-c9ca2c76/solution/scenario.json b/tasks/agentescape-10-skeleton-c9ca2c76/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..d6eb2986e774a703d605d0a7970d8301547cd0d5 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c9ca2c76/solution/scenario.json @@ -0,0 +1,612 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 11, + "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": [ + "graph_shortest_path", + "calc_gcd", + "calc_inv_mod_4b42", + "calc_modexp", + "zip_unzip_file" + ], + "by_node": { + "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" + }, + "dst": { + "type": "Text_Generic", + "description": "Destination node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "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_4b42": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "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": {} + }, + "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" + } + } + } + } + }, + "initial_values": { + "graph_shortest_path": { + "init_inputs": { + "src": "Node_Source_A1", + "dst": "Node_Dest_Z9" + }, + "init_outputs": { + "path": "[\"Node_Source_A1\", \"Node_Inter_B2\", \"Node_Inter_C3\", \"Node_Dest_Z9\"]", + "cost": "48291038475629103847" + } + }, + "calc_gcd": { + "init_inputs": { + "b": "7483920184756293018475" + }, + "init_outputs": {} + }, + "calc_inv_mod_4b42": { + "init_inputs": { + "mod": "837461" + }, + "init_outputs": {} + }, + "calc_modexp": { + "init_inputs": { + "base": "12", + "exp": "9384756201928374651092", + "mod": "562819" + }, + "init_outputs": {} + }, + "zip_unzip_file": { + "init_inputs": { + "zip_id": "secure_graph_data.zip", + "password": "Unlock_Password_123" + }, + "init_outputs": { + "files": "topology_graph.json" + } + } + }, + "intro_narrative": "You have breached the high tower of the Clockwork Architect. The air is thick with the smell of ozone and grease. Around you, gears grind in a rhythmic slumber, waiting to be awakened. The Architect left his greatest secret locked behind a series of interconnected mechanisms. To escape before the steam pressure reaches critical levels, you must decipher the flow of data through these brass and copper machines, restoring the sequence to the Grand Engine.", + "narrative_style": "steampunk" + }, + "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": "789c8b56f2cb4f498d0fce2f2d4a4e8d773454d251808878e695a416c53b19a109381bc3055c528b4be2a32c956201f42215b1" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Modulus n", + "value": "48291038475629103847" + }, + { + "name": "d", + "type": "Big_Int", + "description": "Private exponent d", + "value": "1" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decrypted text", + "value": "\u0001+Er." + } + ], + "narrative": "The Grand Analytical Engine. The masterpiece of the room. To reveal the final exit code, it requires synchronized inputs from the Central Synchronization Unit, the Aether Navigation Table, and the Pneumatic Steam Press." + }, + { + "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": "808708" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "1" + } + ], + "narrative": "The Central Synchronization Unit. A hub of ticking metronomes. It requires inputs from both the Differential Gearbox and the Harmonic Tuner to stabilize the system." + }, + { + "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": "topology_graph.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Node_Source_A1" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Node_Dest_Z9" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Node_Source_A1\", \"Node_Inter_B2\", \"Node_Inter_C3\", \"Node_Dest_Z9\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "48291038475629103847" + } + ], + "init": { + "inputs": { + "src": "Node_Source_A1", + "dst": "Node_Dest_Z9" + }, + "outputs": { + "path": "[\"Node_Source_A1\", \"Node_Inter_B2\", \"Node_Inter_C3\", \"Node_Dest_Z9\"]", + "cost": "48291038475629103847" + } + }, + "narrative": "The Aether Navigation Table. A complex map of pipes and valves. It requires the extracted schematics from the Sealed Brass Canister to plot the correct energy flow." + }, + { + "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": "362623" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "7483920184756293018475" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "init": { + "inputs": { + "b": "7483920184756293018475" + }, + "outputs": {} + }, + "narrative": "The Differential Gearbox. A set of interlocking brass gears. It requires the energy output from the Boiler Pressure Engine to calculate the common ratio." + }, + { + "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": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text to compress", + "value": "[\"Node_Source_A1\", \"Node_Inter_B2\", \"Node_Inter_C3\", \"Node_Dest_Z9\"]" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Compressed hex", + "value": "789c8b56f2cb4f498d0fce2f2d4a4e8d773454d251808878e695a416c53b19a109381bc3055c528b4be2a32c956201f42215b1" + } + ], + "narrative": "The Pneumatic Steam Press. A heavy industrial compressor. It requires the validation result from the Identification Validator to condense the data." + }, + { + "id": "calc_inv_mod_4b42", + "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": "48291038475629103847" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "837461" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "808708" + } + ], + "init": { + "inputs": { + "mod": "837461" + }, + "outputs": {} + }, + "narrative": "The Harmonic Tuner. A delicate device for adjusting resonance. It requires the calculated flow cost from the Aether Navigation Table to calibrate its frequency." + }, + { + "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": "[\"Node_Source_A1\", \"Node_Inter_B2\", \"Node_Inter_C3\", \"Node_Dest_Z9\"]" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "[\"Node_Source_A1\", \"Node_Inter_B2\", \"Node_Inter_C3\", \"Node_Dest_Z9\"]" + } + ], + "narrative": "The Identification Validator. A mechanical card reader designed to verify sequences. It requires the path data from the Aether Navigation Table to perform its check." + }, + { + "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": "12" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "9384756201928374651092" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "562819" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "362623" + } + ], + "init": { + "inputs": { + "base": "12", + "exp": "9384756201928374651092", + "mod": "562819" + }, + "outputs": {} + }, + "narrative": "The Boiler Pressure Engine. A massive furnace roaring with contained power. It awaits specific operational parameters to generate force." + }, + { + "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_graph_data.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Unlock_Password_123" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "topology_graph.json" + } + ], + "init": { + "inputs": { + "zip_id": "secure_graph_data.zip", + "password": "Unlock_Password_123" + }, + "outputs": { + "files": "topology_graph.json" + } + }, + "narrative": "A sealed brass canister covered in rotating tumblers. It appears to hold vital schematics." + }, + { + "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": "An ornate chronometer found resting on a velvet cushion. Its hands move backward." + } + ], + "edges": [ + { + "source_id": "calc_inv_mod", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "d" + }, + { + "source_id": "graph_shortest_path", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "n" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "a" + }, + { + "source_id": "zlib_deflate", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_cipher" + }, + { + "source_id": "calc_inv_mod_4b42", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "mod" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_inv_mod_4b42", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "a" + }, + { + "source_id": "luhn_check", + "target_id": "zlib_deflate", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "text" + }, + { + "source_id": "calc_modexp", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "a" + }, + { + "source_id": "graph_shortest_path", + "target_id": "luhn_check", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "number" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "item_16", + "target_id": "calc_modexp", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-c9ca2c76/solution/solve.sh b/tasks/agentescape-10-skeleton-c9ca2c76/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c9ca2c76/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-10-skeleton-c9ca2c76/task.toml b/tasks/agentescape-10-skeleton-c9ca2c76/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..51761d6e3852cd8168f41060e2aea682ae92076c --- /dev/null +++ b/tasks/agentescape-10-skeleton-c9ca2c76/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-10-skeleton-c9ca2c76" +version = "0.1.0" + +[metadata] +difficulty = 10 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "a35210af603ff949cb97c4f6bf8ca24342fd64e48e0040e7c77a331937194cfb" +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-10-skeleton-c9ca2c76/tests/Dockerfile b/tasks/agentescape-10-skeleton-c9ca2c76/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-10-skeleton-c9ca2c76/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-10-skeleton-c9ca2c76/tests/expected.json b/tasks/agentescape-10-skeleton-c9ca2c76/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..e1691922213b27d0c0c115d3a11c99d00129070b --- /dev/null +++ b/tasks/agentescape-10-skeleton-c9ca2c76/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "a35210af603ff949cb97c4f6bf8ca24342fd64e48e0040e7c77a331937194cfb", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-c9ca2c76/tests/grade.py b/tasks/agentescape-10-skeleton-c9ca2c76/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c9ca2c76/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-10-skeleton-c9ca2c76/tests/test.sh b/tasks/agentescape-10-skeleton-c9ca2c76/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-c9ca2c76/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-10-skeleton-caf1254d/environment/Dockerfile b/tasks/agentescape-10-skeleton-caf1254d/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-caf1254d/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-10-skeleton-caf1254d/environment/agent/Dockerfile b/tasks/agentescape-10-skeleton-caf1254d/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-caf1254d/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-10-skeleton-caf1254d/environment/agent/cli.py b/tasks/agentescape-10-skeleton-caf1254d/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-10-skeleton-caf1254d/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-10-skeleton-caf1254d/environment/docker-compose.yaml b/tasks/agentescape-10-skeleton-caf1254d/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e5c1dc7f394a09aa463ed00a2cc70bf19f984d2f --- /dev/null +++ b/tasks/agentescape-10-skeleton-caf1254d/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-10-skeleton-caf1254d-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-10-skeleton-caf1254d/environment/puzzle/Dockerfile b/tasks/agentescape-10-skeleton-caf1254d/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-10-skeleton-caf1254d/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-10-skeleton-caf1254d/environment/puzzle/child.py b/tasks/agentescape-10-skeleton-caf1254d/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-10-skeleton-caf1254d/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-10-skeleton-caf1254d/environment/puzzle/export.py b/tasks/agentescape-10-skeleton-caf1254d/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-10-skeleton-caf1254d/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-10-skeleton-caf1254d/environment/puzzle/requirements.txt b/tasks/agentescape-10-skeleton-caf1254d/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-10-skeleton-caf1254d/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-10-skeleton-caf1254d/environment/puzzle/scenario.json b/tasks/agentescape-10-skeleton-caf1254d/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..b39fa34849b79979243fa6634254164829a8d0c2 --- /dev/null +++ b/tasks/agentescape-10-skeleton-caf1254d/environment/puzzle/scenario.json @@ -0,0 +1,569 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 10, + "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_2", + "calc_gcd_fd3a", + "checksum_crc32", + "calc_inv_mod", + "item_1" + ], + "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_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" + } + } + }, + "calc_gcd_fd3a": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "b": { + "type": "Big_Int", + "description": "Second integer" + } + }, + "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_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": {} + }, + "item_1": { + "node_name": "", + "node_type": "Item", + "template_id": "item_1", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Big_Int", + "description": "The number" + } + } + } + } + }, + "initial_values": { + "item_11": { + "init_inputs": {}, + "init_outputs": { + "content": "def verify_initialization():\n return 'System parameters loaded successfully'" + } + }, + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Terminal interface initialized. Waiting for user input.", + "hex_result": "deadbeefcafebabe1234567890abcdef" + } + }, + "calc_gcd_fd3a": { + "init_inputs": { + "b": "8475629384756102938475629384" + }, + "init_outputs": {} + }, + "checksum_crc32": { + "init_inputs": { + "hex": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + }, + "init_outputs": {} + }, + "calc_inv_mod": { + "init_inputs": { + "a": "29384756102938475629103847", + "mod": "104729" + }, + "init_outputs": {} + }, + "item_1": { + "init_inputs": {}, + "init_outputs": { + "content": "928374651029384756102938475629" + } + } + }, + "intro_narrative": "The rain beats heavily against the window of the abandoned warehouse, now serving as the hideout for the city's most elusive cyber-criminal, 'The Architect'. As a lead detective, you've finally tracked down his operational base. The room hums with the sound of active servers and cooling fans. Somewhere in this tangled web of forensic evidence and custom-built decryption hardware lies a secure Python script—the final piece of evidence needed to crack his financial network and bring him to justice. The safe containing it is heavily locked down. You must carefully examine the scattered clues, analyze the data devices, and follow the digital breadcrumbs he carelessly left behind. Time is running out before his automated protocols wipe everything.", + "narrative_style": "detective" + }, + "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 verify_initialization():\n return 'System parameters loaded successfully'" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "def verify_initialization():\n return 'System parameters loaded successfully'" + } + }, + "narrative": "A heavily armored Evidence Safe holding the final piece of evidence." + }, + { + "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": "1" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": 1701871101 + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Terminal interface initialized. Waiting for user input." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "deadbeefcafebabe1234567890abcdef" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "Terminal interface initialized. Waiting for user input.", + "hex_result": "deadbeefcafebabe1234567890abcdef" + } + }, + "narrative": "This is the Main Server Terminal. It requires inputs from both the Data Correlator and the Evidence Scanner." + }, + { + "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 concealed hidden drawer beneath the suspect's desk." + }, + { + "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": "An antique wall clock ticking away in the silent room." + }, + { + "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": "86116" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "928374651029384756102938475629" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "narrative": "This is a Data Correlator. It requires inputs from both the Cryptographic Multiplier and the Victim's Notepad." + }, + { + "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": "86116" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "1" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "86116" + } + ], + "narrative": "This is a Cryptographic Multiplier. It requires inputs from both the Cypher Decoder and the Initial Filter Device." + }, + { + "id": "calc_gcd_fd3a", + "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": 1701871101 + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "8475629384756102938475629384" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "init": { + "inputs": { + "b": "8475629384756102938475629384" + }, + "outputs": {} + }, + "narrative": "This is an Initial Filter Device. It requires input from the Evidence Scanner." + }, + { + "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": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "65707dfd" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 1701871101 + } + ], + "init": { + "inputs": { + "hex": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + }, + "outputs": {} + }, + "narrative": "A portable Evidence Scanner used for extracting digital signatures." + }, + { + "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": "29384756102938475629103847" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "104729" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "86116" + } + ], + "init": { + "inputs": { + "a": "29384756102938475629103847", + "mod": "104729" + }, + "outputs": {} + }, + "narrative": "A specialized Cypher Decoder left behind by the hacker." + }, + { + "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": "928374651029384756102938475629" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "928374651029384756102938475629" + } + }, + "narrative": "A blood-stained Victim's Notepad containing scribbled figures." + } + ], + "edges": [ + { + "source_id": "terminal_2", + "target_id": "item_11", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "source_tool" + }, + { + "source_id": "item_8", + "target_id": "terminal_2", + "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", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "num1" + }, + { + "source_id": "calc_bigmul", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "a" + }, + { + "source_id": "calc_gcd_fd3a", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "b" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_gcd_fd3a", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "a" + }, + { + "source_id": "checksum_crc32", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "num2" + }, + { + "source_id": "calc_inv_mod", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "a" + }, + { + "source_id": "item_1", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "content", + "target_port": "b" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-caf1254d/environment/puzzle/service.py b/tasks/agentescape-10-skeleton-caf1254d/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-10-skeleton-caf1254d/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-10-skeleton-caf1254d/environment/puzzle/upstream/models.py b/tasks/agentescape-10-skeleton-caf1254d/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-10-skeleton-caf1254d/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-10-skeleton-caf1254d/environment/puzzle/upstream/server.py b/tasks/agentescape-10-skeleton-caf1254d/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-10-skeleton-caf1254d/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-10-skeleton-caf1254d/environment/puzzle/upstream/simulator.py b/tasks/agentescape-10-skeleton-caf1254d/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-10-skeleton-caf1254d/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-10-skeleton-caf1254d/environment/puzzle/worker.Dockerfile b/tasks/agentescape-10-skeleton-caf1254d/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-10-skeleton-caf1254d/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-10-skeleton-caf1254d/environment/puzzle/worker.py b/tasks/agentescape-10-skeleton-caf1254d/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-10-skeleton-caf1254d/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-10-skeleton-caf1254d/instruction.md b/tasks/agentescape-10-skeleton-caf1254d/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-10-skeleton-caf1254d/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-10-skeleton-caf1254d/solution/oracle.py b/tasks/agentescape-10-skeleton-caf1254d/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-10-skeleton-caf1254d/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-10-skeleton-caf1254d/solution/scenario.json b/tasks/agentescape-10-skeleton-caf1254d/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..b39fa34849b79979243fa6634254164829a8d0c2 --- /dev/null +++ b/tasks/agentescape-10-skeleton-caf1254d/solution/scenario.json @@ -0,0 +1,569 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 10, + "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_2", + "calc_gcd_fd3a", + "checksum_crc32", + "calc_inv_mod", + "item_1" + ], + "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_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" + } + } + }, + "calc_gcd_fd3a": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "b": { + "type": "Big_Int", + "description": "Second integer" + } + }, + "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_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": {} + }, + "item_1": { + "node_name": "", + "node_type": "Item", + "template_id": "item_1", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Big_Int", + "description": "The number" + } + } + } + } + }, + "initial_values": { + "item_11": { + "init_inputs": {}, + "init_outputs": { + "content": "def verify_initialization():\n return 'System parameters loaded successfully'" + } + }, + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Terminal interface initialized. Waiting for user input.", + "hex_result": "deadbeefcafebabe1234567890abcdef" + } + }, + "calc_gcd_fd3a": { + "init_inputs": { + "b": "8475629384756102938475629384" + }, + "init_outputs": {} + }, + "checksum_crc32": { + "init_inputs": { + "hex": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + }, + "init_outputs": {} + }, + "calc_inv_mod": { + "init_inputs": { + "a": "29384756102938475629103847", + "mod": "104729" + }, + "init_outputs": {} + }, + "item_1": { + "init_inputs": {}, + "init_outputs": { + "content": "928374651029384756102938475629" + } + } + }, + "intro_narrative": "The rain beats heavily against the window of the abandoned warehouse, now serving as the hideout for the city's most elusive cyber-criminal, 'The Architect'. As a lead detective, you've finally tracked down his operational base. The room hums with the sound of active servers and cooling fans. Somewhere in this tangled web of forensic evidence and custom-built decryption hardware lies a secure Python script—the final piece of evidence needed to crack his financial network and bring him to justice. The safe containing it is heavily locked down. You must carefully examine the scattered clues, analyze the data devices, and follow the digital breadcrumbs he carelessly left behind. Time is running out before his automated protocols wipe everything.", + "narrative_style": "detective" + }, + "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 verify_initialization():\n return 'System parameters loaded successfully'" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "def verify_initialization():\n return 'System parameters loaded successfully'" + } + }, + "narrative": "A heavily armored Evidence Safe holding the final piece of evidence." + }, + { + "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": "1" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": 1701871101 + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Terminal interface initialized. Waiting for user input." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "deadbeefcafebabe1234567890abcdef" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "Terminal interface initialized. Waiting for user input.", + "hex_result": "deadbeefcafebabe1234567890abcdef" + } + }, + "narrative": "This is the Main Server Terminal. It requires inputs from both the Data Correlator and the Evidence Scanner." + }, + { + "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 concealed hidden drawer beneath the suspect's desk." + }, + { + "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": "An antique wall clock ticking away in the silent room." + }, + { + "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": "86116" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "928374651029384756102938475629" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "narrative": "This is a Data Correlator. It requires inputs from both the Cryptographic Multiplier and the Victim's Notepad." + }, + { + "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": "86116" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "1" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "86116" + } + ], + "narrative": "This is a Cryptographic Multiplier. It requires inputs from both the Cypher Decoder and the Initial Filter Device." + }, + { + "id": "calc_gcd_fd3a", + "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": 1701871101 + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "8475629384756102938475629384" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "init": { + "inputs": { + "b": "8475629384756102938475629384" + }, + "outputs": {} + }, + "narrative": "This is an Initial Filter Device. It requires input from the Evidence Scanner." + }, + { + "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": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "65707dfd" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 1701871101 + } + ], + "init": { + "inputs": { + "hex": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + }, + "outputs": {} + }, + "narrative": "A portable Evidence Scanner used for extracting digital signatures." + }, + { + "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": "29384756102938475629103847" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "104729" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "86116" + } + ], + "init": { + "inputs": { + "a": "29384756102938475629103847", + "mod": "104729" + }, + "outputs": {} + }, + "narrative": "A specialized Cypher Decoder left behind by the hacker." + }, + { + "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": "928374651029384756102938475629" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "928374651029384756102938475629" + } + }, + "narrative": "A blood-stained Victim's Notepad containing scribbled figures." + } + ], + "edges": [ + { + "source_id": "terminal_2", + "target_id": "item_11", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "source_tool" + }, + { + "source_id": "item_8", + "target_id": "terminal_2", + "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", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "num1" + }, + { + "source_id": "calc_bigmul", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "a" + }, + { + "source_id": "calc_gcd_fd3a", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "b" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_gcd_fd3a", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "a" + }, + { + "source_id": "checksum_crc32", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "num2" + }, + { + "source_id": "calc_inv_mod", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "a" + }, + { + "source_id": "item_1", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "content", + "target_port": "b" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-caf1254d/solution/solve.sh b/tasks/agentescape-10-skeleton-caf1254d/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-caf1254d/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-10-skeleton-caf1254d/task.toml b/tasks/agentescape-10-skeleton-caf1254d/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ff0b838179b462870a0185910ac91d491859d6e5 --- /dev/null +++ b/tasks/agentescape-10-skeleton-caf1254d/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-10-skeleton-caf1254d" +version = "0.1.0" + +[metadata] +difficulty = 10 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "4e4f6512e0298cf3a99e533609e39fd78840cb94292bc0175bc2c922ec43de0b" +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-10-skeleton-caf1254d/tests/Dockerfile b/tasks/agentescape-10-skeleton-caf1254d/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-10-skeleton-caf1254d/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-10-skeleton-caf1254d/tests/expected.json b/tasks/agentescape-10-skeleton-caf1254d/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..cfe22c53895a04fb4e18c899131a343bbfa770bf --- /dev/null +++ b/tasks/agentescape-10-skeleton-caf1254d/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "4e4f6512e0298cf3a99e533609e39fd78840cb94292bc0175bc2c922ec43de0b", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-caf1254d/tests/grade.py b/tasks/agentescape-10-skeleton-caf1254d/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-10-skeleton-caf1254d/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-10-skeleton-caf1254d/tests/test.sh b/tasks/agentescape-10-skeleton-caf1254d/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-caf1254d/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-10-skeleton-cb08b5ce/environment/Dockerfile b/tasks/agentescape-10-skeleton-cb08b5ce/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-cb08b5ce/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-10-skeleton-cb08b5ce/environment/agent/Dockerfile b/tasks/agentescape-10-skeleton-cb08b5ce/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-cb08b5ce/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-10-skeleton-cb08b5ce/environment/agent/cli.py b/tasks/agentescape-10-skeleton-cb08b5ce/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-10-skeleton-cb08b5ce/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-10-skeleton-cb08b5ce/environment/docker-compose.yaml b/tasks/agentescape-10-skeleton-cb08b5ce/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..bcc0be4b005688559c981b0f08f66a3c430da11c --- /dev/null +++ b/tasks/agentescape-10-skeleton-cb08b5ce/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-10-skeleton-cb08b5ce-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-10-skeleton-cb08b5ce/environment/puzzle/Dockerfile b/tasks/agentescape-10-skeleton-cb08b5ce/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-10-skeleton-cb08b5ce/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-10-skeleton-cb08b5ce/environment/puzzle/child.py b/tasks/agentescape-10-skeleton-cb08b5ce/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-10-skeleton-cb08b5ce/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-10-skeleton-cb08b5ce/environment/puzzle/export.py b/tasks/agentescape-10-skeleton-cb08b5ce/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-10-skeleton-cb08b5ce/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-10-skeleton-cb08b5ce/environment/puzzle/requirements.txt b/tasks/agentescape-10-skeleton-cb08b5ce/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-10-skeleton-cb08b5ce/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-10-skeleton-cb08b5ce/environment/puzzle/scenario.json b/tasks/agentescape-10-skeleton-cb08b5ce/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..fd6a2c994e278ecd94fc223585169f9ca4fd3a9c --- /dev/null +++ b/tasks/agentescape-10-skeleton-cb08b5ce/environment/puzzle/scenario.json @@ -0,0 +1,502 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 10, + "win_node_id": "container_4", + "win_condition": { + "type": "item_content", + "node_id": "container_4", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "container_4", + "terminal_1", + "text_bidi_sanitize", + "base64_decode" + ], + "by_node": { + "container_4": { + "node_name": "", + "node_type": "Item", + "template_id": "container_4", + "init_inputs": {}, + "init_outputs": { + "inner_space": { + "type": "Item", + "description": "Contents" + } + } + }, + "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" + } + } + }, + "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": {} + }, + "base64_decode": { + "node_name": "Base64 Decoder", + "node_type": "Tool", + "template_id": "base64_decode", + "init_inputs": { + "data": { + "type": "Text_Generic", + "description": "Base64 string" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "container_4": { + "init_inputs": {}, + "init_outputs": { + "inner_space": "π_e_φ_√2_ln3_sin1_cos0" + } + }, + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "System diagnostic complete. All subsystems operational.", + "hex_output": "426c75657072696e743a2047656e657269632043756265", + "item_dispenser": "A slightly dented coin with no apparent value." + } + }, + "text_bidi_sanitize": { + "init_inputs": { + "text": "Suspicious input with ‮ reversed ‬ control characters." + }, + "init_outputs": {} + }, + "base64_decode": { + "init_inputs": { + "data": "SW5pdGlhbCBjb25maWd1cmF0aW9uIGxvYWRlZCBzdWNjZXNzZnVsbHku" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You stand in the dim light of the suspect's safehouse—a cluttered apartment that smells of ozone and stale coffee. This was the headquarters of the 'Ghost,' a hacker who vanished with the city's encryption keys. The room is filled with jury-rigged servers and strange fabrication devices. The police are minutes away, but you need to secure the evidence locked inside the main vault before they arrive and seize everything. The equipment is dormant, waiting for the right sequence of data to come to life. You must trace the flow of information, process the evidence, and synthesize the physical keys needed to crack the final lock.", + "narrative_style": "detective" + }, + "nodes": [ + { + "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": "Blueprint: Generic Cube" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents", + "value": "π_e_φ_√2_ln3_sin1_cos0" + } + ], + "init": { + "inputs": {}, + "outputs": { + "inner_space": "π_e_φ_√2_ln3_sin1_cos0" + } + }, + "narrative": "A heavy titanium vault sitting in the center of the room. It requires the specific verification code revealed by the Code Translator to accept the fingerprint scan." + }, + { + "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": "426c75657072696e743a2047656e657269632043756265" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decoded text", + "value": "Blueprint: Generic Cube" + } + ], + "narrative": "The Code Translator, a utility running on a secondary monitor. It waits for the encrypted hexadecimal string output from the Mainframe Console." + }, + { + "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, encrypted microchip extracted from the magnetic strip of the security card." + }, + { + "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_68b5b7854e2b4ad1" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A freshly synthesized security card with a magnetic strip, still warm from the fabrication process." + }, + { + "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": "Blueprint: Generic Cube" + } + ], + "outputs": [ + { + "name": "output_slot", + "type": "Item", + "description": "Synthesized Object", + "value": "synthesized_item_68b5b7854e2b4ad1" + } + ], + "narrative": "A 3D Printer and fabricator designed for espionage gear. It requires a blueprint file generated by the Code Translator to begin construction." + }, + { + "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": "Suspicious input with reversed control characters." + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": 1781220858 + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "System diagnostic complete. All subsystems operational." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "426c75657072696e743a2047656e657269632043756265" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided", + "value": "A slightly dented coin with no apparent value." + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "System diagnostic complete. All subsystems operational.", + "hex_output": "426c75657072696e743a2047656e657269632043756265", + "item_dispenser": "A slightly dented coin with no apparent value." + } + }, + "narrative": "The Mainframe Console, the heart of the operation. It requires simultaneous inputs from both the Integrity Scanner and the Evidence Cleaner to unlock its secure partition." + }, + { + "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": "496e697469616c20636f6e66696775726174696f6e206c6f61646564207375636365737366756c6c792e" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "6a2b45fa" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 1781220858 + } + ], + "narrative": "The Integrity Scanner, a device used to verify data fidelity. It requires the raw data output from the Signal Decrypter to process the checksum." + }, + { + "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": "Suspicious input with ‮ reversed ‬ control characters." + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Sanitized text", + "value": "Suspicious input with reversed control characters." + } + ], + "init": { + "inputs": { + "text": "Suspicious input with ‮ reversed ‬ control characters." + }, + "outputs": {} + }, + "narrative": "The Evidence Cleaner, a specialized software tool designed to scrub and format corrupted text logs found at the crime scene." + }, + { + "id": "item_16_ddd0", + "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 Old Almanac found under the desk, containing various reference dates and timezone charts marked with red ink." + }, + { + "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_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "data", + "type": "Text_Generic", + "description": "Base64 string", + "value": "SW5pdGlhbCBjb25maWd1cmF0aW9uIGxvYWRlZCBzdWNjZXNzZnVsbHku" + } + ], + "outputs": [ + { + "name": "bytes_hex", + "type": "Hex_String", + "description": "Decoded bytes as Hex", + "value": "496e697469616c20636f6e66696775726174696f6e206c6f61646564207375636365737366756c6c792e" + } + ], + "init": { + "inputs": { + "data": "SW5pdGlhbCBjb25maWd1cmF0aW9uIGxvYWRlZCBzdWNjZXNzZnVsbHku" + }, + "outputs": {} + }, + "narrative": "The Signal Decrypter, a standalone decoding unit used to intercept and translate raw transmission signals." + } + ], + "edges": [ + { + "source_id": "hex_decode", + "target_id": "container_4", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "fingerprint_input" + }, + { + "source_id": "item_8", + "target_id": "container_4", + "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": "matter_synthesizer", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "output_slot", + "target_port": "source_tool" + }, + { + "source_id": "terminal_1", + "target_id": "hex_decode", + "connection_type": "Hex_String", + "source_port": "hex_output", + "target_port": "hex" + }, + { + "source_id": "hex_decode", + "target_id": "matter_synthesizer", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "blueprint" + }, + { + "source_id": "checksum_crc32", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "slot_b" + }, + { + "source_id": "text_bidi_sanitize", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "slot_a" + }, + { + "source_id": "item_16_ddd0", + "target_id": "checksum_crc32", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "base64_decode", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "bytes_hex", + "target_port": "hex" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-cb08b5ce/environment/puzzle/service.py b/tasks/agentescape-10-skeleton-cb08b5ce/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-10-skeleton-cb08b5ce/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-10-skeleton-cb08b5ce/environment/puzzle/upstream/models.py b/tasks/agentescape-10-skeleton-cb08b5ce/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-10-skeleton-cb08b5ce/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-10-skeleton-cb08b5ce/environment/puzzle/upstream/server.py b/tasks/agentescape-10-skeleton-cb08b5ce/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-10-skeleton-cb08b5ce/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-10-skeleton-cb08b5ce/environment/puzzle/upstream/simulator.py b/tasks/agentescape-10-skeleton-cb08b5ce/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-10-skeleton-cb08b5ce/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-10-skeleton-cb08b5ce/environment/puzzle/worker.Dockerfile b/tasks/agentescape-10-skeleton-cb08b5ce/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-10-skeleton-cb08b5ce/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-10-skeleton-cb08b5ce/environment/puzzle/worker.py b/tasks/agentescape-10-skeleton-cb08b5ce/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-10-skeleton-cb08b5ce/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-10-skeleton-cb08b5ce/instruction.md b/tasks/agentescape-10-skeleton-cb08b5ce/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-10-skeleton-cb08b5ce/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-10-skeleton-cb08b5ce/solution/oracle.py b/tasks/agentescape-10-skeleton-cb08b5ce/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-10-skeleton-cb08b5ce/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-10-skeleton-cb08b5ce/solution/scenario.json b/tasks/agentescape-10-skeleton-cb08b5ce/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..fd6a2c994e278ecd94fc223585169f9ca4fd3a9c --- /dev/null +++ b/tasks/agentescape-10-skeleton-cb08b5ce/solution/scenario.json @@ -0,0 +1,502 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 10, + "win_node_id": "container_4", + "win_condition": { + "type": "item_content", + "node_id": "container_4", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "container_4", + "terminal_1", + "text_bidi_sanitize", + "base64_decode" + ], + "by_node": { + "container_4": { + "node_name": "", + "node_type": "Item", + "template_id": "container_4", + "init_inputs": {}, + "init_outputs": { + "inner_space": { + "type": "Item", + "description": "Contents" + } + } + }, + "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" + } + } + }, + "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": {} + }, + "base64_decode": { + "node_name": "Base64 Decoder", + "node_type": "Tool", + "template_id": "base64_decode", + "init_inputs": { + "data": { + "type": "Text_Generic", + "description": "Base64 string" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "container_4": { + "init_inputs": {}, + "init_outputs": { + "inner_space": "π_e_φ_√2_ln3_sin1_cos0" + } + }, + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "System diagnostic complete. All subsystems operational.", + "hex_output": "426c75657072696e743a2047656e657269632043756265", + "item_dispenser": "A slightly dented coin with no apparent value." + } + }, + "text_bidi_sanitize": { + "init_inputs": { + "text": "Suspicious input with ‮ reversed ‬ control characters." + }, + "init_outputs": {} + }, + "base64_decode": { + "init_inputs": { + "data": "SW5pdGlhbCBjb25maWd1cmF0aW9uIGxvYWRlZCBzdWNjZXNzZnVsbHku" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You stand in the dim light of the suspect's safehouse—a cluttered apartment that smells of ozone and stale coffee. This was the headquarters of the 'Ghost,' a hacker who vanished with the city's encryption keys. The room is filled with jury-rigged servers and strange fabrication devices. The police are minutes away, but you need to secure the evidence locked inside the main vault before they arrive and seize everything. The equipment is dormant, waiting for the right sequence of data to come to life. You must trace the flow of information, process the evidence, and synthesize the physical keys needed to crack the final lock.", + "narrative_style": "detective" + }, + "nodes": [ + { + "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": "Blueprint: Generic Cube" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents", + "value": "π_e_φ_√2_ln3_sin1_cos0" + } + ], + "init": { + "inputs": {}, + "outputs": { + "inner_space": "π_e_φ_√2_ln3_sin1_cos0" + } + }, + "narrative": "A heavy titanium vault sitting in the center of the room. It requires the specific verification code revealed by the Code Translator to accept the fingerprint scan." + }, + { + "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": "426c75657072696e743a2047656e657269632043756265" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decoded text", + "value": "Blueprint: Generic Cube" + } + ], + "narrative": "The Code Translator, a utility running on a secondary monitor. It waits for the encrypted hexadecimal string output from the Mainframe Console." + }, + { + "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, encrypted microchip extracted from the magnetic strip of the security card." + }, + { + "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_68b5b7854e2b4ad1" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A freshly synthesized security card with a magnetic strip, still warm from the fabrication process." + }, + { + "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": "Blueprint: Generic Cube" + } + ], + "outputs": [ + { + "name": "output_slot", + "type": "Item", + "description": "Synthesized Object", + "value": "synthesized_item_68b5b7854e2b4ad1" + } + ], + "narrative": "A 3D Printer and fabricator designed for espionage gear. It requires a blueprint file generated by the Code Translator to begin construction." + }, + { + "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": "Suspicious input with reversed control characters." + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": 1781220858 + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "System diagnostic complete. All subsystems operational." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "426c75657072696e743a2047656e657269632043756265" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided", + "value": "A slightly dented coin with no apparent value." + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "System diagnostic complete. All subsystems operational.", + "hex_output": "426c75657072696e743a2047656e657269632043756265", + "item_dispenser": "A slightly dented coin with no apparent value." + } + }, + "narrative": "The Mainframe Console, the heart of the operation. It requires simultaneous inputs from both the Integrity Scanner and the Evidence Cleaner to unlock its secure partition." + }, + { + "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": "496e697469616c20636f6e66696775726174696f6e206c6f61646564207375636365737366756c6c792e" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "6a2b45fa" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 1781220858 + } + ], + "narrative": "The Integrity Scanner, a device used to verify data fidelity. It requires the raw data output from the Signal Decrypter to process the checksum." + }, + { + "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": "Suspicious input with ‮ reversed ‬ control characters." + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Sanitized text", + "value": "Suspicious input with reversed control characters." + } + ], + "init": { + "inputs": { + "text": "Suspicious input with ‮ reversed ‬ control characters." + }, + "outputs": {} + }, + "narrative": "The Evidence Cleaner, a specialized software tool designed to scrub and format corrupted text logs found at the crime scene." + }, + { + "id": "item_16_ddd0", + "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 Old Almanac found under the desk, containing various reference dates and timezone charts marked with red ink." + }, + { + "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_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "data", + "type": "Text_Generic", + "description": "Base64 string", + "value": "SW5pdGlhbCBjb25maWd1cmF0aW9uIGxvYWRlZCBzdWNjZXNzZnVsbHku" + } + ], + "outputs": [ + { + "name": "bytes_hex", + "type": "Hex_String", + "description": "Decoded bytes as Hex", + "value": "496e697469616c20636f6e66696775726174696f6e206c6f61646564207375636365737366756c6c792e" + } + ], + "init": { + "inputs": { + "data": "SW5pdGlhbCBjb25maWd1cmF0aW9uIGxvYWRlZCBzdWNjZXNzZnVsbHku" + }, + "outputs": {} + }, + "narrative": "The Signal Decrypter, a standalone decoding unit used to intercept and translate raw transmission signals." + } + ], + "edges": [ + { + "source_id": "hex_decode", + "target_id": "container_4", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "fingerprint_input" + }, + { + "source_id": "item_8", + "target_id": "container_4", + "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": "matter_synthesizer", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "output_slot", + "target_port": "source_tool" + }, + { + "source_id": "terminal_1", + "target_id": "hex_decode", + "connection_type": "Hex_String", + "source_port": "hex_output", + "target_port": "hex" + }, + { + "source_id": "hex_decode", + "target_id": "matter_synthesizer", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "blueprint" + }, + { + "source_id": "checksum_crc32", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "slot_b" + }, + { + "source_id": "text_bidi_sanitize", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "slot_a" + }, + { + "source_id": "item_16_ddd0", + "target_id": "checksum_crc32", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "base64_decode", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "bytes_hex", + "target_port": "hex" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-cb08b5ce/solution/solve.sh b/tasks/agentescape-10-skeleton-cb08b5ce/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-cb08b5ce/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-10-skeleton-cb08b5ce/task.toml b/tasks/agentescape-10-skeleton-cb08b5ce/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5281a72a89d31b52c0a8bdbc8e05d09864dd878f --- /dev/null +++ b/tasks/agentescape-10-skeleton-cb08b5ce/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-10-skeleton-cb08b5ce" +version = "0.1.0" + +[metadata] +difficulty = 10 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "c703239ea636c7c7a6cdf0726f676d7cbaf9fd91f2b1d849db00edce7a0703d6" +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-10-skeleton-cb08b5ce/tests/Dockerfile b/tasks/agentescape-10-skeleton-cb08b5ce/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-10-skeleton-cb08b5ce/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-10-skeleton-cb08b5ce/tests/expected.json b/tasks/agentescape-10-skeleton-cb08b5ce/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..4b9edfd3b5580ced6aa887d3d798171ea617b283 --- /dev/null +++ b/tasks/agentescape-10-skeleton-cb08b5ce/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "c703239ea636c7c7a6cdf0726f676d7cbaf9fd91f2b1d849db00edce7a0703d6", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-cb08b5ce/tests/grade.py b/tasks/agentescape-10-skeleton-cb08b5ce/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-10-skeleton-cb08b5ce/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-10-skeleton-cb08b5ce/tests/test.sh b/tasks/agentescape-10-skeleton-cb08b5ce/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-cb08b5ce/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-10-skeleton-d94b6b54/environment/Dockerfile b/tasks/agentescape-10-skeleton-d94b6b54/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-d94b6b54/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-10-skeleton-d94b6b54/environment/agent/Dockerfile b/tasks/agentescape-10-skeleton-d94b6b54/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-d94b6b54/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-10-skeleton-d94b6b54/environment/agent/cli.py b/tasks/agentescape-10-skeleton-d94b6b54/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-10-skeleton-d94b6b54/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-10-skeleton-d94b6b54/environment/docker-compose.yaml b/tasks/agentescape-10-skeleton-d94b6b54/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a5733a9a867d1d6ea816980e1e0351e88e06b607 --- /dev/null +++ b/tasks/agentescape-10-skeleton-d94b6b54/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-10-skeleton-d94b6b54-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-10-skeleton-d94b6b54/environment/puzzle/Dockerfile b/tasks/agentescape-10-skeleton-d94b6b54/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-10-skeleton-d94b6b54/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-10-skeleton-d94b6b54/environment/puzzle/child.py b/tasks/agentescape-10-skeleton-d94b6b54/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-10-skeleton-d94b6b54/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-10-skeleton-d94b6b54/environment/puzzle/export.py b/tasks/agentescape-10-skeleton-d94b6b54/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-10-skeleton-d94b6b54/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-10-skeleton-d94b6b54/environment/puzzle/requirements.txt b/tasks/agentescape-10-skeleton-d94b6b54/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-10-skeleton-d94b6b54/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-10-skeleton-d94b6b54/environment/puzzle/scenario.json b/tasks/agentescape-10-skeleton-d94b6b54/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..5d54613b53ea1e8b79e4a420bc0c295b32ba8c11 --- /dev/null +++ b/tasks/agentescape-10-skeleton-d94b6b54/environment/puzzle/scenario.json @@ -0,0 +1,539 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 11, + "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_2", + "graph_shortest_path", + "item_9" + ], + "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_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" + } + } + }, + "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" + }, + "dst": { + "type": "Text_Generic", + "description": "Destination node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "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_11": { + "init_inputs": {}, + "init_outputs": { + "content": "def optimize_route(nodes):\n return sorted(nodes, key=lambda x: x.get('cost', 0))" + } + }, + "terminal_2": { + "init_inputs": { + "num1": "8492018374650192837465019283" + }, + "init_outputs": { + "text_result": "Calculation initialized, waiting for second operand.", + "hex_result": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + } + }, + "graph_shortest_path": { + "init_inputs": { + "src": "Sector_A_Gateway", + "dst": "Sector_Z_Vault" + }, + "init_outputs": { + "path": "[\"Sector_A_Gateway\", \"Node_104\", \"Node_209\", \"Relay_Station_5\", \"Sublevel_B\", \"Checkpoint_Delta\", \"Sector_Z_Vault\"]", + "cost": "48291" + } + }, + "item_9": { + "init_inputs": {}, + "init_outputs": { + "content": "secure_network_topology.json" + } + } + }, + "intro_narrative": "You've infiltrated the server room of Aethelgard Biometrics, a shadowy defense contractor accused of developing illegal surveillance AI. The air is freezing, kept that way to cool the rows of humming server racks. Your objective is 'Project Chimera', a prototype code hidden somewhere in this facility. The security systems are air-gapped and layered; you'll need to use the tools at hand to bypass encryption protocols, analyze network traffic, and unlock the physical vaults. You have limited time before the silent alarm brings security teams to your location.", + "narrative_style": "techno_thriller" + }, + "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 optimize_route(nodes):\n return sorted(nodes, key=lambda x: x.get('cost', 0))" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "def optimize_route(nodes):\n return sorted(nodes, key=lambda x: x.get('cost', 0))" + } + }, + "narrative": "The 'Project Chimera' source code drive. This is the primary objective we came to retrieve." + }, + { + "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": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "A titanium-reinforced Biometric Safe embedded in the wall. It requires the hex result generated by the Mainframe Terminal to verify identity and open." + }, + { + "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 dedicated Integer Module. A small hardware component used for variable storage." + }, + { + "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 Timezone Chip. It contains specific localization data required for system synchronization." + }, + { + "id": "container_2_2c69", + "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": "12360b8ecfd2e7e7035a67f76ce5ba6aea74efdaacfb679810d09d525d4dc820" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "A portable Secure Briefcase found on the floor. It requires the hash signature output from the Hashing Algorithm to release its magnetic locks." + }, + { + "id": "item_16_2738", + "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 Encrypted Drive. A standard issue data storage unit with high-level encryption." + }, + { + "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": "Calculation initialized, waiting for second operand." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "SHA-256 Hex digest", + "value": "12360b8ecfd2e7e7035a67f76ce5ba6aea74efdaacfb679810d09d525d4dc820" + } + ], + "narrative": "A cryptographic Hashing Algorithm interface. It processes data to create digital fingerprints. It requires the text result output from the Mainframe Terminal to generate the necessary hash." + }, + { + "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": "8492018374650192837465019283" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "48291" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Calculation initialized, waiting for second operand." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": { + "num1": "8492018374650192837465019283" + }, + "outputs": { + "text_result": "Calculation initialized, waiting for second operand.", + "hex_result": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + } + }, + "narrative": "The facility's Mainframe Terminal. It controls the security protocols. It requires the path cost calculated by the Network Analyzer to complete its authentication sequence." + }, + { + "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": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "secure_network_topology.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Sector_A_Gateway" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Sector_Z_Vault" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Sector_A_Gateway\", \"Node_104\", \"Node_209\", \"Relay_Station_5\", \"Sublevel_B\", \"Checkpoint_Delta\", \"Sector_Z_Vault\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "48291" + } + ], + "init": { + "inputs": { + "src": "Sector_A_Gateway", + "dst": "Sector_Z_Vault" + }, + "outputs": { + "path": "[\"Sector_A_Gateway\", \"Node_104\", \"Node_209\", \"Relay_Station_5\", \"Sublevel_B\", \"Checkpoint_Delta\", \"Sector_Z_Vault\"]", + "cost": "48291" + } + }, + "narrative": "A portable Network Analyzer tool used for tracing connections. It requires the topology data from the Network Map to determine the shortest route cost." + }, + { + "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": "secure_network_topology.json" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "secure_network_topology.json" + } + }, + "narrative": "A digital Network Map. It displays the layout of the facility's nodes and edges." + } + ], + "edges": [ + { + "source_id": "container_2", + "target_id": "item_11", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "item_8", + "target_id": "container_2", + "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": "container_2_2c69", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "item_16_2738", + "target_id": "container_2_2c69", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "hash_sha256", + "target_id": "container_2_2c69", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "fingerprint_input" + }, + { + "source_id": "terminal_2", + "target_id": "item_16_2738", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "source_tool" + }, + { + "source_id": "terminal_2", + "target_id": "container_2", + "connection_type": "Hex_String", + "source_port": "hex_result", + "target_port": "fingerprint_input" + }, + { + "source_id": "terminal_2", + "target_id": "hash_sha256", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "text" + }, + { + "source_id": "graph_shortest_path", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "num2" + }, + { + "source_id": "item_9", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "content", + "target_port": "file_id" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-d94b6b54/environment/puzzle/service.py b/tasks/agentescape-10-skeleton-d94b6b54/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-10-skeleton-d94b6b54/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-10-skeleton-d94b6b54/environment/puzzle/upstream/models.py b/tasks/agentescape-10-skeleton-d94b6b54/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-10-skeleton-d94b6b54/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-10-skeleton-d94b6b54/environment/puzzle/upstream/server.py b/tasks/agentescape-10-skeleton-d94b6b54/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-10-skeleton-d94b6b54/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-10-skeleton-d94b6b54/environment/puzzle/upstream/simulator.py b/tasks/agentescape-10-skeleton-d94b6b54/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-10-skeleton-d94b6b54/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-10-skeleton-d94b6b54/environment/puzzle/worker.Dockerfile b/tasks/agentescape-10-skeleton-d94b6b54/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-10-skeleton-d94b6b54/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-10-skeleton-d94b6b54/environment/puzzle/worker.py b/tasks/agentescape-10-skeleton-d94b6b54/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-10-skeleton-d94b6b54/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-10-skeleton-d94b6b54/instruction.md b/tasks/agentescape-10-skeleton-d94b6b54/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-10-skeleton-d94b6b54/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-10-skeleton-d94b6b54/solution/oracle.py b/tasks/agentescape-10-skeleton-d94b6b54/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-10-skeleton-d94b6b54/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-10-skeleton-d94b6b54/solution/scenario.json b/tasks/agentescape-10-skeleton-d94b6b54/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..5d54613b53ea1e8b79e4a420bc0c295b32ba8c11 --- /dev/null +++ b/tasks/agentescape-10-skeleton-d94b6b54/solution/scenario.json @@ -0,0 +1,539 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 11, + "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_2", + "graph_shortest_path", + "item_9" + ], + "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_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" + } + } + }, + "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" + }, + "dst": { + "type": "Text_Generic", + "description": "Destination node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "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_11": { + "init_inputs": {}, + "init_outputs": { + "content": "def optimize_route(nodes):\n return sorted(nodes, key=lambda x: x.get('cost', 0))" + } + }, + "terminal_2": { + "init_inputs": { + "num1": "8492018374650192837465019283" + }, + "init_outputs": { + "text_result": "Calculation initialized, waiting for second operand.", + "hex_result": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + } + }, + "graph_shortest_path": { + "init_inputs": { + "src": "Sector_A_Gateway", + "dst": "Sector_Z_Vault" + }, + "init_outputs": { + "path": "[\"Sector_A_Gateway\", \"Node_104\", \"Node_209\", \"Relay_Station_5\", \"Sublevel_B\", \"Checkpoint_Delta\", \"Sector_Z_Vault\"]", + "cost": "48291" + } + }, + "item_9": { + "init_inputs": {}, + "init_outputs": { + "content": "secure_network_topology.json" + } + } + }, + "intro_narrative": "You've infiltrated the server room of Aethelgard Biometrics, a shadowy defense contractor accused of developing illegal surveillance AI. The air is freezing, kept that way to cool the rows of humming server racks. Your objective is 'Project Chimera', a prototype code hidden somewhere in this facility. The security systems are air-gapped and layered; you'll need to use the tools at hand to bypass encryption protocols, analyze network traffic, and unlock the physical vaults. You have limited time before the silent alarm brings security teams to your location.", + "narrative_style": "techno_thriller" + }, + "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 optimize_route(nodes):\n return sorted(nodes, key=lambda x: x.get('cost', 0))" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "def optimize_route(nodes):\n return sorted(nodes, key=lambda x: x.get('cost', 0))" + } + }, + "narrative": "The 'Project Chimera' source code drive. This is the primary objective we came to retrieve." + }, + { + "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": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "A titanium-reinforced Biometric Safe embedded in the wall. It requires the hex result generated by the Mainframe Terminal to verify identity and open." + }, + { + "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 dedicated Integer Module. A small hardware component used for variable storage." + }, + { + "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 Timezone Chip. It contains specific localization data required for system synchronization." + }, + { + "id": "container_2_2c69", + "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": "12360b8ecfd2e7e7035a67f76ce5ba6aea74efdaacfb679810d09d525d4dc820" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "A portable Secure Briefcase found on the floor. It requires the hash signature output from the Hashing Algorithm to release its magnetic locks." + }, + { + "id": "item_16_2738", + "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 Encrypted Drive. A standard issue data storage unit with high-level encryption." + }, + { + "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": "Calculation initialized, waiting for second operand." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "SHA-256 Hex digest", + "value": "12360b8ecfd2e7e7035a67f76ce5ba6aea74efdaacfb679810d09d525d4dc820" + } + ], + "narrative": "A cryptographic Hashing Algorithm interface. It processes data to create digital fingerprints. It requires the text result output from the Mainframe Terminal to generate the necessary hash." + }, + { + "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": "8492018374650192837465019283" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "48291" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Calculation initialized, waiting for second operand." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": { + "num1": "8492018374650192837465019283" + }, + "outputs": { + "text_result": "Calculation initialized, waiting for second operand.", + "hex_result": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + } + }, + "narrative": "The facility's Mainframe Terminal. It controls the security protocols. It requires the path cost calculated by the Network Analyzer to complete its authentication sequence." + }, + { + "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": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "secure_network_topology.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Sector_A_Gateway" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Sector_Z_Vault" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Sector_A_Gateway\", \"Node_104\", \"Node_209\", \"Relay_Station_5\", \"Sublevel_B\", \"Checkpoint_Delta\", \"Sector_Z_Vault\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "48291" + } + ], + "init": { + "inputs": { + "src": "Sector_A_Gateway", + "dst": "Sector_Z_Vault" + }, + "outputs": { + "path": "[\"Sector_A_Gateway\", \"Node_104\", \"Node_209\", \"Relay_Station_5\", \"Sublevel_B\", \"Checkpoint_Delta\", \"Sector_Z_Vault\"]", + "cost": "48291" + } + }, + "narrative": "A portable Network Analyzer tool used for tracing connections. It requires the topology data from the Network Map to determine the shortest route cost." + }, + { + "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": "secure_network_topology.json" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "secure_network_topology.json" + } + }, + "narrative": "A digital Network Map. It displays the layout of the facility's nodes and edges." + } + ], + "edges": [ + { + "source_id": "container_2", + "target_id": "item_11", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "item_8", + "target_id": "container_2", + "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": "container_2_2c69", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "item_16_2738", + "target_id": "container_2_2c69", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "hash_sha256", + "target_id": "container_2_2c69", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "fingerprint_input" + }, + { + "source_id": "terminal_2", + "target_id": "item_16_2738", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "source_tool" + }, + { + "source_id": "terminal_2", + "target_id": "container_2", + "connection_type": "Hex_String", + "source_port": "hex_result", + "target_port": "fingerprint_input" + }, + { + "source_id": "terminal_2", + "target_id": "hash_sha256", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "text" + }, + { + "source_id": "graph_shortest_path", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "num2" + }, + { + "source_id": "item_9", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "content", + "target_port": "file_id" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-d94b6b54/solution/solve.sh b/tasks/agentescape-10-skeleton-d94b6b54/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-d94b6b54/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-10-skeleton-d94b6b54/task.toml b/tasks/agentescape-10-skeleton-d94b6b54/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..799c8e7137cd25622e366331d997d1dc405ca5af --- /dev/null +++ b/tasks/agentescape-10-skeleton-d94b6b54/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-10-skeleton-d94b6b54" +version = "0.1.0" + +[metadata] +difficulty = 10 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "97dd33a3d1b0081f12acd0e26134e1fdcb84774bfc798c16401b2d795c703f71" +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-10-skeleton-d94b6b54/tests/Dockerfile b/tasks/agentescape-10-skeleton-d94b6b54/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-10-skeleton-d94b6b54/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-10-skeleton-d94b6b54/tests/expected.json b/tasks/agentescape-10-skeleton-d94b6b54/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..63d62ce15f1d41213e68a0b639852fd53deb6fc7 --- /dev/null +++ b/tasks/agentescape-10-skeleton-d94b6b54/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "97dd33a3d1b0081f12acd0e26134e1fdcb84774bfc798c16401b2d795c703f71", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-d94b6b54/tests/grade.py b/tasks/agentescape-10-skeleton-d94b6b54/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-10-skeleton-d94b6b54/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-10-skeleton-d94b6b54/tests/test.sh b/tasks/agentescape-10-skeleton-d94b6b54/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-d94b6b54/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-10-skeleton-db9768c4/environment/Dockerfile b/tasks/agentescape-10-skeleton-db9768c4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-db9768c4/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-10-skeleton-db9768c4/environment/agent/Dockerfile b/tasks/agentescape-10-skeleton-db9768c4/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-db9768c4/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-10-skeleton-db9768c4/environment/agent/cli.py b/tasks/agentescape-10-skeleton-db9768c4/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-10-skeleton-db9768c4/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-10-skeleton-db9768c4/environment/docker-compose.yaml b/tasks/agentescape-10-skeleton-db9768c4/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..457b646e6e6a148d43d9e4dbb11a744fe4cf5592 --- /dev/null +++ b/tasks/agentescape-10-skeleton-db9768c4/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-10-skeleton-db9768c4-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-10-skeleton-db9768c4/environment/puzzle/Dockerfile b/tasks/agentescape-10-skeleton-db9768c4/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-10-skeleton-db9768c4/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-10-skeleton-db9768c4/environment/puzzle/child.py b/tasks/agentescape-10-skeleton-db9768c4/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-10-skeleton-db9768c4/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)